2013-06-26 69 views
0

我似乎無法找到這個問題的答案。我擁有的是以下內容,我有一個活動可以產生8個線程來完成某些事情,這些線程需要在活動關閉並且工作時保持活動狀態。我遇到的問題是當我再次打開活動時,它會產生同一個線程的另一個實例。在Android中殺死/停止重複線程

我在eclipse中使用DDMS來驗證線程的多個副本正在產生,我也有一個toast消息,每秒輸出線程的ID來驗證確實有兩個運行線程的副本。

所以我的問題是,我如何避免線程的多個實例運行或如何殺死較舊的實例?

其中一個線程的示例如下。

new Thread(new Runnable() 
    { 
     public void run() 
     { 
      while(true) 
      { 
       DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); // This is where we read the global date and time into our string 
       currentDateTimeString = df.format(new Date()); 

       DateFormat womm = new SimpleDateFormat("mm");     // This is where we read the minute of the wait one minute into our string 
       WOMMinString = womm.format(new Date()); 

       DateFormat womh = new SimpleDateFormat("hh");     // This is where we read the hour of the wait one minute into our string 
       WOMHourString = womh.format(new Date()); 

       DateFormat cds = new SimpleDateFormat("dd");     // This is where we read the current day into our string 
       currentDayString = cds.format(new Date()); 

       DateFormat cms = new SimpleDateFormat("MM");     // This is where we read the current month into our string 
       currentMonthString = cms.format(new Date()); 

       DateFormat cys = new SimpleDateFormat("yyyy");     // This is where we read the current year into our string 
       currentYearString = cys.format(new Date()); 

       try 
       { 
        Thread.sleep(1000); 
       } 
       catch (InterruptedException e1) 
       { 
        appendLog("Could not sleep the thread (Main 2) " + currentDateTimeString + ""); 
       } 
      } 
     } 
    }).start(); 

謝謝。

回答

0

存儲在一個實例變量的參考線:

private Thread myWorker; 

onResume()檢查線程是否正在運行,如果沒有,創建一個新的開始吧。

請注意,Android在電力和內存消耗方面有一個非常嚴格的政策,所以您的應用程序可能隨時被殺死,包括您的線程。此外,活動應該可以隨時暫停和停止。確保活動暫停或停止時,您的線程已正確停止。

因此,進行長期計算的最佳方法是使用Service類而不是Activity。您仍然必須爲您的工作創建不同的線程,但生命週期稍微放鬆一些。

參考文獻:

+0

我的線程需要在活動被關閉保持活躍,這是一個後臺線程。所以我不能停止或關閉線程。問題是,當我重新進入活動時,我不想讓兩個實例出現。 – Maverick

+0

只需創建一個單獨的「Service」類並從「Activity」類啓動此服務。在'服務'中,運行你的線程。這將是正確的做法。 「服務」獨立於「活動」的生命週期。但是,當應用程序被用戶或操作系統強制關閉時,它也會被殺死。 – nif

+0

線程訪問活動中聲明的太多變量,它只是太忙了,以至於無法正常工作,會先看看是否沒有其他方法。 – Maverick