如何停止正在运行的AsyncTask

网上查到的最好的办法
public class MyTask extends AsyncTask {

private volatile boolean running = true;
private final ProgressDialog progressDialog;

public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);

progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});

}

@Override
protected void onPreExecute() {
progressDialog.show();
}

@Override
protected void onCancelled() {
running = false;
}

@Override
protected Void doInBackground(Void... params) {

while (running) {
// does the hard work
}
return null;
}

// ...

}


你可能感兴趣的:(android)