从设置AlarmManager到20分钟后,我需要触发一段代码。

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

我已经玩了几天的代码了,只是行不通。

最佳答案

当涉及到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()

Here is a larger sample project显示此技术。

08-18 02:42
查看更多