1. 是否存在OS kill 的应用程序,但没有kill 服务的情况?
tl;博士:是的,这是可能的。但是,Service
必须在它自己的进程中启动。
解释:
重要的是要意识到 Android 操作系统会在内存不足时杀死进程,而不是单个组件,例如Activities
或Services
(请参阅此答案)。
鉴于上述陈述,很明显,只有当它们包含在单独的进程中时,aService
才能独立于 the 存在。Application
否则,当它们的进程被销毁时,它们将一起被销毁。
现在考虑单独进程上的Service
和存在的情况。Application
在 Android 中,进程在内存不足的情况下从最低优先级到最高优先级被销毁。优先顺序是:空 < 背景 < 服务 < 可见 < 前景(见这里)。因此,您可能会在您还活着的时候Application
被销毁(例如,如果您的应用程序在后台),也可能在您的应用程序还活着的时候被销毁(应用程序在前台)。Service
Service
android:process
您可以通过在组件清单标签中定义属性来声明应用程序的任何组件(Activity、Service、ContentProvider 等)以在其自己的进程中运行。
来自Processes的官方文档:
默认情况下,同一应用程序的所有组件都在同一进程中运行,大多数应用程序不应更改这一点。Activity
但是,[...] 每种类型的组件元素( 、Service
、Receiver
和)的清单条目都Provider
支持一个android:process
属性,该属性可以指定该组件应在其中运行的进程。您可以设置此属性,以便每个组件在其自己的进程中运行,或者使某些组件共享一个进程而其他组件不共享。[...] 该Application
元素还支持 android:process 属性,以设置适用于所有组件的默认值。
2. 服务被系统重启后,应用也会重启吗?
这与问题1中的答案有关。
If the Service
exists in the same process as the Application
then they will both be destroyed and restarted together.
If the Service
exists in a separate process as the Application
then they are completely separate processes, and therefore will be destroyed and restarted independent of each other as the Android OS deems appropriate.