I'm trying to make an audio player app, all running smoothly by utilizing activity and services. But there is a constraint when you have selected an audio and play it. Currently when the audio is playing, while selecting the same audio, I make it start from the beginning.
The question: How to detect that the selected audio is being played. If the selected audio is different from what is being played it will be played from scratch but if it is the same it will not do anything.
In my activity :
//connect to the service
private ServiceConnection serviceConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Services.MediaBinder binder = (Services.MediaBinder) service;
//get service
services = binder.getService();
mediaBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mediaBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, Services.class);
playIntent.putExtra("url", String.valueOf(urlRaw));
bindService(playIntent, serviceConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
In services : Get variable using onBind:
@Override
public IBinder onBind(Intent intent) {
urlMedia = intent.getStringExtra("url");
return mediaBinder; // private final IBinder mediaBinder
}
I use in onStartCommand to play the selected audio.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//An audio file is passed to the service through putExtra();
if(isPng()){
mPlayer.release();
}
mPlayer = MediaPlayer.create(getApplicationContext(), getResources().getIdentifier(String.valueOf(urlMedia),"raw",getPackageName()));
mPlayer.start();
} catch (NullPointerException e) {
stopSelf();
}
if (mPlayer != null)
initMusicPlayer();
return START_STICKY;
}