Android的设置多个闹钟多个、闹钟、Android

2023-09-12 23:39:23 作者:帅比小伙儿萌萌哒i

我想实现一个Android应用程序,需要报警(或警示)多次沿着时间。

I'm trying to implement an Android app that needs to alarm (or to alert) multiple times along the time.

我已经搜查,但我发现最近被设置报警的定数,我想这个例子没有工作。

I've already searched, but the nearest I found was a fixed-number of alarms set, and I guess the example didn't work.

我想知道是否有存在的一种方法,动态地设置多个闹钟,像报警的数组,然后触发报警者在其特定的时间戳。

What I want to know if there is exists an approach to dynamically set multiple alarms, like an Array of alarms and then to trigger those alarms in their specific timestamps.

我希望这个问题是清楚的:)

I hope that the question is clear :)

推荐答案

如果您要设置多个报警(重复或单),那么你只需要创建自己的 PendingIntent 有不同的请求$ C $(C S)。如果请求code 是一样的,那么新的报警将覆盖旧的。

If you want to set multiple alarms (repeating or single), then you just need to create their PendingIntents with different requestCode. If requestCode is the same, then the new alarm will overwrite the old one.

下面是code创建多个单独的报警,并保存在的ArrayList 。我把 PendingIntent 的数组中,因为你需要取消报警。

Here is the code to create multiple single alarms and keep them in ArrayList. I keep PendingIntent's in the array because that what you need to cancel your alarm.

// context variable contains your `Context`
AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();

for(i = 0; i < 10; ++i)
{
   Intent intent = new Intent(context, OnAlarmReceiver.class);
   // Loop counter `i` is used as a `requestCode`
   PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
   // Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
   mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
                SystemClock.elapsedRealtime() + 60000 * i, 
                pendingIntent); 

   intentArray.add(pendingIntent);
}

此外,见这个问题:How在Android的设置多个报警的时间?。