Java Android:如何使用AlarmManager
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1082437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: How to use AlarmManager
提问by Tom
I need to trigger a block of code after 20 minutes from the AlarmManager
being set.
我需要AlarmManager
在设置后 20 分钟后触发一个代码块。
Can someone show me sample code on how to use an AlarmManager
in ?Android?
有人可以向我展示如何AlarmManager
在 ?Android 中使用的示例代码吗?
I have been playing around with some code for a few days and it just won't work.
我已经玩了几天的代码,但它不起作用。
采纳答案by CommonsWare
"Some sample code" is not that easy when it comes to AlarmManager
.
“一些示例代码”对于AlarmManager
.
Here is a snippet showing the setup of 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);
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()
.
在这个例子中,我使用setRepeating()
. 如果您想要一次性警报,您只需使用set()
. 确保将闹钟开始的时间与您在初始参数中使用的时基相同set()
。在我上面的例子中,我使用的是AlarmManager.ELAPSED_REALTIME_WAKEUP
,所以我的时基是SystemClock.elapsedRealtime()
.
Here is a larger sample projectshowing this technique.
这是一个更大的示例项目,展示了这种技术。
回答by Default
There are some good examples in the android sample code
android示例代码中有一些很好的例子
.\android-sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app
.\android-sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app
The ones to check out are:
要检查的有:
- AlarmController.java
- OneShotAlarm.java
- 报警控制器.java
- OneShotAlarm.java
First of, you need a receiver, something that can listen to your alarm when it is triggered. Add the following to your AndroidManifest.xml file
首先,您需要一个接收器,它可以在触发时监听您的警报。将以下内容添加到您的 AndroidManifest.xml 文件中
<receiver android:name=".MyAlarmReceiver" />
Then, create the following class
然后,创建以下类
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
Then, to trigger an alarm, use the following (for instance in your main activity):
然后,要触发警报,请使用以下内容(例如在您的主要活动中):
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
.
.
Or, better yet, make a class that handles it all and use it like this
或者,更好的是,创建一个处理所有内容的类并像这样使用它
Bundle bundle = new Bundle();
// add extras here..
MyAlarm alarm = new MyAlarm(this, bundle, 30);
this way, you have it all in one place (don't forget to edit the AndroidManifest.xml
)
这样,您就可以将所有内容集中在一处(不要忘记编辑AndroidManifest.xml
)
public class MyAlarm extends BroadcastReceiver {
private final String REMINDER_BUNDLE = "MyReminderBundle";
// this constructor is called by the alarm manager.
public MyAlarm(){ }
// you can use this constructor to create the alarm.
// Just pass in the main activity as the context,
// any extras you'd like to get later when triggered
// and the timeout
public MyAlarm(Context context, Bundle extras, int timeoutInSeconds){
AlarmManager alarmMgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarm.class);
intent.putExtra(REMINDER_BUNDLE, extras);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeoutInSeconds);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
// here you can get the extras you passed in when creating the alarm
//intent.getBundleExtra(REMINDER_BUNDLE));
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
回答by Arnold
Some sample code when you want to call a service from the Alarmmanager:
当您想从 Alarmmanager 调用服务时的一些示例代码:
PendingIntent pi;
AlarmManager mgr;
mgr = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(DataCollectionActivity.this, HUJIDataCollectionService.class);
pi = PendingIntent.getService(DataCollectionActivity.this, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() , 1000, pi);
You dont have to ask userpermissions.
您不必询问用户权限。
回答by SohailAziz
What you need to do is first create the intent you need to schedule. Then obtain the pendingIntent of that intent. You can schedule activities, services and broadcasts. To schedule an activity e.g MyActivity:
您需要做的是首先创建您需要安排的意图。然后获取该意图的pendingIntent。您可以安排活动、服务和广播。要安排活动,例如 MyActivity:
Intent i = new Intent(getApplicationContext(), MyActivity.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),3333,i,
PendingIntent.FLAG_CANCEL_CURRENT);
Give this pendingIntent to alarmManager:
将此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);
Now MyActivity will be launched after 5 seconds of the application launch, no matter you stop your application or device went in sleep state(due to RTC_WAKEUP option). You can read complete example code Scheduling activities, services and broadcasts #Android
现在 MyActivity 将在应用程序启动 5 秒后启动,无论您停止应用程序还是设备进入睡眠状态(由于 RTC_WAKEUP 选项)。您可以阅读完整的示例代码调度活动、服务和广播#Android
回答by kurt
I wanted to comment but <50 rep, so here goes. Friendly reminder that if you're running on 5.1 or above and you use an interval of less than a minute, this happens:
我想发表评论但 <50 代表,所以在这里。友情提示,如果您在 5.1 或更高版本上运行并且您使用的间隔少于一分钟,则会发生这种情况:
Suspiciously short interval 5000 millis; expanding to 60 seconds
See here.
见这里。
回答by Faxriddin Abdullayev
An AlarmManager is used to trigger some code at a specific time.
AlarmManager 用于在特定时间触发某些代码。
To start an Alarm Manager you need to first get the instance from the System. Then pass the PendingIntent which would get executed at a future time that you specify
要启动警报管理器,您需要首先从系统获取实例。然后传递将在您指定的未来时间执行的 PendingIntent
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
int interval = 8000; //repeat interval
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
You need to be careful while using the Alarm Manager. Normally, an alarm manager cannot repeat before a minute. Also in low power mode, the duration can increase to up to 15 minutes.
使用警报管理器时需要小心。通常,警报管理器不能在一分钟内重复。同样在低功耗模式下,持续时间可以增加到 15 分钟。