2011-12-16 45 views
0

我的应用程序正在启动一个持续运行的线程,运行一段时间(true){}。当我重新打开/重新输入应用程序时,会创建另一个线程并与之前同时运行。我想要一个可以检查前一个会话中的线程是否仍在运行的机制,如果这样做,则不应该重新创建它。如何实现这一目标?如何在重新打开应用程序时检查前一个会话的线程是否仍在运行?

+0

@JohnVint是的,他们应该。由于该应用程序在Android设备上运行。忽略手机关机的情况,因为那些线程无论如何都会被杀死。 – Miky 2011-12-16 16:24:11

回答

1

在你的线程创建一个

Boolean isRunning = false; 

当你的线程开始 把它放在共享偏好这样的应用..

isRunning = true; 
    SharedPreferences settings = getSharedPreferences("isThreadRunning", 0); 
    SharedPreferences.Editor editor = settings.edit(); 
    editor.putBoolean("isRunning", isRunning); 
    editor.commit(); 

现在,当线程完成只是改变它回到错误。

isRunning = false; 

在你的活动中,只需从这个共享首选项中取出布尔值即可。

SharedPreferences settings = getSharedPreferences("isThreadRunning", 0); 
    boolean running = settings.getBoolean("silentMode", false); //if it doesnt exist it will automatically set to false which means the thread hasnt or isnt running 

then just test. 

if(running){ 
//Do something 
}else{ 
//the thread isnt running so lets start it. 
} 

这是一个非常简单的方法来做到这一点。

希望它有帮助

+1

线程完成并设置为false后,请确保将它放入捆绑软件中,就像我在第一行代码中所做的那样。 – 2011-12-16 16:17:20

+0

感谢这似乎是一个非常好的和简单的解决方案,SharedPreferences关闭时持续发生?因为如果这样做,那么即使该线程被关闭而终止,我的isRunning也会始终设置为true。 – Miky 2011-12-16 16:46:00

1

我写了一个简单的线程列表,然后回来。 user1031312拥有更好的解决方案,但无论如何它是有用的。不知道它是否会列出来自以前会话的线程。它会在一个称为thread_textview的TextView中列出线程名称和ID。

// This method recursively visits all thread groups under 'group'. 
public static void visit(ThreadGroup group, int level) { 
    // Get threads in 'group' 
    int numThreads = group.activeCount(); 
    Thread[] threads = new Thread[numThreads*2]; 
    numThreads = group.enumerate(threads, false); 

    // Enumerate each thread in 'group' 
    for (int i=0; i<numThreads; i++) { 
     // Get thread 
     thread_textview.append("-> "+threads[i].getName()+":"+threads[i].getId()+"\n"); 
    } 

    // Get thread subgroups of 'group' 
    int numGroups = group.activeGroupCount(); 
    ThreadGroup[] groups = new ThreadGroup[numGroups*2]; 
    numGroups = group.enumerate(groups, false); 

    // Recursively visit each subgroup 
    for (int i=0; i<numGroups; i++) { 
     visit(groups[i], level+1); 
    } 
} 
1

您可以使用ServerSocket绑定到端口。一次,操作系统将只允许绑定一个线程。这将防止下一个不执行。

ServerSocket serverSocket = new ServerSocket(1234); 

对于下一个线程,它会抛出BindException。所以你的线程中的第一行,它会做你想做的。

p.s. 1234是未使用的端口号。

另一种选择 - 上面的答案可能不适合你想要的东西,所以这里是另一种选择。

public MyThreadFactory { 

    List<String> runningThreads = new List<String>(); 

    public synchronized void startThread(MyThread thread) { 
      if (! runningThreads.contains(thread.getID())) { 
       runningThreads.add(thread.getID()); 
       // MyThread implements Runnable 
       new Thread(thread).start(); 
      } 
    } 
} 

假设您的线程对象具有getID方法或其他唯一标识其类型的东西。

相关问题