Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to know if an activity is finished?

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?

like image 276
Jack BeNimble Avatar asked Jun 11 '11 02:06

Jack BeNimble


People also ask

How do I know if my activity is finished?

Using activity. isFinishing() is the right one solution. it return true if activity is finished so before creating dialog check for the condition.

How do you finish an activity?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

How do I close all activities on Android?

exit(); or finish(); it exit full application or all activity.


1 Answers

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.

@Override
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.

like image 76
achie Avatar answered Oct 05 '22 18:10

achie