我试试并捕获“doInBackground”,如果应用程序在“doInBackground”中执行catch方法,我不希望代码运行onPostExecute。代码如下:
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Void doInBackground(String... aurl) {
try{
//some code, jump to onPostexecute after complete
}
catch{
//some code, don't do onPostExecute after complete
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//some code
}
@Override
protected void onPostExecute(Void unused) {
//some code
}
}
答案 0 :(得分:6)
您可以尝试在cancel(true)
中使用doInBackground()
。请尝试以下代码:
protected Void doInBackground(String... aurl) {
try{
//some code, jump to onPostexecute after complete
}
catch{
cancel(true);
}
return null;
}
关于cancel()
调用此方法将导致调用onCancelled(Object) 在doInBackground(Object [])返回后的UI线程上。打电话给这个 方法保证永远不会调用onPostExecute(Object)。后 调用此方法时,应检查返回的值 isCancelled()定期从doInBackground(Object [])来完成 尽早完成任务。
点击此链接了解更多详情:
http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
答案 1 :(得分:3)
从您的AsyncTask的doInBackground()
到onPostExecute()
返回布尔数据类型。并检查你想要为成功做些什么,
@Override
protected boolean doInBackground(String... aurl) {
try{
//some code, jump to onPostexecute after complete
return true;
}
catch{
//some code, don't do onPostExecute after complete
return false;
}
}
和
@Override
protected void onPostExecute(boolean flag) {
if(flag)
{
//some code
}
}
答案 2 :(得分:1)
您可以在AsyncTask
中设置一个布尔变量并检查该变量。例如:
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {
private boolean run_do_in_background = true;
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Void doInBackground(String... aurl) {
try{
//some code, jump to onPostexecute after complete
}
catch{
//some code, don't do onPostExecute after complete
run_do_in_background = false;
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//some code
}
@Override
protected void onPostExecute(Void unused) {
if(run_do_in_background) { //only if this is true will excecute the code in doInBackground
//some code
}
}
}
答案 3 :(得分:1)
使用Pair,以便返回两个结果
示例,将ANYTHING替换为您要返回的类型:
public class DownloadFileAsync extends AsyncTask<String, Integer, Pair<Exception, ANYTHING> > {
@Override
protected Pair<Exception, ANYTHING> doInBackground(String... aurl) {
try{
return new Pair<Exception, ANYTHING>(null, /* anything can go here */);
}
catch (Exception e) {
return new Pair<Exception, ANYTHING>(e, null);
}
}
@Override
protected void onPostExecute(Pair<Exception, ANYTHING> result) {
// Evaluate the exception here
if(result.first != null) {
// an eror occured, do something about it
}
}
}
这种方式允许你处理onPostExecute中的异常,并且如果一切正常,则从result.second获取结果。