如果我有一个 Android 服务,它在 onStartCommand
中具有以下内容:
MyWidgetUpdater updater = new MyWidgetUpdater();
updater.updateWidgets(...);
updater
在后台线程中检索数据,然后在前台线程中更新小部件。如果服务在后台处理完成之前停止(例如 stopSelf()
)会怎样?这是否会导致小部件有时无法完成更新(因为线程可能已被终止)?如果是这样,是否有一种设计模式可以知道您的所有小部件何时完成更新并且可以安全地停止服务?
最佳答案
What happens if the service is stopped (e.g. stopSelf()) before the background processing is complete?
假设这是您自己创建的一个线程,Android 不会注意到该线程,它将继续运行、泄漏,直到 Android 终止您的进程。
If so, is there a design pattern to know when all of your widgets have completed updating and its safe to stop the service?
在工作完成之前不要调用 stopSelf()
。我不知道您在哪里调用 stopSelf()
,但在您引用的模式中,它通常会在该线程的末尾完成。
这就是 IntentService
流行的原因之一:它为您处理所有线程和 stopSelf()
内容。
关于android - 如果服务停止,后台线程会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12944371/