读书人

您真的会用AsyncTask吗

发布时间: 2012-09-21 15:47:26 作者: rapoo

你真的会用AsyncTask吗
一个典型的AsyncTask应用

public class DialogTestActivity extends Activity {private Button button1;private Task task;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);this.button1 = (Button) findViewById(R.id.button1);button1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {Toast.makeText(DialogTestActivity.this, "task 正在运行", Toast.LENGTH_SHORT).show();//task.cancel(true);  //  如果Task还在运行,则先取消它//task = null;} else {task = new Task();task.execute();}}});}@Overrideprotected void onDestroy() {super.onDestroy();// 用户按回退的时候要取消正在进行的任务task.cancel(true);}private class Task extends AsyncTask<Void, Void, Void> {@Overrideprotected void onPreExecute() {super.onPreExecute();Toast.makeText(DialogTestActivity.this, "task 开始运行", Toast.LENGTH_SHORT).show();}@Overrideprotected Void doInBackground(Void... params) {try {// 模拟耗时操作 比如网络连接等Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}// 判断如果task已经cancel就没有必须继续进行下面的操作if (!isCancelled()) {System.out.println("task 如果被cancel,就不会显示");}return null;}@Overrideprotected void onPostExecute(Void result) {super.onPostExecute(result);Toast.makeText(DialogTestActivity.this, "task 完成", Toast.LENGTH_SHORT).show();// 所有调用当前context的对象要注意判断activity是否还存在// 典型的比如弹窗if (!isFinishing()) {try {createAlertDialog().show();} catch (Exception e) {}}}@Overrideprotected void onCancelled() {super.onCancelled();System.out.println("task 取消");}}private AlertDialog createAlertDialog() {return new AlertDialog.Builder(DialogTestActivity.this).setTitle("fadfasdf").setPositiveButton("OK", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int whichButton) {}}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int whichButton) {}}).create();}}

读书人网 >移动开发

热点推荐