一个典型AsyncTask的。
01 | public class DialogTestActivity extends Activity { |
02 | private Button button1; |
03 | private Task task; |
04 |
05 | @Override |
06 | public void onCreate(Bundle savedInstanceState) { |
07 | super .onCreate(savedInstanceState); |
08 | setContentView(R.layout.main); |
09 | this .button1 = (Button) findViewById(R.id.button1); |
10 | button1.setOnClickListener( new View.OnClickListener() { |
11 |
12 | @Override |
13 | public void onClick(View v) { |
14 | if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) { |
15 | Toast.makeText(DialogTestActivity. this , "task 正在运行" , Toast.LENGTH_SHORT).show(); |
16 | //task.cancel(true); // 如果Task还在运行,则先取消它 |
17 | } else { |
18 | task = new Task(); |
19 | task.execute(); |
20 | } |
21 | } |
22 | }); |
23 | } |
24 |
25 | @Override |
26 | protected void onDestroy() { |
27 | super .onDestroy(); |
28 | // 用户按回退的时候要取消正在进行的任务 |
29 | task.cancel( true ); |
30 | } |
31 |
32 | private class Task extends AsyncTask<Void, Void, Void> { |
33 | |
34 | @Override |
35 | protected void onPreExecute() { |
36 | super .onPreExecute(); |
37 | Toast.makeText(DialogTestActivity. this , "task 开始运行" , Toast.LENGTH_SHORT).show(); |
38 | } |
39 | |
40 | @Override |
41 | protected Void doInBackground(Void... params) { |
42 | try { |
43 | // 模拟耗时操作 比如网络连接等 |
44 | Thread.sleep( 5000 ); |
45 | } catch (InterruptedException e) { |
46 | e.printStackTrace(); |
47 | } |
48 | // 判断如果task已经cancel就没有必须继续进行下面的操作 |
49 | if (!isCancelled()) { |
50 | System.out.println( "task 如果被cancel,就不会显示" ); |
51 | } |
52 | return null ; |
53 | } |
54 |
55 | @Override |
56 | protected void onPostExecute(Void result) { |
57 | super .onPostExecute(result); |
58 | Toast.makeText(DialogTestActivity. this , "task 完成" , Toast.LENGTH_SHORT).show(); |
59 | // 所有调用当前context的对象要注意判断activity是否还存在 |
60 | // 典型的比如弹窗 |
61 | if (!isFinishing()) { |
62 | try { |
63 | createAlertDialog().show(); |
64 | } catch (Exception e) { |
65 | } |
66 | } |
67 | } |
68 |
69 | @Override |
70 | protected void onCancelled() { |
71 | super .onCancelled(); |
72 | System.out.println( "task 取消" ); |
73 | } |
74 |
75 | } |
76 |
77 | private AlertDialog createAlertDialog() { |
78 | return new AlertDialog.Builder(DialogTestActivity. this ).setTitle( "fadfasdf" ) |
79 | .setPositiveButton( "OK" , new DialogInterface.OnClickListener() { |
80 | public void onClick(DialogInterface dialog, int whichButton) { |
81 |
82 | } |
83 | }).setNegativeButton( "Cancel" , new DialogInterface.OnClickListener() { |
84 | public void onClick(DialogInterface dialog, int whichButton) { |
85 |
86 | } |
87 | }).create(); |
88 | } |
89 | } |