I'm trying to make a simple mp3 player app for a project and I'm having trouble with accessing the service from the main activity. I have some onclicklisteners in the activity:
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayService.class);
intent.putExtra("key", 0);
startService(intent);
}
});
pause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayService.class);
intent.putExtra("key", 1);
startService(intent);
}
});
stop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayService.class);
intent.putExtra("key", 2);
}
});
and a switch statement in my service that responds to the onclicks:
@Override
public int onStartCommand(Intent intent, int flags, int startId){
int key = intent.getIntExtra("key", 1);
MediaPlayer mMediaPlayer = new MediaPlayer();
FileInputStream fileStream = null;
try {
fileStream = new FileInputStream("/sdcard/Download/Bob_Marley-Jammin.mp3");
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
switch (key) {
case 0: //Play
if (mMediaPlayer.isPlaying()){
break;
}
else
try {
mMediaPlayer.setDataSource(fileStream.getFD());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.start();
break;
case 1: //Pause
mMediaPlayer.pause();
break;
case 2: //Stop
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
}
break;
default:
break;
}
return Service.START_NOT_STICKY;
}
For some reason the play call works but the pause and stop calls have no effect. I think this might be because I'm creating a new MediaPlayer reference each time I'm calling the service. (I'm not sure how to fix this)
So I've heard it's easier to access the service by making it a singleton class and accessing it from the activity but I'm not sure how to implement that. Any tips based off my code?