是否保证 android 服务调用 onDestroy()? [英] Is an android service guaranteed to call onDestroy()?

查看:74
本文介绍了是否保证 android 服务调用 onDestroy()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

android上一个Activity的生命周期图并不能保证onDestroy()会被调用,而是保证进程可能会被杀死,Activity会被突然删除.android 上服务的生命周期图确实保证会调用 onDestroy().所以我有两个关于这种差异的问题.

The life cycle diagram of an Activity on an android does not guarantee that onDestroy() would be called, but that the process may be killed and the Activity is removed abruptly. The life cycle diagram of a Service on an android does guarantee that onDestroy() would be called. So I have two questions relating to this difference.

首先,如果 Service 与 Activity 属于同一进程,那么 Service onDestroy() 是否被调用,而 Activity onDestroy() 没有被调用?我不这么认为,因为杀死进程"表明操作系统正在停止其线程并释放其资源.

Firstly, if the Service is part of the same process as the Activity, is the Service onDestroy() called, though the Activity onDestroy() is not called? I would think not, as "killing a process" suggest that the operating system is stopping its threads and releasing its resources.

如果是这样的话,一个 Service-only 进程会被操作系统突然杀死吗?

And if that is the case, can a Service-only-process be abruptly killed by the OS?

推荐答案

我不确定您在哪里看到服务保证调用 onDestroy().据我所知,事实并非如此.如果您阅读文档的 this 页面,它会描述条件其中一项服务可能会被终止.因此,如果您要问一个同时承载活动和服务的进程是否被终止,是否会在服务上调用 onDestroy()(但不会在活动上调用),那么答案是否定的;服务的 onDestroy() 不一定会被调用.至于仅服务进程是否可以被操作系统突然杀死:是的,它可以.当您有大量工作要做,并且您的 onStartCommand 调用仅将要异步完成的工作排队时,尤其如此.然后服务将大部分时间花在受保护的 onCreateonStartCommandonDestroy 方法中.

I'm not sure where you're seeing that a Service is guaranteed to have onDestroy() called. As far as I know, this isn't the case. If you read this page of the docs, it describes the conditions in which a service could be killed. So if you're asking if a process which hosts both an activity and service is being killed, will onDestroy() be called on the service (but not on the activity) then the answer is no; a service's onDestroy() will not necessarily be called. As to whether a service-only process can be abruptly killed by the OS: yes, it can. This is especially true when you have a lot of work to do, and your onStartCommand call only queues up the work to do asynchronously. Then the service will be spending the majority of its time not in the protected onCreate, onStartCommand or onDestroy methods.

这篇关于是否保证 android 服务调用 onDestroy()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆