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;
}
}
來源
2011-04-09 04:58:58
JAL
謝謝取消方法關閉對話框,我不能讓onCancelled()永遠執行,但! – CQM 2011-04-09 22:16:52
在調用我的後臺線程的活動中,我有一個_initTask.cancel(true),用於在活動停止時停止後臺線程。然後在我的doInBackground()方法中,在嘗試返回之前檢查this.isCancelled()。當doInBackground()檢測到isCancelled()時,它會自動執行onCancelled()方法,而不是onPostExecuteMethod()。 – 2011-04-10 23:14:31