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();
謝謝。
我的線程需要在活動被關閉保持活躍,這是一個後臺線程。所以我不能停止或關閉線程。問題是,當我重新進入活動時,我不想讓兩個實例出現。 – Maverick
只需創建一個單獨的「Service」類並從「Activity」類啓動此服務。在'服務'中,運行你的線程。這將是正確的做法。 「服務」獨立於「活動」的生命週期。但是,當應用程序被用戶或操作系統強制關閉時,它也會被殺死。 – nif
線程訪問活動中聲明的太多變量,它只是太忙了,以至於無法正常工作,會先看看是否沒有其他方法。 – Maverick