简体   繁体   English

Android:如何知道活动是否完成?

[英]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.我正在开发一个在给定活动中自动并连续播放 mp3 文件的应用程序。 it knows when the current mp3 play is completed by listening for an "onCompletion" event from the MediaPlayer.它通过侦听来自 MediaPlayer 的“onCompletion”事件来知道当前 mp3 播放何时完成。

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.当触发“onCompletion”事件时,它会尝试访问列表活动中的视图并在 null 指针异常上崩溃。

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.尝试在 Activity 生命周期方法 onStop 或 onDestroy 中触发它们。 Check this documentation for more details.查看此文档以获取更多详细信息。

onStop will be triggered when user clicks on back button. onStop 将在用户单击后退按钮时触发。 So handle your events in onStop.所以在 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.最终,onDestroy 也将被调用,但不一定在单击后退按钮时立即调用。

if you are using Kotlin use this如果您使用的是Kotlin使用这个

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

Here is more on the topic 是有关该主题的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM