更新时间:2022-05-25 22:38:08
一些示例代码并非如此简单code> AlarmManager 。
"Some sample code" is not that easy when it comes to AlarmManager
.
这是一个显示 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()
.
这是一个更大的样本项目展示了这种技术。