سؤال

I'm working on an app that plays mp3 files automatically and in succession from within a given activity. it knows when the current mp3 play is completed by listening for an "onCompletion" event from the MediaPlayer.

However, if I return to the start display by pressing the back button while media is playing, apparently the activity is still running. When the "onCompletion" event is triggered, it tries to access the view within a list activity and crashes on an null pointer exception.

What is the best way to determine that the activity is no longer "active" and therefore be able to prevent the call to play the next audio?

هل كانت مفيدة؟

المحلول

Try triggering those in the Activity lifecycle methods onStop or onDestroy. Check this documentation for more details.

onStop will be triggered when user clicks on back button. So handle your events in onStop.

public void onStop () {
//do your stuff here
super.onStop() 
}

Eventually onDestroy will also be called, but not necessarily as soon as the back button is clicked.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top