gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:42:40 25 4
gpt4 key购买 nike

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

1) 如果我的服务与应用程序在同一个进程中工作,那么该服务也会存活吗?

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

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

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

最佳答案

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

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

嗯,不。你的Service是您的应用程序的一个组成部分。如果它是活的,那么应用程序也是活的(另见第三个问题)。 但是如果你返回START_STICKYSTART_REDELIVER_INTENT来自 onStartCommand() , 那么如果被系统终止(而不是强制停止),它将被尽快重新创建。

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 可以通知 ServiceonPause()或在 onStop() .自Version HONEYCOMB起,两者都保证被调用.

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

一般情况下,你的应用进程不会因为当前的Activity被立即杀死。不再处于前台。所以很可能 Service将收到您从 onPause() 发送的任何通知.

关于android - 服务和 Android 应用程序生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35646425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com