Android: How to know if an activity is finished?
Asked Answered
S

2

17

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?

Shoreline answered 11/6, 2011 at 2:54 Comment(0)
B
28

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.

Bobker answered 11/6, 2011 at 3:20 Comment(4)
Thanks. I just set a flag in the onStop method, and check it in the listener. It worked like a charm.Shoreline
onStop() will be triggered also when some new activity comes in front of this activity. If you want to listen back button press try onBackPressed() event.Ornamented
onStop is also called on configuration changesCaster
You really should add @Override , good coding stylePsychosurgery
R
1

if you are using Kotlin use this

override fun onStop () {
    super.onStop()
    //do stuff
}

Here is more on the topic

Reuben answered 18/4, 2020 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.