使用AsyncTask的一些技巧(转)

异步任务还可以取消,在Activity或者Fragment销毁等状态后,耗时任务便需要停止。

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还在运行,则先取消它
				} 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();
	}
}

 超时处理

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class TimeoutTestActivity extends Activity {
	private final static int TIME_OUT = 3 * 1000;
	private final static int SLEEP_TIME = 2 * 1000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//new TimeOutTask().execute();
		new CancelSelfWhenTimeOutTask().execute();
	}

	private class CancelSelfWhenTimeOutTask extends AsyncTask<Void, Void, Void> {
		private boolean done = false;

		@Override
		protected Void doInBackground(Void... params) {
			cancelSelfWhenTimeOut();
			sleep();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Toast.makeText(TimeoutTestActivity.this, "任务完成", Toast.LENGTH_SHORT)
					.show();
		}

		private void cancelSelfWhenTimeOut() {
			new Timer().schedule(new TimerTask() {

				@Override
				public void run() {
					if (!done) {
						CancelSelfWhenTimeOutTask.this.cancel(true);
					}
				}
			}, TIME_OUT);
		}

		private void sleep() {
			try {
				Thread.sleep(SLEEP_TIME);
				done = true;
			} catch (InterruptedException e) {
			}
		}
	}

	private class TimeOutTask extends AsyncTask<Void, Void, Void> {
		private boolean done = false;
		private boolean isTimeOut = false;

		@Override
		protected Void doInBackground(Void... params) {
			try {
				throwTimeOutException();
			} catch (Exception e) {
				isTimeOut = true;
			}
			sleep();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (isTimeOut) {
				Toast.makeText(TimeoutTestActivity.this, "任务超时",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(TimeoutTestActivity.this, "任务完成",
						Toast.LENGTH_SHORT).show();
			}
		}

		private void throwTimeOutException() {
			new Timer().schedule(new TimerTask() {

				@Override
				public void run() {
					if (!done) {
						isTimeOut = true;
					}
				}
			}, TIME_OUT);
		}

		private void sleep() {
			try {
				Thread.sleep(SLEEP_TIME);
				done = true;
			} catch (InterruptedException e) {
			}
		}
	}

}
原文地址:https://www.cnblogs.com/weixiao870428/p/3543871.html