AlarmManager+Notification实现定时通知提醒功能

AlarmManager简介

AlarmManager实质是一个全局的定时器,是Android中常用的一种系统级别的提示服务,在指定时间或周期性启动其它组件(包括Activity,Service,BroadcastReceiver)。本文将讲解一下如何使用AlarmManager实现定时提醒功能。

闹钟配置

周期闹钟

Intent intent = new Intent();
intent.setAction(GlobalValues.TIMER_ACTION_REPEATING);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5 * 1000, 3 * 1000, sender);
setRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

该方法用于设置周期性执行的定时服务。type:闹钟类型,startTime:闹钟首次执行时间,intervalTime:闹钟两次执行的间隔时间,pi:闹钟响应动作。

setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

该方法也用于设置周期定式服务,与上一种类似。不过其两个闹钟执行的间隔时间不是固定的。它相对而言更省电一些,因为系统可能会将几个差不多的闹钟合并为一个来执行,减少设备的唤醒次数。

intervalTime内置变量

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

定时闹钟

//获得系统提供的AlarmManager服务的对象
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//Intent设置要启动的组件,这里启动广播
Intent myIntent = new Intent();
myIntent.setAction(GlobalValues.TIMER_ACTION);
//PendingIntent对象设置动作,启动的是Activity还是Service,或广播!
PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);
//注册闹钟
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5 * 1000, sender);
set(int type,long startTime,PendingIntent pi)

该方法用于设置一次性定时服务。type:闹钟类型,startTime:闹钟执行时间,pi:闹钟响应动作。

取消闹钟

Intent myIntent = new Intent();
myIntent.setAction(GlobalValues.TIMER_ACTION);
//myIntent.setAction(GlobalValues.TIMER_ACTION_REPEATING);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(sender);

设置多个闹钟:

若连续设置多个闹钟,则只有最后一个闹钟会生效,那么这种情况我们怎么处理呢?其实很简单。我们可以给每个闹钟设置唯一的id,传入getBroadcast()第二个参数。在这里我是每设置一个id则自增1存入Shareprefrence里,保证id唯一性。

 //给每个闹钟设置不同ID防止覆盖
int alarmId = SharedPreUtils.getInteger(context, "alarm_id", 0);
SharedPreUtils.setInteger(context, "alarm_id", ++alarmId);
PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);

在取消闹钟时我们也可以根据这个id关闭不同的闹钟。

参数详解

type:闹钟类型

ELAPSED_REALTIME:
在指定的延时过后,发送广播,但不唤醒设备(闹钟在睡眠状态下不可用)。如果在系统休眠时闹钟触发,它将不会被传递,直到下一次设备唤醒。

ELAPSED_REALTIME_WAKEUP:
在指定的延时过后,发送广播,并唤醒设备(即使关机也会执行operation所对应的组件) 。延时是要把系统启动的时间SystemClock.elapsedRealtime()算进去的。

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

RTC_WAKEUP:
指定当系统调用System.currentTimeMillis()方法返回的值与triggerAtTime相等时启动operation所对应的设备(在指定的时刻,发送广播,并唤醒设备)。即使系统关机也会执行operation所对应的组件。

POWER_OFF_WAKEUP:
表示闹钟在手机关机状态下也能正常进行提示功能,所以是5个状态中用的最多的状态之一,该状态下闹钟也是用绝对时间,状态值为4;不过本状态好像受SDK版本影响,某些版本并不支持。

long intervalTime:执行时间

闹钟的第一次执行时间,以毫秒为单位,可以自定义时间,不过一般使用当前时间。需要注意的是,本属性与第一个属性(type)密切相关。

如果第一个参数对应的闹钟使用的是相对时间(ELAPSED_REALTIME和ELAPSED_REALTIME_WAKEUP),那么本属性就得使用相对时间(相对于系统启动时间来说),比如当前时间就表示为:SystemClock.elapsedRealtime();

如果第一个参数对应的闹钟使用的是绝对时间(RTC、RTC_WAKEUP、POWER_OFF_WAKEUP),那么本属性就得使用绝对时间,比如当前时间就表示为:System.currentTimeMillis()

long startTime:间隔时间

对于周期定时方式来说,存在本属性,表示两次闹钟执行的间隔时间,也是以毫秒为单位。

PendingIntent pi:执行动作

是闹钟的执行动作,比如发送一个广播、给出提示等等。PendingIntent是Intent的封装类,需要注意的是:

  • 如果是通过启动服务来实现闹钟提示的话,PendingIntent对象的获取就应该采用Pending.getService(Context c,int i,Intent intent,int j)方法。
  • 如果是通过广播来实现闹钟提示的话,PendingIntent对象的获取就应该采用PendingIntent.getBroadcast(Context c,int i,Intent intent,int j)方法。
  • 如果是采用Activity的方式来实现闹钟提示的话,PendingIntent对象的获取就应该采用PendingIntent.getActivity(Context c,int i,Intent intent,int j)方法。
  • 如果这三种方法错用了的话,虽然不会报错,但是看不到闹钟提示效果。

广播配置

新建闹钟BroadCastReceiver:

public class AlarmReceiver extends BroadcastReceiver {
    private NotificationManager m_notificationMgr = null;
    private static final int NOTIFICATION_FLAG = 3;
    @Override
    public void onReceive(Context context, Intent intent) {
        m_notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVIC
        if (intent.getAction().equals(GlobalValues.TIMER_ACTION_REPEATING)) {
            Log.e("alarm_receiver", "周期闹钟");
        } else if (intent.getAction().equals(GlobalValues.TIMER_ACTION)) {
            Log.e("alarm_receiver", "定时闹钟");
                        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);
            Intent intent1 = new Intent(context, WriteDiaryActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);
            Notification notify = new Notification.Builder(context)
                    .setSmallIcon(R.drawable.logo) // 设置状态栏中的小图片,尺寸一般建议在24×24
                    .setLargeIcon(bitmap) // 这里也可以设置大图标
                    .setTicker("亲情日历") // 设置显示的提示文字
                    .setContentTitle("亲情日历") // 设置显示的标题
                    .setContentText("您有日记提醒哦") // 消息的详细内容
                    .setContentIntent(pendingIntent) // 关联PendingIntent
                    .setNumber(1) // 在TextView的右方显示的数字,可以在外部定义一个变量,点击累加setNumber(count),这时显示的和
                    .getNotification(); // 需要注意build()是在API level16及之后增加的,在API11中可以使用getNotificatin()来
            notify.flags |= Notification.FLAG_AUTO_CANCEL;
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIF
            manager.notify(NOTIFICATION_FLAG, notify);
            bitmap.recycle(); //回收bitmap
        }
    }
}

注册BroadCastReceiver:

最后别忘了在清单里注册广播。

<!--闹钟接收广播-->
<receiver android:name=".util.service.AlarmReceiver">
    <intent-filter>
        <action android:name="com.e_eduspace.TIMER_ACTION_REPEATING" />
        <action android:name="com.e_eduspace.TIMER_ACTION" />
    </intent-filter>
</receiver>

附件

常量:

public class GlobalValues {
    // 周期性的闹钟
    public final static String TIMER_ACTION_REPEATING = "com.e_eduspace.TIMER_ACTION_REPEATING";
    // 定时闹钟
    public final static String TIMER_ACTION = "com.e_eduspace.TIMER_ACTION";
}

工具类

package com.e_eduspace.familycalendar.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.prolificinteractive.materialcalendarview.CalendarDay;

/**
 * 闹钟定时工具类
 *
 * @author xulei
 * @time 2016/12/13 10:03
 */

public class AlarmTimer {

    /**
     * 设置周期性闹钟
     *
     * @param context
     * @param firstTime
     * @param cycTime
     * @param action
     * @param AlarmManagerType 闹钟的类型,常用的有5个值:AlarmManager.ELAPSED_REALTIME、
     *                         AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、
     *                         AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP
     */
    public static void setRepeatingAlarmTimer(Context context, long firstTime,
                                              long cycTime, String action, int AlarmManagerType) {
        Intent myIntent = new Intent();
        myIntent.setAction(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManagerType, firstTime, cycTime, sender);
        //param1:闹钟类型,param1:闹钟首次执行时间,param1:闹钟两次执行的间隔时间,param1:闹钟响应动作。
    }

    /**
     * 设置定时闹钟
     *
     * @param context
     * @param cycTime
     * @param action
     * @param AlarmManagerType 闹钟的类型,常用的有5个值:AlarmManager.ELAPSED_REALTIME、
     *                         AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、
     *                         AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP
     */
    public static void setAlarmTimer(Context context, long cycTime,
                                     String action, int AlarmManagerType, CalendarDay date) {
        Intent myIntent = new Intent();
        //传递定时日期
        myIntent.putExtra("date", date);
        myIntent.setAction(action);
        //给每个闹钟设置不同ID防止覆盖
        int alarmId = SharedPreUtils.getInteger(context, "alarm_id", 0);
        SharedPreUtils.setInteger(context, "alarm_id", ++alarmId);
        PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManagerType, cycTime, sender);
    }

    /**
     * 取消闹钟
     *
     * @param context
     * @param action
     */
    public static void cancelAlarmTimer(Context context, String action) {
        Intent myIntent = new Intent();
        myIntent.setAction(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(sender);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容