计时器Timer_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 计时器Timer

计时器Timer

 2013/11/4 12:35:50  HU555U  程序员俱乐部  我要评论(0)
  • 摘要:publicclassMainActivityextendsActivity{privateGetDataTasktask;privateTimertimer=newTimer();privateTimerTasktimerTask=newTimerTask(){@Overridepublicvoidrun(){handler.sendEmptyMessage(0);}};privateHandlerhandler=newHandler()
  • 标签:
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,就会打印信息。
  • 相关文章
发表评论
用户名: 匿名