2014-09-21 66 views
0

在我的android應用程序中,我使用一個線程來下載一些數據。在Android中強制關閉線程

這是目前工作代碼的原型:當下載數據形成的服務器是非常緩慢的發生

void startThread() 
{ 
    thread = new Thread(this); 
    thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND); 
    thread.start(); 
} 

@Override 
public void run() 
{ 
    while(application_running) 
    { 
     //download my data... (on slow server response, execution gets stuck here) 
    } 
} 

問題。雖然我關閉了應用程序:數據下載線程仍然活着。但是我需要這個線程在應用程序關閉後立即關閉。

有什麼辦法強制關閉它嗎?或者其他任何標準的方式來下載數據?

+0

你可以在'onPause()'方法中調用'thread.interrupt()'方法來停止線程,併爲你的問題在慢速連接後發佈logcat錯誤 – 2014-09-21 06:58:41

回答

0

使用與您的活動(或片段)生命週期關聯的AsyncTask。

http://developer.android.com/reference/android/os/AsyncTask.html

假設你有你的AsyncTask稱爲T成員變量,它已經在您的活動或片段的其他地方開始,你可以做的onDestroy下列():

if ((t != null) && !t.isCancelled()) 
    { 
     boolean mayInterruptIfRunning = true; 
     t.cancel(mayInterruptIfRunning); 
     t = null; 
    } 

使用AsyncTask還有一個好處,即允許您在UI線程上安全地更新UI以獲取進度報告,並且通過重寫onProgressUpdate和onPostExecute方法完成後臺任務。