class="java">
public class MainActivity extends Activity {
private GetDataTask task;
private Timer timer = new Timer();
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
};
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
System.out.println("-------------");;
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (null != task) task.cancel(true);
task = new GetDataTask();
task.execute();
}
private class GetDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
timer.schedule(timerTask, 5 * 1000);
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3 * 1000);
//Thread.sleep(8 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
task = null;
timer.cancel();
handler.removeCallbacks(timerTask);
handler.removeMessages(0);
}
}
}
说明:首先让计时器延时5秒执行timeTask,如果
线程睡眠3秒,那么3秒后timer被取消,timeTask不会执行,就不会有打印信息。如果线程睡眠8秒,那么5秒后就会执行timeTask,就会打印信息。