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,


   1. In onResume I'm calling an AsynTask method that will check all the 
   running services and check If my MusicService is also running.
   2. If yes then I'm calling an aidl method to check if 
   mediaPlayer.isPlaying() is true or not.
   3. 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


// 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

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to