80

我需要在设置AlarmManager 20分钟后触发一段代码。Android:如何使用AlarmManager

有人可以告诉我关于如何在Android中使用AlarmManager的示例代码?

我一直在玩一些代码几天,它不会工作。

回答

100

当涉及到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显示此技术。

+2

再次问候。谢谢回复。如果我购买了您的书,是否可以解释如何详细实施警报管理器? – Tom 2009-07-04 20:09:30

+7

高级Android书籍(版本0.9)有约9页涉及AlarmManager,WakeLocks和其他示例。这可能会在版本1.0中稍微扩大,因为我在上面的答案中提到了我所提到的修复。如果您对本书或其示例代码有疑问,请跳至http://groups.google.com/group/cw-android,我很乐意回答。 – CommonsWare 2009-07-04 23:23:44

+17

任何Android开发者都应该订阅Mark的书籍:)至少一次 – Bostone 2010-02-12 16:09:25

58

有在机器人的示例代码

一些很好的例子。\ Android的SDK \样品\机器人-10 \ ApiDemos \ SRC \ COM \示例\机器人\的API \应用

检查出的是:

  • AlarmController.java
  • OneShotAlarm.java

首先,您需要一个接收器,它可以在触发时监听您的闹钟。以下添加到您的AndroidManifest.xml文件

<receiver android:name=".MyAlarmReceiver" /> 

然后,创建下面的类

public class MyAlarmReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show(); 
    } 
} 

然后触发报警,请使用以下(例如在您的主要活动):

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); 


或者,更好,使处理它所有的一个类,并使用它像这样

Bundle bundle = new Bundle(); 
// add extras here.. 
MyAlarm alarm = new MyAlarm(this, bundle, 30); 

这样,你就拥有了一切在一个地方(不要忘记编辑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(); 
    } 
} 
2

当你想打电话从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); 

你不必问用户权限。

7

你需要做的是首先创建你需要安排的意图。然后获取该意图的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选项)。 你可以阅读完整的示例代码Scheduling activities, services and broadcasts #Android

3

我想发表评论,但< 50代表处,所以这里去。友情提醒:如果你在5.1或以上时,如果您使用的更小的间隔不到一分钟,出现这种情况:

Suspiciously short interval 5000 millis; expanding to 60 seconds 

here