Android下结合Notification和AlarmManager实现定时提醒

时间:2024-05-19 21:12:19

Android下结合Notification和AlarmManager实现定时提醒

Notification和AlarmManager的分别使用

首先是一个notification的使用,程序里我实现了一个点击发送推送,打开通知设置,channel设置等点击事件。(channel是安卓O新增的更新)
然后是结合AlarmManager的使用,实现一个定时发送notification的例子。
具体原理是调用系统AlarmManager设置一个时间发送广播,程序在接收到广播时发送推送。
程序的界面如图,运行过程不做展示。具体代码在文末。
Android下结合Notification和AlarmManager实现定时提醒

再说几个遇到的坑

  1. 安卓O新增了一个Notification Channel,使用notification需指定发送的channel
    我的理解是为了对notification进行分类。例如打开微博的通知设置可以看到有微博热点,消息推送,其他等多个channel。因此可以手动进行设置选择想要接收的notification。
    Channel的创建如下:
NotificationChannel mNotificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
mNotificationChannel.setDescription(CHANNEL_DESCRIPTION);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService
(this.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mNotificationChannel);
CHANNEL_ID, CHANNEL_NAME, CHANNEL_DESCRIPTION是自己定义的字符串,对应channel的id, 名字与描述。NotificationManager.IMPORTANCE_DEFAULT是notification的重要程度,如是否弹框,有没有声音或者震动。对应O之前的setPriority。

在设置builder时再根据不同版本做出对应操作:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        } else
        {
            builder = new NotificationCompat.Builder(this);
            builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        }
  1. 安卓O之后对于广播的静态注册也有约束,发送广播时需指定一个ComponentName,否则无法发送成功。这个问题纠结了很久,在参考了参考这位朋友的博客才明白:https://blog.****.net/kongqwesd12/article/details/78998151。
    Recevier的实现例子很多,不做展示。Recevier的实现例子很多,不做展示。
  2. AlarmManager的函数使用,从安卓4.4开始set()就不支持准确激发了,当使用set()或者setRepeat()时,系统会把多个闹钟服务(不同时间)集中在同一时间激发,准确激发应使用setExact(),setWindow()和setInexactRepeating()。

项目地址: [1]: https://github.com/Zengcxuan/NotificationAndAlarm