I'm creating a media player app.
When I starts or resumes the application I want to check if the media player was already playing a song.
So that if it was I will set my Pause/Play ToggleButton
to Pause, else it was not playing earlier then button will set to Play.
(i.e. for e.g. if the user was already using the media player and left the app by pressing home or back button & now he resumes the player. then the button should be configured correctly.)
The actual MediaPlayer object is implemented in the Service & all the communications are done via AIDL interface
methods.
Right now,
- In
onResume
I'm calling anAsynTask method
that will check all the running services and check If myMusicService
is also running. - If yes then I'm calling an
aidl method
to check ifmediaPlayer.isPlaying()
is true or not. - If yes then the
toggleButton
will set to pause(i.e. currently playing), else play.
Problem:
This AsyncTask
is creating a race condition. That is sometimes it runs as intended & sometimes it just throws error
Code:
// In onResume
protected void onResume() {
new PlayerStatusCheck().execute();
}
//AsyncTask Class
class PlayerStatusCheck extends AsyncTask {
boolean isServiceAvailable;
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (com.example.playingworking.MusicService.class.getName()
.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
protected Object doInBackground(Object... params) {
isServiceAvailable = isMyServiceRunning();
return null;
}
@Override
protected void onPostExecute(Object result) {
try {
if (!isServiceAvailable) {
doInBackground(null);
} else {
if (aidlObject.isMediaPlaying()) {
tbPlayPause.setChecked(true);
} else {
tbPlayPause.setChecked(false);
}
}
} catch (RemoteException e) {
Toast.makeText(MainActivity.this,
"MainActivity onPostExecute: " + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
Code In MusicService :
//In IBinder onBind()
public boolean isMediaPlaying(){
if(mediaPlayer.isPlaying()){
return true;
}
return false;
}
Please Suggest...Thanks