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{ 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 { 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) { } } }}