如何设置AlarmManager的唯一ID?

时间:2011-10-07 15:16:49

标签: android android-alarms

我正在使用此代码启动警报。

警报在用户可以启动的活动中设置。

//Setting alarm to fire off NEW_GAME intent every 24 hours.
            String alarm = Context.ALARM_SERVICE;
            Calendar calendar = Calendar.getInstance();

            calendar.set(Calendar.HOUR_OF_DAY, 8);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND, 0);

             Log.i("Test", "Current time: " + System.currentTimeMillis() );
                Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );

                int currentDate = calendar.get(Calendar.DATE);
                calendar.set(Calendar.DATE, currentDate+1);

                Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );


            AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
                Intent intent = new Intent("NEW_ITEM");
                PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);

                am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);

我被告知我需要提供一个uniqu id,以便警报不会在getBroadcast()所在的位置相互写入。

问题是当用户可以根据需要多次打开Activity时,我该怎么做?

此外,如果我每次提供一个唯一的ID,这意味着它可能因为唯一的ID而设置5个相同的ALARMS。

如何或以何种方式解决这个问题?

1 个答案:

答案 0 :(得分:4)

您可以随时使用目标时间的unix时间戳作为唯一ID。这样,准确时间的警报将相互覆盖,而所有其他警报将保持独立

[编辑:]以下是一些示例代码:

AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
            Intent intent = new Intent(String.valueOf(calendar.getTimeInMillis()));
            PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
            am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);