gpt4 book ai didi

android - 系统停止时android服务如何响应

转载 作者:行者123 更新时间:2023-11-29 21:56:04 27 4
gpt4 key购买 nike

我有一个问题是关于 Android 服务在被系统停止时的行为方式。据我了解,如果系统 (OS) 由于需要资源而停止服务,则系统有责任重新启动它。在这种情况下,系统不会在停止服务时调用 onDestroy() 和在启动服务时调用 onCreate(),而只会调用 onStartCommand()。

如果我在 onStartCommand() 中创建一个线程,我将如何在系统停止服务时清理线程。如果我不停止线程,onStartCommand() 将创建一个新线程。我认为,它可能归结为 onStartCommand() 参数( Intent 、标志和 startId)。当系统在停止服务后启动服务时,它们可能会有所不同,因为它需要资源。谁能告诉我通过 startService() 命令或系统本身(停止后)启动服务时参数有什么不同

我可以在 onCreate() 中创建线程,但我不确定当系统停止服务时线程是否仍然存在。处理这种情况的最佳方法是什么。

谢谢

最佳答案

As per my understanding, if system (OS) stops the service due to resources needed, it is responsibility of system to start it again.

这取决于您从 onStartCommand() 返回的内容。 START_NOT_STICKY,例如,意味着操作系统不必再次启动您的服务。

In this scenario, system would not call onDestroy() when stopping service and onCreate() when starting service, rather it would just call onStartCommand().

它是否调用 onDestroy() 将在一定程度上取决于服务停止的方式(例如,直接停止或通过进程终止)。但是,如果操作系统重新启动服务,它仍应在新实例上调用 onCreate()

If I am creating a thread in onStartCommand(), how would I cleanup thread when system stops service.

确保在 onDestroy() 中,发生了导致线程消失的事情。 onDestroy() 将被调用(您的服务可以进行清理),或者您的进程正在终止(您的线程随之消失)。

Could anyone tell me what would be difference in parameters when service started by startService() command or by system itself (after stopping it)

START_FLAG_REDELIVERY 将包含在传递给 onStartCommand() 的标志中,但据我所知,只有当您返回 START_REDELIVER_INTENT 时才会设置它> 来自 onStartCommand()

关于android - 系统停止时android服务如何响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13237418/

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