当IntentService启动时,Application对象启动了吗?

Ana*_*man 4 android android-intent android-service android-lifecycle android-intentservice

我想了解Application对象的生命周期Android,尤其是IntentService.

如果IntentService启动,Application对象是否会随之启动?这个的确切顺序是什么?最后,在这种情况下什么时候会被销毁?

Dav*_*ser 6

Application实例是单例.每当Android创建一个操作系统进程来托管Activity, Service, BroadcastReceiver, Provider应用程序的Android组件()时,它就会执行以下操作:

  • 创建一个新Application实例(将调用该类的构造函数)
  • 调用onCreate()Application实例

之后,Android然后实例化必要的组件(调用该组件的构造函数),然后调用onCreate()该组件.

在示例中IntentService,您应该看到以下内容(按顺序):

  • 创建Application(调用构造函数Application)的新实例
  • 呼叫 Application.onCreate()
  • 创建IntentService(调用构造函数IntentService)的新实例
  • 呼叫 IntentService.onCreate()

如果您IntentService完成并停止,Android将最终调用onDestroy()IntentService实例.此时,如果操作系统进程中没有其他活动组件,Android可能会决定终止操作系统进程,或者可能会暂停操作系统进程一段时间.

如果Android需要IntentService再次启动并且您的应用程序仍然存在实时操作系统进程,则Android将不会创建新的操作系统进程,只会重用现有的操作系​​统进程.在这种情况下,Application实例已经存在,因此Android不需要实例化新的实例.Android只是创建一个新的实例IntentService,调用IntentService.onCreate()并启动它IntentService.

Application实例永远不会被破坏.当Android想要关闭托管您的应用程序的操作系统进程时,它只会杀死该进程.