2011-04-08 138 views
0

這一切都開始了,因爲我想在後臺線程中顯示Toast消息。 (Toast消息在嘗試加載它們時會崩潰而不告訴它們加載UI線程)現在我意識到我想要顯示Toast消息並關閉後臺線程,這是一種錯誤處理並讓用戶知道錯誤。Android離開doInBackgroundThread而不離開活動?

後臺線程中的所需條件將用戶帶到新的活動並完成當前的活動。這樣可行。

現在我注意到,我不知道另一種方式來結束backgroundthread並在同一活動上顯示吐司消息?

如何從doInBackground結束後臺線程?

回答

0

您需要爲您的任務執行cancel()方法。然後,當它取消而不是運行onPostExecute()時,它會調用onCancelled()。把你的Toast消息放在那裏。

+0

謝謝取消方法關閉對話框,我不能讓onCancelled()永遠執行,但! – CQM 2011-04-09 22:16:52

+0

在調用我的後臺線程的活動中,我有一個_initTask.cancel(true),用於在活動停止時停止後臺線程。然後在我的doInBackground()方法中,在嘗試返回之前檢查this.isCancelled()。當doInBackground()檢測到isCancelled()時,它會自動執行onCancelled()方法,而不是onPostExecuteMethod()。 – 2011-04-10 23:14:31

0

RD如果我可能會建議一個相當扭曲的方法來處理後臺線程中的錯誤。考慮將調用包裝在後臺線程的try catch中並返回一個有狀態的對象。所以如果你想要後臺線程返回一個字符串,創建一個BoolString類。

//a utility class to signal success or failure, return an error message, and return a useful String value 
//see Try Out in C# 
public final class BoolString { 
public final boolean success; 
public final String err; 
public final String value; 

public BoolString(boolean success, String err, String value){ 
    this.success= success; 
    this.err= err; 
    this.value= value; 
} 
} 

用法:

public BoolString tryEncrypt(String inString, String password) { 
    try { 
     String value= encrypt(inString, password); 
     return new BoolString(true,"",value); 
    } 
    catch (GeneralSecurityException e){ 
     return new BoolString(false,e.getMessage(),""); 
    } 
} 

    protected void onPostExecute(BoolString result){   
     progress.dismiss(); 
     if (result.success){ 
       result.value; 
     } 
     else { 
       result.err; 
     } 
    }