`

你真的会用AsyncTask吗

 
阅读更多
一个典型的AsyncTask应用
public class DialogTestActivity extends Activity {
	private Button button1;
	private Task task;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.button1 = (Button) findViewById(R.id.button1);
		button1.setOnClickListener(new View.OnClickListener() {

			@Override
			public 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();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 用户按回退的时候要取消正在进行的任务
		task.cancel(true);
	}

	private class Task extends AsyncTask<Void, Void, Void> {
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Toast.makeText(DialogTestActivity.this, "task 开始运行", Toast.LENGTH_SHORT).show();
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			try {
				// 模拟耗时操作 比如网络连接等
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 判断如果task已经cancel就没有必须继续进行下面的操作
			if (!isCancelled()) {
				System.out.println("task 如果被cancel,就不会显示");
			}
			return null;
		}

		@Override
		protected 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) {
				}
			}
		}

		@Override
		protected 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();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics