AlarmManager详解:android中的定时任务

1.概述

AlarmManager通常用途是用来开发手机闹钟,但是AlarmManager的用处并只是这个。AlarmManager其实是一个全局定时器,它可以在指定时间或指定周期启动其他组件,在特定的时刻为我们广播一个指定的Intent。简单的说就是我们设定一个时间,当到达这个时间,就会发出广播提醒我们.

2.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)
    下面我们讲一下这三个方法的用途

2.1首先了解一下 type

我们去看源码发现type就分为四种

  • AlarmManager.ELAPSED_REALTIME
    状态值为3,
    在指定的延时过后,发送广播,但不唤醒设备(闹钟在睡眠状态下不可用)。如果在系统休眠时闹钟触发,不会激活设备执行事件。

  • AlarmManager.ELAPSED_REALTIME_WAKEUP
    状态值为2,
    顾名思义,在指定的延时过后,发送广播,如果设备休眠就会唤醒设备,发出广播执行事件

  • AlarmManager.RTC
    状态值为1,
    该状态下闹钟使用绝对时间,也就是指定当系统调用System.currentTimeMillis()方法返回的值与triggerAtTime相等时启动operation所对应的设备(在指定的时刻,发送广播,但不唤醒设备)。如果在系统休眠时闹钟触发,它将不会被传递,直到下一次设备唤醒(闹钟在睡眠状态下不可用)。

  • AlarmManager.RTC_WAKEUP
    状态值为0
    闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用绝对时间,,也就是指定当系统调用System.currentTimeMillis()方法返回的值与triggerAtTime相等时启动operation所对应的设备
  • AlarmManager.POWER_OFF_WAKEUP
    状态值为4
    表示闹钟在手机关机状态下也能正常进行提示功能,

2.2set(int type,long startTime,PendingIntent pi)设置一次性闹钟

也就是闹钟只执行一次,当执行完之后,不会再次执行

  • 参数1 type: 就是上面的type
  • 参数2 startTime 闹钟执行的时间
  • 参数3 pi 执行的事件

2.3 setRepeating(int type,long startTime,long intervalTime,PendingIntent pi)周期性执行的定时服务

  • 参数1 type: 就是上面的type
  • 参数2 startTime 闹钟执行的时间
  • 参数3 intervalTime 间隔时间 详情请看 2.3.1
  • 参数4 pi 执行的事件

2.3.1 intervalTime的解释

AlarmManager.INTERVAL_FIFTEEN_MINUTES 间隔15分钟
AlarmManager.INTERVAL_HALF_HOUR 间隔半个小时
AlarmManager.INTERVAL_HOUR 间隔一个小时
AlarmManager.INTERVAL_HALF_DAY 间隔半天
AlarmManager.INTERVAL_DAY 间隔一天

2.4setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi)此方法跟2.3基本上相似,只不过这个方法优化了很多,省电

3 使用步骤

  1. 获得AlarmManager实例
    ALarmManager manager=(ALarmManager)getSystemService(ALARM_SERVICE)
  2. 定义PendingIntent发出的广播
  3. 调用AlarmManager方式设置定时或者重复提醒
  4. 取消提醒

3.1 定义的PendingIntent

Intent intent = new Intent(AlarmTest.this,
        AlarmActivity.class);
//AlarmActivity就是当闹钟提醒的时候打开的activity,你也可以发送广播
intent.setAction("nzy");
// 创建PendingIntent对象
PendingIntent pi = PendingIntent.getActivity(
        AlarmTest.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
// 根据用户选择时间来设置Calendar对象
calendar.set(Calendar.HOUR, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
// 设置AlarmManager将在Calendar对应的时间启动指定组件
aManager.set(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(), pi);

3.2 取消闹钟

Intent intent = new Intent(AlarmTest.this, AlarmActivity.class); intent.setAction("nzy");
//这里的action必须和上面设置的action一样 也就是取消的唯一标识
PendingIntent pendingIntent = PendingIntent.getActivity( AlarmTest.this, 0, intent, 0);  // 创建PendingIntent对象 
aManager.cancel(pendingIntent);

猜你喜欢

转载自blog.csdn.net/qq_33408235/article/details/77935087