android的全局定时器AlarmManager详解

个人主页已迁移到: http://www.blog4app.com


AlarmManager对象配合Intent使用,可以定时开启一个Activity,发送一个BroadCast或者开启一个Service。

 

AlarmManager有如下用法:

 

(1)在指定时间后,执行某操作

 

Intent intent=new Intent(this,ShowUtil.class); PendingIntent sender=PendingIntent.getBroadcast(this, 0, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+4*1000, sender);//4秒后执行 

 

 

(2)周期性执行某动作

 

Intent intent=new Intent(this,ShowUtil.class); PendingIntent sender=PendingIntent.getBroadcast(this, 0, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 5*1000, sender);//每5秒执行一次 //alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 5*1000, sender);//每5秒执行一次 

 

 

 

(3)关于同时定义多个定时器和关闭指定定时器

 

 

 

public static PendingIntent sender1; public static PendingIntent sender2; Intent intent=new Intent(this,ShowUtil.class); sender1=PendingIntent.getBroadcast(this, 1, intent, 0);//第二个参数,用来标识不同的send sender2=PendingIntent.getBroadcast(this, 2, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2*1000, sender1); alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5*1000, sender2); //在其他地方 AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); alarm.cancel(**.sender1); alarm.cancel(**.sender2); 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(android,service)