AlarmManager的使用

一般我们用timer和AlarmManager进行定时任务。

先简单说下timer的使用:

 1 TimerTask task = new TimerTask(){  
 2       public void run() {  
 3       Message message = new Message();      
 4       message.what = 1;      
 5       handler.sendMessage(message);    
 6    }  
 7 };
 8 timer = new Timer(true);
 9 timer.schedule(task,1000, 1000); //延时1000ms后执行,1000ms执行一次
10 timer.cancel(); //退出计时器

很简单吧。timer不是说明的重点,我们着重说明下AlarmManager如何实现定时任务的。
先说AlarmManager类的关键函数

setRepeating(int type,long startTime,long intervalTime,PendingIntent pi),用于设置重复闹钟。

第一参数:
ELAPSED_REALTIME:闹钟在睡眠状态下不可用,使用的是相对系统启动时间。

ELAPSED_REALTIME_WAKEUP:闹钟在睡眠状态下可用,使用的是相对系统启动时间。

RTC:闹钟在睡眠状态下不可用,使用的是真实时间。

RTC_WAKEUP:闹钟在睡眠状态下可用,使用的是真实时间。*一般我们使用这个*

第二个参数:延迟时间,即延迟多少时间运行第一条定时任务

第三个参数:第一条之后的任务间隔时间;

第四是pendingIntent字面意义:等待的,未决定的Intent。即将要执行的哪个任务,是服务还是activity。

我的使用方法如下:

1 AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
2 Intent intent =new Intent(UplBasicParams.this, AlarmReceiver.class);
3 intent.setAction(GETADTASKACTION);
4 sender=PendingIntent.getBroadcast(UplBasicParams.this, 0, intent, 0);
5 alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),60*1000, sender);

有时我们需要重置定时任务,那么sender要使用同一个才行。
第4行 getBroadcast 因为要调用的是一个receiver,所以要用这个获取pendingIntent,如果要调用的是服务,需要使用getService来获取pi

好了,就说到这里吧。如果有什么技术问题,欢迎大家共同交流 qq群263862916

原文地址:https://www.cnblogs.com/mytech/p/4037256.html