Service被销毁后的线程

发布于 2024-11-08 11:05:41 字数 545 浏览 0 评论 0原文

我有一个名为 MyService 的 Android Service

我有一个带有两个按钮(启动服务/停止服务)的Activity

当用户单击“启动服务”按钮时,使用 MyService 启动

startService(new Intent(this, MyService.class));

当用户单击“停止服务”按钮时,使用 In MyService 停止

stopService(new Intent(this, MyService.class));

MyService > 我创建一个 Thread T 来执行一些长时间运行的任务。

我的问题是:如果 Service 被销毁,那么即使 T 仍在运行,它也会被销毁吗?

I have an android Service called MyService.

I have an Activity with two buttons (start service/stop service).

When user clicks the button "start service", MyService is started using

startService(new Intent(this, MyService.class));

When user clicks the button "stop service", MyService is stopped using

stopService(new Intent(this, MyService.class));

In MyService I create a Thread T that performs some long running task.

My question is: If the Service is destroyed, is T also destroyed even if it is still running?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮凉 2024-11-15 11:05:41

不,结束您显式创建的线程不是 Android 框架的责任。您需要扩展onDestroy()。这是该方法的 javadoc:

由系统调用以通知服务不再使用并正在被删除。此时服务应该清理它持有的资源(线程、注册的接收器等)。返回后,将不再有对此 Service 对象的调用,并且它实际上已死亡。不要直接调用此方法。

我还建议您让线程使用中断,以便你可以优雅地结束它。

No, ending a thread you explicitly created is not the responsibility of the Android framework. You need to extend onDestroy(). Here is the javadoc for this method:

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up an 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. Do not call this method directly.

I would also suggest that you make your thread use Interrupts so that you can end it gracefully.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文