I am trying to make togglePlayPause button for media player. first I made a play_pause_toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="false" android:drawable="@drawable/play"/>
<item android:drawable="@drawable/pause"/>
</selector>
second I made a function to listen to the playing state when sound playing it set the button to activate so it changes the button image from play to pause. this works very well when I open the app, but when going away from activity and come back the button only shows a playing image when clicking it, when restarting the app it works fine again.
private void handleStateChanged(int state){
boolean isPlaying = (state == PlaybackStateCompat.STATE_PLAYING);
playToggleButton.setActivated(isPlaying);
}
@Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
super.onPlaybackStateChanged(state);
if (state != null){
handleStateChanged(state.getState());
}
}
The problem that I unregister mediaControllerCallback in onStop() and I should unregister it in onDestroy() instead.