简体   繁体   English

即使在服务被系统杀死后,Service 内部的线程也会继续运行

[英]Thread inside Service keep running even after the service is killed by the system

my thread is basically a loop of some actions.我的线程基本上是一些动作的循环。

I have set a few checks in my loop, to check basically if a boolean is still true or false.我在我的循环中设置了一些检查,基本上检查 boolean 是否仍然为真或假。 The boolean is set to true when starting the service and set to false when the service is being stopped. boolean 在启动服务时设置为 true,在服务停止时设置为 false。 More specifically, I set the boolean to false in onDestroy() method of my Service class.更具体地说,我在我的服务 class 的 onDestroy() 方法中将 boolean 设置为 false。

Example:例子:

  public class MyThread extends Thread{
   
    
private boolean active; 
    
public void setBoolean(boolean active)
    this.active=active;
    }
    }
    
    public class MyService extends Service{
    
    private Mythread mythread;
    
    @Override
    public void onDestroy()
    {
    mythread.setBoolean(false);
    }
    }

The issue is that when a Service is being stopped by the system, onDestroy() method is not called.问题是当系统停止服务时,不会调用onDestroy()方法。 So, how can I properly stop the thread when the service is no longer running?那么,当服务不再运行时,如何正确停止线程?

It helps to know exactly what you mean by " when the service is being stopped ."这有助于准确了解“服务何时停止”的含义。 I found 3 links related to your problem that I am sure will help to solve your issue (or at least to fully understand it):我发现了 3 个与您的问题相关的链接,我相信它们将有助于解决您的问题(或至少完全理解它):

TL:DR - If you are forcing stop, onDestroy() will most likely not get called. TL:DR - 如果你强制停止, onDestroy()很可能不会被调用。

Even if the first helps, read through the rest.即使第一个有帮助,请通读 rest。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使在使用服务后,应用也被杀死 - App is getting killed even after using Service 即使重新启动后,服务也始终保持运行 - Keep a service running all the time even after a reboot 即使应用程序被强制停止,也要重新启动服务,即使关闭应用程序,也要在后台继续运行服务如何? - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? 即使应用程序被强制停止,也要重新启动服务;关闭应用程序后,仍要在后台运行服务。 - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? Android如何在用户杀死应用程序后继续运行后台服务? - Android How to keep Running the background service when app is killed by user? Android 前台服务即使在被杀死后仍保持麦克风访问权限 - Android foreground service holds microphone access even after being killed 如何在没有服务的情况下杀死应用程序后在后台线程中运行代码? - How to run code in background thread after app is killed without Service? IntentService / Service-即使应用程序终止,也可以继续运行-Android - IntentService/Service - Keep running even if the application is terminated - Android 在Thread或Service内的线程中创建服务 - Create a service inside Thread or Thread inside Service 服务在线程中运行 - Service running in a thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM