Android:如何使用警报管理器 [英] Android: How to use AlarmManager

查看:37
本文介绍了Android:如何使用警报管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 AlarmManager 设置 20 分钟后触发代码块.

I need to trigger a block of code after 20 minutes from the AlarmManager being set.

有人可以向我展示如何在 ِAndroid 中使用 AlarmManager 的示例代码吗?

Can someone show me sample code on how to use an AlarmManager in ِAndroid?

我已经玩了几天的代码,但它不起作用.

I have been playing around with some code for a few days and it just won't work.

推荐答案

对于 AlarmManager 来说,一些示例代码"并不是那么容易.

"Some sample code" is not that easy when it comes to AlarmManager.

这是一个显示AlarmManager设置的片段:

Here is a snippet showing the setup of AlarmManager:

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

在这个例子中,我使用了 setRepeating().如果您想要一次性警报,您只需使用 set().确保在与 set() 的初始参数中使用的相同时基中指定闹钟开始的时间.在我上面的例子中,我使用了 AlarmManager.ELAPSED_REALTIME_WAKEUP,所以我的时间基准是 SystemClock.elapsedRealtime().

In this example, I am using setRepeating(). If you want a one-shot alarm, you would just use set(). Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to set(). In my example above, I am using AlarmManager.ELAPSED_REALTIME_WAKEUP, so my time base is SystemClock.elapsedRealtime().

这里有一个更大的示例项目,展示了这种技术.

这篇关于Android:如何使用警报管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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