java学习_Timer相关

1.Timer

Timer outTimer=null;
OutTimerTask outTimeTask=null;


//构造&初始化

outTimer = new Timer();


//开启超时

outTimeTask = new OutTimerTask();//每次都要构造新的TimerTask,TimerTask被cancle掉就不能再用了
outTimer.schedule(outTimeTask, 40*1000);//40s超时


	private class OutTimerTask extends TimerTask{
		@Override
		public void run() {
			cancel();
			//在这里做的就是超时处理
		}
	}


也可以写一个工具类:

import java.util.TimerTask;

public class OutTimerTask extends TimerTask {
	public interface OutTimerTaskWatcher {
		public void timeOutNotify(int id);
	}
	
	//data..
	OutTimerTaskWatcher watcher;
	int id=0;
	//=end: data..

	public OutTimerTask(OutTimerTaskWatcher watcher, int id) {
		this.watcher = watcher;
		this.id = id;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		watcher.timeOutNotify(id);
	}

}



2.AlarmManager(for android)

如果把一个timer放在Activity或Service里,时间长了很可能被干掉。

所以Android提供了AlarmManager,我们只需要注册

//闹钟到时后触发的动作,定义在这里。这是启动一个Service,也可以是BroadcastReceiver,详见ApiDemo
PendingIntent  mAlarmSender = PendingIntent.getService(MainActivity.this,
                0, new Intent(MainActivity.this, TaskService.class), 0);

// Schedule the alarm!
                AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
                am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                firstTime, Common.TaskAlarmRate, mAlarmSender);

// And cancel the alarm.
                AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
                am.cancel(mAlarmSender);



s




s


你可能感兴趣的:(java学习_Timer相关)