服务和 Android 应用程序生命周期

Service and Android Application lifecycle

我有点困惑。我读过使用启动服务的最大好处是它独立于应用程序,因此,即使 android 终止了您的应用程序,您的服务仍然存在。那么我的问题是:

1) 如果我的服务与应用程序在同一个进程中工作,该服务是否也存在?

2) 我正在使用 BroadcastReceiver 来检测设备连接的变化,因此,如果应用程序被终止但服务没有终止,我是否仍会收到连接变化?

3) 如果我想从服务中获取当前的连接状态,我可以使用 getApplicationContext() 来实现吗,或者它可能 returns 为空?第二种情况,如何获取当前网络状态?

4) 与连接类似,每次应用程序将其状态从前台更改为后台(在应用程序 paused/resumed 上)时,我都会通过 Otto 的总线发送一个事件。因此,我的服务订阅了该更改,以便了解当前的应用程序状态。如果我的应用程序被终止,我可以相信该事件吗?或者无法发送?

1) 服务默认终止。但是您可以覆盖 onStartCommand 和 return START_STICKY。还有其他标志。所以阅读更多关于它的信息 https://developer.android.com/reference/android/app/Service.html#START_STICKY

2) 是的,我会接受接收方的更改。

3) getApplicationContext() 不应 return NULL。

4) 如果您的应用程序已终止,则应该调用 onPause。所以服务在后台知道那个应用程序。当您启动应用程序时,onResume 调用,因此服务也会知道该应用程序在前台。

你误会了Activity and Application in Android. You can find more about Service lifecycle here

首先,如果使用前景Service,不太可能被突然杀死。话虽如此:

If my service works in the same process than the application, the service will be alive too?

嗯,不。您的 Service 是您申请的一个组成部分。如果它是活的,那么应用程序也是活的(另见第三个问题)。 但是如果你从onStartCommand()returnSTART_STICKYSTART_REDELIVER_INTENT,那么它会在被系统终止时被重新创建(不是强制-尽快停止)。

I'm using a BroadcastReceiver to detect the changes in the device's connectivity so, if the application is killed but the service is not, would I still receive that connectivity changes?

对于静态 BroadcastReceiver(在 Manifest 中注册):这取决于您的应用程序是如何终止的。如果用户强制停止它,那么接收器只会在用户再次启动您的应用程序后重新开始工作。在所有其他情况下:静态接收器将完好无损,如果接收器是动态创建和注册的,则应在关闭 Activity/ Service 时及时取消注册以避免内存泄漏,因此无论如何,这种接收器并不意味着 24/7 全天候工作。

If I want to get the current connectivity status from the service, could I do that by using the getApplicationContext() or it may returns null?

那个更简单:Service,就像 Activity,扩展了 ContextWrapper。所以如果它起来了并且运行,你可以调用getApplicationContext().

I'm sending an event through Otto's bus each time that the application changes its status from foreground to background (on application paused/resumed)... If my application is killed, can I trust in that events? Or they could not be sent?

我认为您可能混淆了 ApplicationActivity。因为如果需要通知 Service,那么您很可能会想到应用程序的可见部分,例如著名的来电。

在这种情况下,您的 Activity 可以在 onPause()onStop() 中通知 Service。自 Version HONEYCOMB.

以来,两者都保证被调用

现在我必须承认我不确定 Otto 的 EventBus,但是一个肯定可行的选项是使用 ServiceSTART_REDELIVER_INTENT 并通过调用 startService(myNotifyingIntent) 通知服务.

通常情况下,您的应用进程不会因为当前Activity不再在前台而被立即杀死。因此 Service 很可能会收到您从 onPause().

发送的任何通知