2

我只需要停止在同一应用程序的先前运行时创建的线程。这就是场景。我正在后台使用线程从数据库中检索数据以获取通知,但是当我再次启动该应用程序时,线程数正在增加。我需要阻止这一切。我认为最好在应用程序主类的 onCreate() 方法中停止后台运行线程。但是没办法做到。请尽快帮我解决这个问题。

谢谢和最好的问候,Shehan。

4

2 回答 2

0

在活动类中保留对正在运行的线程的静态引用。在您的线程内部,您需要有一个可以设置的布尔变量或一个可以调用的方法,这将导致您的线程完成。你可以检查你是否有一个正在onCreate()运行的线程,如果有,告诉它停止。这是一个代码示例:

在您的活动中:

private static Thread myThread;

在您的活动中,当您创建线程时:

if (myThread != null) {
    if (myThread.isAlive()) {
        myThread.running = false; // Tell the thread to stop running now
    }
}
myThread = new Thread(...);
myThread.start();

在你的线程中:

public boolean running = true; // Initator of this thread should set this to false to make the thread complete

public void run() {
    while (running) {
        // do whatever your thread does in a loop
    }
}
于 2012-10-18T08:43:49.647 回答
0

您可以停止活动的 onDestroy() 运行线程。

请找到以下内容,例如:

 static boolean stopThread=false;
    public myThread implements Ruunable{
    public void run(){
    while(true){
    //your logic
    if(stopThread)
    break;
    }
    }


    @Override
        protected void onDestroy() 
        {    

          stopThread=true;
        }    
于 2012-10-18T10:33:29.590 回答