private Timer timer;
timer = new Timer();
// 1s后执行task,经过6s再次执行
timer.schedule(timerTask, 1000, 1000 * 6);
// 定时刷新
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
//执行任务操作
}
};
};
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
//结束定时任务
timer.cancel();
//这个是在网上找的方法没试过...
二、Handler实现定时任务:void onCreate(){
......
Handler handler = new Handler();
Runnable runnable = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
// 在此处添加执行的代码
handler.postDelayed(this, 50);// 50ms后执行this,即runable
}
};
handler.postDelayed(runnable, 50);// 打开定时器,50ms后执行runnable操作
}
void onDestroy(){
......
handler.removeCallbacks(this);// 关闭定时器处理
}
void onCreate(){
......
Handler handler = new Handler();
Runnable runnable = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
// 在此处添加执行的代码
doSomeThing();
handler.removeCallbacks(this); //移除定时任务
}
};
handler.postDelayed(runnable, 50);// 打开定时器,50ms后执行runnable
}
三, AlarmManager实现精确定时操作:
/**
* 启动或停止定时器
* @param context
* @param isOn 开关
*/
public static void setServiceAlarm(Context context, Boolean isOn) {
Intent intent = new Intent(context, GPSService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (isOn) {
mAlarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), POLL_INTERVAL, pi);
}else {
mAlarmManager.cancel(pi);
pi.cancel();
}
}
/**
* 判断定时器的启动或停止状态
* @param context
* @return
*/
public static boolean isServiceAlarmOn(Context context){
Intent intent = new Intent(context, GPSService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
return pi != null;
}