1.导入类:import android.os.AsyncTask;
2.如下方法:
private TestAsyncTask mTestAsyncTask;
private void testAsync() {
if (mTestAsyncTask != null && mTestAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
//cancel exsiting task first
mTestAsyncTask.cancel(true);
}
mTestAsyncTask = new TestAsyncTask();
mTestAsyncTask.execute();
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//do background jobs here
return null;
}
@Override
protected void onPostExecute(Void result) {
//finish jobs here
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}