一个典型AsyncTask的。
01 |
public class DialogTestActivity extends Activity |
02 |
private Button |
03 |
private Task |
04 |
05 |
@Override |
06 |
public void onCreate(Bundle |
07 |
super .onCreate(savedInstanceState); |
08 |
setContentView(R.layout.main); |
09 |
this .button1 |
10 |
button1.setOnClickListener( new View.OnClickListener() |
11 |
12 |
@Override |
13 |
public void onClick(View |
14 |
if (task null && |
15 |
Toast.makeText(DialogTestActivity. this , "task , |
16 |
//task.cancel(true); |
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, |
33 |
|
34 |
@Override |
35 |
protected void onPreExecute() |
36 |
super .onPreExecute(); |
37 |
Toast.makeText(DialogTestActivity. this , "task , |
38 |
} |
39 |
|
40 |
@Override |
41 |
protected Void |
42 |
try { |
43 |
// |
44 |
Thread.sleep( 5000 ); |
45 |
} catch (InterruptedException |
46 |
e.printStackTrace(); |
47 |
} |
48 |
// |
49 |
if (!isCancelled()) |
50 |
System.out.println( "task ); |
51 |
} |
52 |
return null ; |
53 |
} |
54 |
55 |
@Override |
56 |
protected void onPostExecute(Void |
57 |
super .onPostExecute(result); |
58 |
Toast.makeText(DialogTestActivity. this , "task , |
59 |
// |
60 |
// |
61 |
if (!isFinishing()) |
62 |
try { |
63 |
createAlertDialog().show(); |
64 |
} catch (Exception |
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 |
78 |
return new AlertDialog.Builder(DialogTestActivity. this ).setTitle( "fadfasdf" ) |
79 |
.setPositiveButton( "OK" , new DialogInterface.OnClickListener() |
80 |
public void onClick(DialogInterface int whichButton) |
81 |
82 |
} |
83 |
}).setNegativeButton( "Cancel" , new DialogInterface.OnClickListener() |
84 |
public void onClick(DialogInterface int whichButton) |
85 |
86 |
} |
87 |
}).create(); |
88 |
} |
89 |
} |