Android PendingIntent.getBroadcast方法中 intent数据不更新问题

项目详情
问题:设置多个不同的提醒闹钟,但是提醒内容始终是一样,最后测试发现,intent值虽然赋进去了,但是不知道为啥 PendingIntent.getBroadcast(ScheduleView.this, 0, intent, 0);里的intent值输出来却是以前的。。。猜想getBroadcast()函数的问题。

  1. Service 中设置定时广播的代码
private AlarmManager alarmManager;
        private Calendar calendar;
        private Intent intent;
        private PendingIntent pendingIntent;
        private int alarmCount = 0;

        public void setAlarm(String todo, int code) {
            alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
            calendar = Calendar.getInstance();
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
            intent = new Intent("android.intent.action.alarm");
            intent.putExtra("todo", todo);
            intent.putExtra("remindTypeCode", code);
            Log.d(TAG, "setAlarm: " + intent.getStringExtra("todo") + intent.getIntExtra("remindTypeCode", 0));
            calendar.set(year, (month-1), day, hour, minute, 0);
            pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

原因:查看了很多资料,是因为PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags) 第二个和第四个参数引起的。

解决

int alarmCount=0;
PendingIntent pi = PendingIntent.getBroadcast(ScheduleView.this,alarmCount++, intent,PendingIntent.FLAG_UPDATE_CURRENT); // 创建PendingIntent

将第二个参数设置成自增变量,保证每次不同,将第四个参数设置成及时更新。只有这两个参数都设置才有用。数据不变,更新了也没用,数据变了,不更新也没用。

你可能感兴趣的:(Android)