Android 设置多个闹钟 [英] Android Set Multiple Alarms

查看:63
本文介绍了Android 设置多个闹钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个需要多次报警(或提醒)的 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.

推荐答案

如果你想设置多个闹钟(重复或单个),那么你只需要用不同的创建他们的PendingIntent>请求代码.如果 requestCode 相同,则新闹钟会覆盖旧闹钟.

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.

这是创建多个单个警报并将它们保存在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's 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);
}

另外,看到这个问题:如何在 android 中一次设置多个闹钟?.

Also, see this question: How to set more than one alarms at a time in android?.

这篇关于Android 设置多个闹钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆