我有一个在自己的进程中运行的服务。它在晚上看起来很好,但是在我睡觉之后,我认为Android会采取行动。
我是否认为Android杀死服务时不会调用onDestroy()
?如果没有,那么杀戮是否还有其他地方?
我想我需要研究AlarmManager
。
答案 0 :(得分:3)
我有一个在自己的进程中运行的服务。
为什么它在自己的过程中?
我认为Android杀死服务时不会调用onDestroy()吗?
可能,也可能没有。
如果没有,是否还有其他地方被注册?
没有
我想我需要研究AlarmManager。
用户讨厌永远存在的服务,这就是任务杀手流行的原因。他们更讨厌在自己的进程中运行的服务,因为他们消耗额外的RAM,CPU和电池,通常没有充分的理由。
如果您的目标是定期执行某项操作,请使用AlarmManager
- 这就是原因。
答案 1 :(得分:1)
根据开发人员文档中的Service lifecycle,当服务被终止或停止时,将调用onDestroy()
方法。
此外,如果某个应用程序在后台运行服务(即在背景中播放音乐播放器),系统会认为该应用程序处于活动状态,并且除了极端条件外不会终止其进程(我不认为它发生在实践中。)
该文件说:
Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.
在这里,我正在考虑的是,如果服务被os杀死,操作系统将尝试稍后重新启动它。但是,在这种情况下,是否调用了onDestroy()方法?我不确定。有人对此进行了测试吗?