开发者

Android get out of doInBackgroundThread without leaving the activity?

this all started because I wanted to display a toast message in a background thread. (Toast messages crash the app when trying to load them without telling them to load on UI thread) Now I realize I want to display a toast message AND close the background thread, this is a kind of error handling and letting the user know of the error.

The 开发者_JAVA百科desired condition in the background thread takes the user to a new activity and finishes the current one. That works.

Now I noticed that I don't know of another way to end the backgroundthread and show the toast message on the same activity?

How do I end the background thread from doInBackground?


You need to execute the cancel() method for your task. Then when it's cancelled rather than running the onPostExecute() it will call onCancelled(). Put your Toast message in there.


RD If I may suggest a rather twisted method of handling errors in a background thread. Consider wrapping the calls in the background thread in a try catch and return a stateful object. So if you want the background thread to return a string, create a BoolString class.

//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;
 }
}

Usage:

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;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜