Android:如何使用AlarmManager

Android:如何使用AlarmManager

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

有人可以给我看一下如何AlarmManager在Android中使用的示例代码吗?

我已经玩了几天的代码,它只是不起作用。


小怪兽爱吃肉
浏览 518回答 3
3回答

跃然一笑

“一些示例代码”并非如此简单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()。这是一个展示这种技术的大型示例项目。

aluckdog

您需要做的是首先创建您需要安排的意图。然后获取该intent的pendingIntent。您可以安排活动,服务和广播。安排活动,例如MyActivity:  Intent i = new Intent(getApplicationContext(), MyActivity.class);   PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),3333,i,   PendingIntent.FLAG_CANCEL_CURRENT);将此pendingIntent提供给alarmManager:  //getting current time and add 5 seconds in it   Calendar cal = Calendar.getInstance();   cal.add(Calendar.SECOND, 5);   //registering our pending intent with alarmmanager   AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);   am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), pi);现在MyActivity将在应用程序启动5秒后启动,无论您停止应用程序还是设备进入睡眠状态(由于RTC_WAKEUP选项)。您可以阅读完整的示例代码调度活动,服务和广播#Android
打开App,查看更多内容
随时随地看视频慕课网APP