Android:应用程序结束时停止服务和警报
我有一个由多个活动组成的应用程序。当应用程序启动时,使用 AlarmManager
安排一些警报并启动一些服务:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
a.setInexactRepeating(...)
....
我想知道有什么方法可以保证当用户退出时每个服务都停止并且每个警报都未安排应用程序。
问题是用户可以从不同的 Activity 中离开应用程序,而且我不喜欢在每个 Activity 中重写 onDestroy
方法的想法。应用程序结束时我是否可以收到任何已知的Intent
?
我还发现 Android 应用程序可以有一个从 Application
扩展的类,并带有 onTerminate
方法:
public class MyApplication extends Application {
@Override
public void onTerminate() {
...
}
}
但是文档非常清楚:“永远不要依赖在调用此方法时;在许多情况下,不需要的应用程序进程将被内核简单地杀死而不执行任何应用程序代码”
任何建议都将受到高度赞赏。
I have an application that consist of several Activities. When the application starts, some alarms are scheduled using AlarmManager
and some services are started:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
a.setInexactRepeating(...)
....
I would like to know any way to guarantee every service is stopped and every alarm is unscheduled when the user exits the application.
The problem is that the user can leave the application from different Activities, and I don't like the idea of overriding the onDestroy
method in every Activity. Is there any known Intent
I can receive when the application ends?
I've also found that an Android application can have a class that extends from Application
, with a onTerminate
method:
public class MyApplication extends Application {
@Override
public void onTerminate() {
...
}
}
But the documentation is very clear: "never depend on this method being called; in many cases an unneeded application process will simply be killed by the kernel without executing any application code"
Any suggestion is highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Android 中不存在“用户退出应用程序”这样的事情。
不。
在许多情况下,在不再有正在运行的组件后的某个时间,将调用此方法。在您的情况下,有正在运行的组件(服务)。
我知道它不会被调用的唯一情况是进程正在终止,在这种情况下,您的服务也将被消除,但预定的警报不会。
There is no such thing as "user exits the application" in Android.
No.
This will be called, in many cases, sometime after there are no more running components. In your case, there are running components (services).
The only case I know of when it will not be called is if the process is being terminated, in which case your service will be eliminated as well, though scheduled alarms will not.