How to stop the Background running service in android? - android

Intent svc=new Intent(BeapSoundActivity.this, BackgroundService.class);
pendingIntent = PendingIntent.getService(BeapSoundActivity.this, 0, svc, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
I am using the above code to start my service in mt onCreate(),
I just want to stop this service when I click a Button to change my Activity
I used this line in my Button Click
stopService(new Intent(BeapSoundActivity.this, BackgroundService.class));
But it didnt worked for me
Here is my BackGroundService class
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
public class BackgroundService extends Service{
// private static final String TAG = null;
// MediaPlayer player;
MediaPlayer mMediaPlayer;
String strResponse;
int i=0;
static {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
mMediaPlayer = new MediaPlayer();
Log.e("Oncreate","oncreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
// player.start();
Log.e("Onstartcommand","onstartcommand");
pendingCount();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
// super.onStart(intent,startId);
Log.e("Onstart","onstart");
// pendingCount();
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
// player.stop();
// player.release();
}
#Override
public void onLowMemory() {
}
public void playSound(Context context) throws IllegalArgumentException, SecurityException, IllegalStateException,
IOException {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(context, soundUri);
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
public void pendingCount(){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://mybusinessapp2.testshell.net/api/Orders");
post.addHeader("UserName", "info#mybusinessapp.com");
post.addHeader("Password", "c7d7cdf598be88a21a477842ebfa5ca5");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String post_response = null;
try {
post_response = httpClient.execute(post,resHandler);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("resp",post_response);
try{
JSONObject jobject=new JSONObject(post_response);
strResponse= jobject.getString("Count");
}
catch(Exception e){
e.printStackTrace();
}
Log.e("tv",""+BeapSoundActivity. pending_number);
try{
BeapSoundActivity. pending_number.setText(strResponse);
// int pending=Integer.parseInt(BeapSoundActivity.pending_number.getText().toString());
// Log.e("counter",""+pending);
}
catch(NullPointerException e){
e.printStackTrace();
}
int pending=Integer.parseInt( strResponse);
if(pending==0){
mMediaPlayer.stop();
mMediaPlayer = new MediaPlayer();
}
if(pending>0){
try {
playSound(BackgroundService.this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Please help me in solving this issue
Thanks in advance

you created an alarm that start your service every 10 seconds. did you canceled it before stopping the service? (if not, use (AlarmManager)getSystemService(Context.ALARM_SERVICE).cancel)

Related

Android music player as a Service and show the title track,album image on UI

I tried to write the music player code in android.I want to show the current title of the song,artist and album image.
The Activity is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.PlayMusicService.LocalBinder;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GetMusic extends Activity implements OnGestureListener {
static Handler seekhandler=new Handler();
boolean isServiceConnected=false;
PlayMusicService playServ;
static TextView tv1,tv2,tv3;
Button previous,next;static ImageView img;static GestureDetector gDetector;
int pausePressed=1;static SeekBar sb;
int currentIndex=0;Cursor cursor;GenericSongClass GSC;
static MediaPlayer mediaPlayer;static int posofaudiotrack;
private ServiceConnection conn=new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isServiceConnected=false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder=(LocalBinder)service;
playServ=binder.getService();
isServiceConnected=true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_music);
gDetector= new GestureDetector(this);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
tv3=(TextView)findViewById(R.id.textView3);
getSongs();
img=(ImageView)findViewById(R.id.imageView1);
sb=(SeekBar)findViewById(R.id.seekBar1);
try{
Intent serv = new Intent(this,PlayMusicService.class);
bindService(serv, conn, Context.BIND_AUTO_CREATE);
System.out.println("in try calling service");
startService(serv);
}
catch(Exception e){
System.out.println("Exception is"+e);
}
System.out.println("after binding");
/*
try {
playSong(0);
}
catch(Exception e){
System.out.println("Exception is"+e);
}*/
//PlayMusic p=new PlayMusic();
// p.execute();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isServiceConnected) {
unbindService(conn);
isServiceConnected = false;
}
}
public static void mediaPlayerPause()
{
if(mediaPlayer!=null)
{
mediaPlayer.pause();
posofaudiotrack=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mediaPlayer!=null&&!mediaPlayer.isPlaying())
{
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
}
public class PlayMusic extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getSongs();
return null;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public static ArrayList<GenericSongClass> songs = null;
public void getSongs() {
Toast.makeText(getApplicationContext(), "in BindAllSongs()", Toast.LENGTH_SHORT).show();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.COMPOSER,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ALBUM
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = getBaseContext().getContentResolver().query(uri,
projection, selection, null, sortOrder);
/* int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String s=cursor.getString(column_index);*/
// Toast.makeText(getApplicationContext(), "path is"+s, Toast.LENGTH_SHORT).show();
// System.out.println("path is"+s);
if (null == cursor) {
Log.e("error","cursor is null");
// If the Cursor is empty, the provider found no matches
} else if (cursor.getCount() < 1) {
Log.i("info","cursor count<1");
} else {
songs = new ArrayList<GenericSongClass>(cursor.getCount());
cursor.moveToFirst();
int colIndex=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = cursor.getString(colIndex);
// Toast.makeText(getApplicationContext(), "PATH IS"+path, Toast.LENGTH_SHORT).show();
System.out.println("PATH IS"+path);
while (!cursor.isAfterLast()) {
GSC = new GenericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songComposer=cursor.getString(3);
GSC.title=cursor.getString(4);
GSC.album=cursor.getString(5);
songs.add(GSC);
cursor.moveToNext();
}
// Toast.makeText(getApplicationContext(), "songs first is"+songs.get(0).songTitle, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "songs length is"+songs.size(), Toast.LENGTH_SHORT).show();
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.e("I", "Media player has been loaded to memory !");
}
});
/*for(int i=0;i<songs.size();i++){
if(mediaPlayer.isPlaying())
mediaPlayer.reset();
String p=songs.get(i).songData;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "exception is"+ex, Toast.LENGTH_SHORT).show();
Log.i("ex is",ex.toString());
} finally {
if (cursor != null) {
cursor.close();
}}
}
protected void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
protected void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
private void playSong(int index) {
// TODO Auto-generated method stub
try{
mediaPlayer.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tv1.setText(songs.get(index).title);
tv2.setText(songs.get(index).album);
tv3.setText(songs.get(index).songArtist);
// tv3.append(songs.get(index).album);
mediaPlayer.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mediaPlayer.start();
sb.setMax(mediaPlayer.getDuration());
seekUpdation();
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
mediaPlayer.seekTo(seekBar.getProgress());
seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
playServ.getNextSong();
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
sb.setProgress(mediaPlayer.getCurrentPosition());
seekhandler.postDelayed(run, 1000);
}
public class GenericSongClass {
String songTitle = "";
String songArtist = "";
String songData = "";
String songComposer="";
String title="";
String album="";
String isChecked = "false";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_music, menu);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float velocityX,
float velocityY) {
pausePressed=1;//int x=playServ.getCurrentIndex();
// TODO Auto-generated method stub
if(start.getRawX() < finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "chanegd", Toast.LENGTH_SHORT).show();
if(playServ!=null){
/* if(x==0)
x=songs.size()-1;
else{
x=currentIndex-1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getPreviousSong();}
else
System.out.println("ms null");
}
else if(start.getRawX()>finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "changed on other", Toast.LENGTH_SHORT).show();
Log.d("onFLing","in onFling");
if(playServ!=null){
/*
if(x == songs.size()-1){
x=0;
}
else
{
x=x+1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getNextSong();
}
else
System.out.println("ms null");
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
System.out.println("PAUSEPRESSED"+pausePressed);
if(pausePressed==1){
pausePressed=0;
playServ.mediaPlayerPause();
}else if(pausePressed==0){
pausePressed=1;
//mediaPlayer.seekTo(posofaudiotrack);
playServ.mediaPlayerResume();
}
return true;
}
}
and the Service is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.GetMusic.GenericSongClass;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class PlayMusicService extends Service{
MediaPlayer mp;int currentIndex=0;
ArrayList<GenericSongClass> songs=GetMusic.songs;int pausePressed=1;
IBinder servbind=new LocalBinder();
public class LocalBinder extends Binder{
PlayMusicService getService()
{
return PlayMusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return servbind;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mp=new MediaPlayer();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
System.out.println("in onPrepared");
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
getNextSong();
}
});
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
System.out.println("in try");
playSong(0);
}
catch(Exception e){
System.out.println("in catch and exception is "+e.getMessage());
}
}
public void playSong(int index){
// TODO Auto-generated method stub
try{
System.out.println("in playsong");
mp.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
GetMusic.tv1.setText(songs.get(index).title);
GetMusic.tv2.setText(songs.get(index).album);
GetMusic.tv3.setText(songs.get(index).songArtist);
GetMusic.tv3.append(songs.get(index).album);
mp.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
GetMusic.img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mp.start();
GetMusic.sb.setMax(mp.getDuration());
seekUpdation();
GetMusic.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
mp.seekTo(seekBar.getProgress());
GetMusic.seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
GetMusic.sb.setProgress(mp.getCurrentPosition());
GetMusic.seekhandler.postDelayed(run, 1000);
}
public int getCurrentIndex(){
return currentIndex;
}
public void mediaPlayerPause()
{
if(mp!=null)
{
mp.pause();
//pos=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mp!=null&&!mp.isPlaying())
{
mp.seekTo(mp.getCurrentPosition());
mp.start();
}
}
public void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
public void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.start();
return 0;
}
#Override
public void onDestroy()
{
mp.release();
super.onDestroy();
}
}
The issue is it's playing good sometimes and sometimes it's stopping when we press back button or swiping other apps on home screen.I want to show the title track,image on UI.But with this code it's showing wrong images for some songs and for some it's even not showing the image even if the image exists.And after back screen pressed and so when we use other apps and get back to this It's showing simply TextView and normal android image.Is recreation of activity needed?Can we call Activity method from Service?How to solve the issues?Please help me.
You need background music service and communicate with Activity with message or bond activity to service, not call Activity method from service, that will cause cross process problem.
I actually opensource a Music Player with Background service, Lyric, from a business project I have wrote, you check this out:https://github.com/Wangchao0721/MusicPlayer
But I haven't got time to fill Readme for it, just check MediaPlayerActivity.java in activity package, you gonna know how to use this.

Open video file from File Explorer and playing in my videoplayer activity

I have my VideoPlayerActivity.java and I want to open when I press on a video file from my sdcard through my file explore or another application
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;
public class VideoPlayerActivity extends Activity implements OnErrorListener, OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
MediaPlayerControl, SurfaceHolder.Callback, VideoControllerView.MediaPlayerControl, Runnable {
private static final String TAG = "Player";
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
VideoControllerView controller;
private int position;
private String videoPath;
int videoWidth, videoHeight;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video_player);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
videoPath = getIntent().getStringExtra("videoPath");
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
controller = new VideoControllerView(this);
try {
// String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
/* final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mediaPlayer != null) {
mediaPlayer.start();
return;
}
current = path;*/
// Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 166);
// Uri uri = MediaStore.Files.getContentUri("external");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.prepareAsync();
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
Intent intent = new Intent();
intent.setClass(VideoPlayerActivity.this, MainActivity.class);
startActivity(intent);
}
});
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoPath);
mediaPlayer.prepare();
Log.v(TAG, "Duration: ===>" + mediaPlayer.getDuration());
mediaPlayer.start();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
} /*catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}*/
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
private final Handler handler = new Handler (){
#Override
public void handleMessage(Message msg) {
final int currentPos = msg.getData().getInt("CurrentPosition");
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
/*if(controller.isShowing()) {
controller.hide();
}else {
controller.show();
}*/
return false;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
mediaPlayer.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
// End VideoMediaController.MediaPlayerControl
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
videoWidth = width;
videoHeight = height;
Toast.makeText(getApplicationContext(),
String.valueOf(videoWidth) + "x" + String.valueOf(videoHeight),
Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()){
surfaceHolder.setFixedSize(videoWidth, videoHeight);
}
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void run() {
// TODO Auto-generated method stub
controller = new VideoControllerView(this);
try {
mediaPlayer.setDataSource(videoSrc);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
/*
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("CurrentPosition", mediaPlayer.getCurrentPosition());
msg.setData(bundle);
handler.sendMessage(msg);
// handler.postDelayed(callBack, 500);*/
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
And my logcat error is
01-03 20:42:14.881: V/MediaPlayer(14737): setVideoSurfaceTexture
01-03 20:42:14.881: W/System.err(14737): java.lang.NullPointerException: uriString
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:468)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:458)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri.parse(Uri.java:430)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1256)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1221)
My XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:keepScreenOn="true"
android:id="#+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SurfaceView
android:id="#+id/playersurface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
And one more question. I have this public void method for streaming
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
How can I used to stream files from another application program?
When I play video from main activity it plays and when I quit and go to file explorer and chose my player from custom dialog box and open I have that problem with uriString...
When navigating through your files you can set a clicklistener on a thumbnail. I use this code to fire up a full-screen video editor:
thumbNail.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (pathType.equals("image")) {
<snip>
}
else {
// music file
}
else {
// must be video
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(cmsURL + pathListFull,"video/mp4");
PackageManager packageManager = getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivity(intent);
}
else {
Log.d("SHOWFILE", "no intents available");
}
}
}
});

Android soundboard onpause

I have a problem with my soundboard im quite new to programming and i need help from some pros
The Problem is that my soundboard doesnt stop when i press the home button or the return button i need it to pause the sound or stop it here is the code hope you can help
package com.example.firstly;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Mymenu extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.dinal, R.id.ele, R.id.syl,
R.id.amel, R.id.krz, R.id.mar,
R.id.sra, R.id.bab, R.id.har,
R.id.kur, };
final int[] soundIds = { R.raw.dinal_ama, R.raw.daj_ama, R.raw.syl_ama,
R.raw.ame_ama, R.raw.krzy_ama, R.raw.marihuanen_ama,
R.raw.srac_ama, R.raw.zajeb_ama, R.raw.hardcore_ama,
R.raw.oookurwa_ama, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener); }
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Stop or pause the player in your activity's on pause, use the code below
package com.example.firstly;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Mymenu extends Activity {
int selectedSoundId;
MediaPlayer player;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.dinal, R.id.ele, R.id.syl, R.id.amel,
R.id.krz, R.id.mar, R.id.sra, R.id.bab, R.id.har, R.id.kur, };
final int[] soundIds = { R.raw.dinal_ama, R.raw.daj_ama, R.raw.syl_ama,
R.raw.ame_ama, R.raw.krzy_ama, R.raw.marihuanen_ama,
R.raw.srac_ama, R.raw.zajeb_ama, R.raw.hardcore_ama,
R.raw.oookurwa_ama, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
player.stop(); // to stop the player
player.release(); // if you want to pause the song use player.pause();
}
}

muting one audio and playing other audio in its place (VideoView)

package z.x;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class AsdqweActivity extends Activity {
/** Called when the activity is first created. */
VideoView myVideoView;
TextView translation;
String SrcPath = "/sdcard/bunny.MP4",txtdisplay="";
Thread Thread1,Thread2;
Button tag;
int count=0,tstart=-1,tend=0;
AudioManager am;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myVideoView = (VideoView) findViewById(R.id.newVideoView);
translation= (TextView) findViewById(R.id.translation);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(myVideoView);
myVideoView.setMediaController(mediaController);
myVideoView.setKeepScreenOn(true);
Runnable runnable = new VideoPlayer();
Thread2= new Thread(runnable);
Thread2.start();
runnable = new CountDownRunner();
Thread1= new Thread(runnable);
Thread1.start();
runnable = new AudioPlayer();
Thread1= new Thread(runnable);
Thread1.start();
am =
tag = (Button) findViewById(R.id.start);
tag.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//how to change the text on the button????????
if(count%2==0)
{
tstart=myVideoView.getCurrentPosition();
System.out.println("tag starts here: "+ tstart);
myVideoView.pause();
tend=tstart+1000;
count++;
if((tstart+1000)>myVideoView.getDuration())
{
tend=myVideoView.getDuration();
count++;
}
}
else
{
tend = myVideoView.getCurrentPosition();
if(tend>=(tstart+1000)){
System.out.println("tag ends here: "+ tend);
count++;
myVideoView.pause();
}
else
{
System.out.println("invalid tagging");
}
tstart=-1;
}
}
});
myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
Log.v("log_tag", "On Completion");
try {
Thread1.join();
Thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//r.stopThread();
finish();
}
});
}
class VideoPlayer implements Runnable{
public void run()
{
myVideoView.requestFocus();
myVideoView.setVideoPath(SrcPath);
myVideoView.start();
}
}
class AudioPlayer implements Runnable{
public AudioPlayer() {
// TODO Auto-generated constructor stub
}
public void run()
{
/*myVideoView.setsetvolume(0,0);
audio.requestFocus();
audio.setVideoPath(SrcPathaudio);
audio.start();*/
}
}
class CountDownRunner implements Runnable
{
File file = new File("/sdcard/harsh.srt");
long r=0;
RandomAccessFile rand;
public CountDownRunner() {
// TODO Auto-generated constructor stub
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try {
rand = new RandomAccessFile(file,"r");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
translation = (TextView)findViewById(R.id.translation);
}
public void run()
{
// Get the object of DataInputStream
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(100);
}catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
closeRandFile();
}
public void closeRandFile(){
try {
rand.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doWork(){
runOnUiThread(new Runnable() {
public void run() {
try{
rand.seek(r);
//If it returns milliseconds, divide by 1000
int playTime = myVideoView.getCurrentPosition();
long t1=0,t2=0;
int i=0,j=0;
/* String textValue = "i havent entered it yet";
System.out.println(playTime);
if(playTime<15000){
textValue = "its still not 15000";
System.out.println(textValue);
}else if(playTime>3000)
{textValue = "its more than 15000";}*/
////////////////////////////////////
try{
// Open the file that is the first
// command line parameter
String strLine;
//Read File Line By Line
while(((strLine = rand.readLine()) != null)&&((strLine=="")))
{
System.out.println(strLine+" line 184");
}
if(strLine != null)
{
i = Integer.parseInt(strLine);
System.out.println(strLine+" line 189");
if(i>j){
if((strLine = rand.readLine()) != null)
{
//02:03:24,100 --> 02:03:25,500
//String substring(int startIndex, int endIndex)
int h =Integer.parseInt(strLine.substring(0,2));
int m =Integer.parseInt(strLine.substring(3,5));
int s =Integer.parseInt(strLine.substring(6,8));
int ms=Integer.parseInt(strLine.substring(9,12));
t1 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("start of this text time "+t1);
int l = strLine.indexOf("-->")+4;
h =Integer.parseInt(strLine.substring(l+0,l+2));
m =Integer.parseInt(strLine.substring(l+3,l+5));
s =Integer.parseInt(strLine.substring(l+6,l+8));
ms=Integer.parseInt(strLine.substring(l+9,l+12));
t2 = (((((h*60)+m)*60)+s)*1000)+ms ;
System.out.println("end of this text time "+t2);
}
if((playTime<=t2)&&(playTime>=t1)){
while (((strLine = rand.readLine()) != null)&&(strLine!="")){
// Print the content on the console
txtdisplay=txtdisplay+strLine;
}
System.out.println(txtdisplay);
r=rand.getFilePointer();
translation.setText(txtdisplay);
}
txtdisplay="";
}
}
//Close the input stream
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
//////////////////////////////////////
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
I am new here. I was asked by my professor to play other audio while the same video is being played(for example a person doesn't understand English and wants the the app to play french ). I have used video view. One possible method was to mute the present audio and play the french audio stored in my sdcard. but video view supports no muting( i couldn't find one). I read that i have to go for media player instead of video view.
Please help...!! what should i do... Thanks in advance.
if you want to get access to the MediaPlayer of a VideoView you have to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener, then you can call setVolume(0f, 0f); function to set the volume to 0.
Do this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
VideoView videoView = (VideoView)this.findViewById(R.id.VVSimpleVideo);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
videoView.setMediaController(mc);
String _path = "/mnt/sdcard/Movies/video5.mp4";
videoView.setVideoPath(_path);
videoView.setOnPreparedListener(PreparedListener);
videoView.requestFocus();
//Dont start your video here
//videoView.start();
}
MediaPlayer.OnPreparedListener PreparedListener = new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer m) {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
m.setVolume(0f, 0f);
m.setLooping(false);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};

Video not displayed with 2 instances of mediaplayer

I am trying to use two instances of mediaplayer. When the first instance is played the second instance is prepared in another thread.and when first instance completes the file the second instance is started.
Problem: the second instance plays only audio, video is not visible.
Observation:If i prepare the second instance with the same surface holder as that of the first and start after first instance is completed it works fine.
Here is the code
package com.THER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.THER.MessengerServiceActivities.IncomingHandler;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.VideoView;
import android.widget.ViewSwitcher;
public class MediaPlayerActivity extends Activity implements OnCompletionListener, Callback, OnPreparedListener {
private MediaPlayer mMediaPlayer1 = null;
private SurfaceView mPreview1;
private SurfaceHolder holder1;
private ViewSwitcher switcher;
Integer counter = 0;
Integer played_files = 1;
private MediaPlayer mMediaPlayer2 = null;
private SurfaceView mPreview2;
private SurfaceHolder holder2;
boolean mIsBound;
boolean finish_flag = false;
/** Messenger for communicating with service. */
Messenger mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent;
super.onCreate(savedInstanceState);
setContentView(R.layout.videoview);
doBindService();
intent = getIntent();
counter=intent.getIntExtra("counter",counter);
mPreview1 =(SurfaceView)findViewById(R.id.surfaceView1);
holder1 = mPreview1.getHolder();
holder1.addCallback(this);
holder1.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPreview2 =(SurfaceView)findViewById(R.id.surfaceView2);
holder2 = mPreview2.getHolder();
holder2.addCallback(this);
holder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer1 = new MediaPlayer();
mMediaPlayer1.setScreenOnWhilePlaying(true);
mMediaPlayer2 = new MediaPlayer();
mMediaPlayer2.setScreenOnWhilePlaying(true);
try {
mMediaPlayer1.setDataSource("/sdcard/1.mp4");
mMediaPlayer1.setDisplay(holder1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer1.setOnCompletionListener(this);
mMediaPlayer1.setOnPreparedListener(this);
//mMediaPlayer2.setOnPreparedListener(this);
mMediaPlayer2.setOnCompletionListener(this);
}
private class MediaPlayerTask extends AsyncTask<MediaPlayer, Void, String> implements OnCompletionListener {
String file;
private SurfaceHolder holder;
#Override
protected String doInBackground(MediaPlayer... mp1) {
// TODO Auto-generated method stub
//mp1[0].reset();
if(counter%2 == 0)
{
file = "/sdcard/2.mp4";
holder = holder2;
}
else
{
file = "/sdcard/1.mp4";
holder = holder1;
}
try {
mp1[0].reset();
mp1[0].setDataSource(file);
mp1[0].setDisplay(holder);
mp1[0].prepare();
mp1[0].setOnCompletionListener(this);
//mp1[0].start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
public void onCompletion(MediaPlayer mp)
{
if(counter%2 == 0)
{
played_files++;
mMediaPlayer1.stop();
mMediaPlayer1.release();
mMediaPlayer2.start();
}
else
{
played_files++;
mMediaPlayer2.stop();
mMediaPlayer2.release();
mMediaPlayer1.start();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
if(counter%2 == 0)
{
mMediaPlayer2.prepare();
}
else
{
mMediaPlayer1.prepare();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
//if(counter == 1)
mp.start();
}
}
Please take a look at the following thread:
http://groups.google.com/group/android-developers/browse_thread/thread/7d08a124a2e48bb3?pli=1
It looks like using two SurfaceViews was not intended by the Android developers.

Categories

Resources