如何使用 long-运行 onDestroy 来管理停止服务?

How to manage stopping a Service with a long-running onDestroy?

我有一个 android 服务 class,它有一个很长的 运行 onDestroy。我需要防止这种情况发生,因为当有活动 运行.

时它会导致挂起

似乎有些人很乐意在 onDestroy 方法中启动一个 thread/AsyncTask 来保存长 运行 代码,尽管我担心线程可能会被杀死。另一种解决方案可能是使用 startService 而不是 stopService ,目的是告诉服务启动一个关闭线程,该线程最后调用 stopSelf。

这些解决方案是否明智,或者有其他方法吗?

你应该知道onDestroy没有绝对的保证会被执行。

It seems some people are happy starting a thread/AsyncTask in the onDestroy method to hold the long running code, though I'm concerned that the threads may be killed.

我假设您正在尝试释放一些资源或向服务器发送某种消息。

如果有资源,则无需担心 - 如果您启动新线程,它只会与托管进程(您的应用程序)一起被终止。如果发生这种情况 - 没关系,系统会为您释放资源。

在服务器消息的情况下 - 这有点复杂。我喜欢你将命令发送到 Service 而不是调用 stopService 的想法。其他选择是从您的 onDestroy 开始另一个拆卸 Service,它将执行长时间的 运行 操作并自行关闭。

关闭 Intent 是一种合理的方式。

不过在 onDestroy 中启动另一个线程是个坏主意。当您不期望或不想要它时,它可能会被调用或不被调用。


编辑:要保留重要信息,这两种方式都不是一个好主意。 你不能保证这些方法在你的进程被杀死之前实际上得到 运行 。对于不重要的数据,您当然可以采用这些方式,但您最好在获得数据后立即持久化数据,或者至少在固定的时间间隔内(如果您有连续的数据输入)。

来自official Documentation

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here.

This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

这里 Documentation 专门用于服务:

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up any resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead.

(我包含了活动文档,因为它更准确)