我的解决方案是创建自己的 asynctask 类:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import br.com.zcr.ezcrm.R;
public class AsyncTask implements Runnable {
private Activity activity;
private Handler handler;
private Action action;
private boolean showDialog = true;
private boolean running = false;
private boolean canceled = false;
private Thread t;
private ProgressDialog progress;
public AsyncTask(Activity activity) {
this.activity = activity;
handler = new Handler();
}
public AsyncTask(Activity activity, Action action) {
this.activity = activity;
this.action = action;
handler = new Handler();
}
private ProgressDialog getDialog() {
if (progress != null)
return progress;
progress = ProgressDialog.show(activity, null, activity.getString(R.string.carregando), true, false);
progress.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
setCanceled(true);
}
});
return progress;
}
private void showDialog() {
if (showDialog)
getDialog().show();
}
private void hideDialog() {
if (showDialog)
getDialog().dismiss();
}
public void execute(boolean showDialog) {
this.showDialog = showDialog;
execute();
}
public void execute() {
if (running || action == null)
return;
running = true;
// Utils.setFixedOrientation(activity);
showDialog();
t = new Thread(AsyncTask.this);
t.start();
}
@Override
public void run() {
try {
final Object o = action.run();
if (canceled)
return;
handler.post(new Runnable() {
public void run() {
action.onFinnish(o);
}
});
} catch (final Exception e) {
if (canceled)
return;
handler.post(new Runnable() {
public void run() {
action.onError(e);
}
});
} finally {
canceled = false;
hideDialog();
// Utils.setUnfixedOrientation(activity);
running = false;
}
}
/*
* public void stop() { running = false; }
*/
public void setAction(Action a) {
action = a;
}
public void setCanceled(boolean canceled) {
if (canceled)
t = null;
this.canceled = canceled;
}
public interface Action {
/** Acao a ser executada */
public Object run() throws Exception;
/** Chamado no fim de todas as execucoes */
public void onFinnish(Object result);
/** Para qualquer execucao e retorna o erro */
public void onError(Exception e);
}
}
这是实现:
AsyncTask task = new AsyncTask(this, new Action() {
public Object run() throws Exception {
return WebService.autenticate(login, pass);
}
public void onFinnish(Object result) {
//result was returned in run method
verifyLogin((String) result);
}
public void onError(Exception e) {
//error
}
});