美文网首页
android AlarmManager使用详解

android AlarmManager使用详解

作者: 聆听璇律 | 来源:发表于2018-11-23 16:36 被阅读23次

AlarmManager是android中系统自带的一个提醒服务,比如设置闹钟,做一个定时任务,还可以设置重复操作

AlarmManager中常用的有三个方法:
1、set(int type,long startTime,PendingIntent pi),用于设置一次闹钟。

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

3、setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi),同样是用于设置重复闹钟,但是它是不准确的,相对于第二个方法,也更加节能。

下面就看看这些方法中的参数:
type为闹钟的类型,可分为四个常量:
ELAPSED_REALTIME:闹钟在睡眠状态下不可用,使用的是相对系统启动时间。

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

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

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

startTime:为开始时间
intervalTime:为重复闹钟的间隔时间,内置了几种:
INTERVAL_FIFTEEN_MINUTES 15分钟
INTERVAL_HALF_HOUR 半个小时
INTERVAL_HOUR 一个小时
INTERVAL_HALF_DAY 半天
INTERVAL_DAY 一天

PendingIntent :广播的一个intent,我们用广播接受闹钟的定时任务,注册一个广播去接受,任务指令。
使用PendingIntent的getBroadcast (Context context, int requestCode, Intent intent, int flags)方法可以得到一个发送广播动作的PendingIntent对象
为以下4个常量或其他支持使用Intent.fillIn()来控制它的变量:

FLAG_CANCEL_CURRENT:如果描述的PendingIntent对象已经存在时,会先取消当前的PendingIntent对象再生成新的。

FLAG_NO_CREATE:如果描述的PendingIntent对象不存在,它会返回null而不是去创建它。

FLAG_ONE_SHOT:创建的PendingIntent对象只使用一次。

FLAG_UPDATE_CURRENT:如果描述的PendingIntent对象存在,则保留它,并将新的PendingIntent对象的数据替换进去。

Intent advAlarmIntent = new Intent(this, AdvBroadcastReceiver.class).setAction('自己设置action');
PendingIntent advBroadcast = PendingIntent.getBroadcast(this, 0, advAlarmIntent, 0);//AdvBroadcastReceiver是我自己的广播,换成你自己的
alarmService.setInexactRepeating(AlarmManager.RTC_WAKEUP, '开始时间', '间隔时间', advBroadcast);//这里设置的重复闹钟

另一个就是在manifest.xml中注册自己的广播

public class AdvBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ('自己设置的action'.equals(action)) {
            Log.e("定时任务", "正在下载adv");
        }
    }
}

这样就可以实现定时任务了,如果要定时任务service启动还可以加上service

相关文章

网友评论

      本文标题:android AlarmManager使用详解

      本文链接:https://www.haomeiwen.com/subject/uxwjqqtx.html