使用AlarmClock或Alarmmanager,从用户输入添加警报

时间:2016-01-02 12:57:16

标签: java android android-studio

是Android应用开发的新手

需要打开用户输入数据的警报..

我已阅读有关Alarmclock:可用于将闹钟设置为默认时钟应用程序且无法取消..

Alarmmanager:用于在指定时间触发事件,但它具有设置或取消警报的功能

想法:使用AlarmClock设置闹钟并使用Alarmmanager取消闹钟..是否可以这样做

我怎么能这样做?帮助我

2 个答案:

答案 0 :(得分:0)

要设置闹钟,您需要创建一个将为pendingIndent输入的intent。这个pendingIntent将进入报警管理器。

要取消闹钟,请创建pendingIntent,同样的requestCode / ID,然后调用alarmanager.cancel()

有关如何设置闹钟管理器的完整代码,请参阅示例。有很多,几乎每个例子都是工作例子

答案 1 :(得分:0)

要创建闹钟,您可以执行以下操作:

        //... some code here

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // if you don't want the alarm to go off even in Doze mode, use
            // setExact instead
            mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
                    alarmTimeMillis,
                    getPendingIntent(context);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mAlarmManager.setExact(AlarmManager.RTC_WAKEUP,
                    alarmTimeMillis,
                    getPendingIntent(context);
        } else {
            // Inexact time was only introduced in API 19+. Before that, all was exact time
            mAlarmManager.set(AlarmManager.RTC_WAKEUP,
                    alarmTimeMillis,
                    getPendingIntent(context);
        }

这里有些话。在API 19之前,所有警报都是准确的,这就是我们使用set方法的原因。在API 19及之后,引入了不准确的警报,这就是为什么我们需要使用setExact用于完全警报而set用于不准确< / em>警报。 在API 23中,引入了打盹模式。在该模式下,如果手机处于打盹模式,任何设置为setsetExact的闹钟都不会响起。要强制设备退出打盹并触发警报,请使用setExactAndAllowWhileIdle

方法getPendingIntent可能是这样的:

    private PendingIntent getPendingIntent(Context context) {
        int requestCode = 69;
        return PendingIntent.getBroadcast(context, requestCode,
                new Intent(mContext, AlarmReceiver.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
    }

当然,你可以照常将额外内容加入意图中。

要取消警报,您只需要使用相同的requestCode创建待处理的意图,并在警报管理器上调用取消,例如:

(AlarmManager) context.getSystemService(Context.ALARM_SERVICE)
                      .cancel(getPendingIntent(context));

请注意上面的调用远非完美,所以请不要按原样使用。