您的位置:首页 > 其它

AlarmManager的使用

2014-10-20 15:07 127 查看
一般我们用timer和AlarmManager进行定时任务。

先简单说下timer的使用:

TimerTask task = new TimerTask(){
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
timer = new Timer(true);
timer.schedule(task,1000, 1000); //延时1000ms后执行,1000ms执行一次
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。

我的使用方法如下:

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


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

好了,就说到这里吧。如果有什么技术问题,欢迎大家共同交流 qq群263862916
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: