1import android.app.Activity;
2import android.os.AsyncTask;
3import android.os.Bundle;
4import android.provider.Settings.System;
5import android.view.View;
6import android.widget.Button;
7import android.widget.TextView;
8import android.view.View.OnClickListener;
9
10public class AsyncTaskActivity extends Activity implements OnClickListener {
11
12 Button btn;
13 AsyncTask<?, ?, ?> runningTask;
14
15 @Override
16 protected void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.main);
19 btn = findViewById(R.id.button1);
20
21 // Because we implement OnClickListener, we only
22 // have to pass "this" (much easier)
23 btn.setOnClickListener(this);
24 }
25
26 @Override
27 public void onClick(View view) {
28 // Detect the view that was "clicked"
29 switch (view.getId()) {
30 case R.id.button1:
31 if (runningTask != null)
32 runningTask.cancel(true);
33 runningTask = new LongOperation();
34 runningTask.execute();
35 break;
36 }
37 }
38
39 @Override
40 protected void onDestroy() {
41 super.onDestroy();
42 // Cancel running task(s) to avoid memory leaks
43 if (runningTask != null)
44 runningTask.cancel(true);
45 }
46
47 private final class LongOperation extends AsyncTask<Void, Void, String> {
48
49 @Override
50 protected String doInBackground(Void... params) {
51 for (int i = 0; i < 5; i++) {
52 try {
53 Thread.sleep(1000);
54 } catch (InterruptedException e) {
55 // We were cancelled; stop sleeping!
56 }
57 }
58 return "Executed";
59 }
60
61 @Override
62 protected void onPostExecute(String result) {
63 TextView txt = (TextView) findViewById(R.id.output);
64 txt.setText("Executed"); // txt.setText(result);
65 // You might want to change "executed" for the returned string
66 // passed into onPostExecute(), but that is up to you
67 }
68 }
69}
70