AlarmManager 设置多个提醒只有最后一个有效

先来说一下AlarmManager的使用方法


 
        Intent intent1 = new Intent("ELITOR_CLOCK_STARTUP");
        intent1.putExtra("msg", "开机时间到了");
        PendingIntent  pi = PendingIntent.getService(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager  am = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 14);
        c.set(Calendar.MINUTE, 20);
        c.set(Calendar.SECOND, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
        } else {
            am.set(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
        }


这是我一贯的写法,但如果设置多个提醒事件时,总是最后一个有效,在网上找了好久终于得到了解决,用这篇博客来提醒一下自己

问题出在这一行

pi = PendingIntent.getService(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);


解决办法

PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags);

第二个参数requestCode一定要是唯一的,比如不同的ID之类的,(如果系统需要多个定时器的话)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值