reiley
reiley

Reputation: 3761

Android: How to check Service status in Activity's onResume()?

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.

I was planning to implement a method:

public boolean isMediaPlaying() throws RemoteException {
    if (mediaPlayer != null) {
        if (mediaPlayer.isPlaying()) {
        return true;
    }
    return false;
}

Problem: But the ServiceConnection's onServiceConnected is executed after on resume.

Please suggest how can I check this status on activity resume?

Thanks in advance.

Upvotes: 0

Views: 2453

Answers (1)

Georgy Gobozov
Georgy Gobozov

Reputation: 13731

You can hold reference to yor service in Application class. For example

    public class App extends Application {

    private static PlayerService player;

    @Override
    public void onCreate() {
        super.onCreate();

        if (player == null)
            bindService(new Intent(App.this, PlayerService.class), connection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        player.stop();
        player = null;
        getApplicationContext().unbindService(connection);
    }

    public static PlayerService getPlayer() {
        return player;
    }


    private ServiceConnection connection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            player = ((PlayerService.PlayerServiceListener) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            player = null;
        }
    };

}

And then in activity onResume use

App.getPlayer().isPlaying

Upvotes: 1

Related Questions