Stop the AsyncTask
Description
The following code shows how to Stop the AsyncTask.
Example
Main layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<Button
android:id="@+id/btnStartCounter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"
android:onClick="startCounter" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Main Activity Java code
package com.java2s.myapplication4.app;
/* ww w.j a v a 2 s. c o m*/
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
static TextView txtView1;
DoCountingTask task;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView1 = (TextView) findViewById(R.id.textView1);
}
public void startCounter(View view) {
task = (DoCountingTask) new DoCountingTask().execute();
}
public void stopCounter(View view) {
task.cancel(true);
}
private class DoCountingTask extends AsyncTask<Void, Integer, Void> {
protected Void doInBackground(Void... params) {
for (int i = 0; i < 1000; i++) {
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d ("Threading", e.getLocalizedMessage());
}
if (isCancelled()) break;
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
txtView1.setText(progress[0].toString());
Log.d ("Threading", "updating...");
}
}
@Override
protected void onPause() {
super.onPause();
stopCounter(txtView1);
}
}
The preceding code will update the UI safely from another thread.
Note
To stop the AsyncTask subclass, you need to get an instance of it first and call its cancel() method.
Within the task, you call the isCancelled() method to check whether the task should be terminated.