Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to use AlarmManager

I need to trigger a block of code after 20 minutes from the AlarmManager being set.

Can someone show me sample code on how to use an AlarmManager in ِAndroid?

I have been playing around with some code for a few days and it just won't work.

like image 507
Tom Avatar asked Jul 04 '09 15:07

Tom


People also ask

How does alarm Manager work?

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock.

How do you set a repeat alarm on android?

At the top of the main panel you should see an option to Add alarm. Tap this and you'll be presented with a time in the top half of the screen, with various settings in the lower half. Scroll the hours up or down until you reach the one you want, then repeat the process with the minutes.

Is AlarmManager deprecated?

IntentService + WakefulBroadcastReceiver + AlarmManager are deprecated with API 26 (Android 8.0 Oreo).

How does an application get access to the AlarmManager?

How does an application get access to the AlarmManager? Use the AlarmManager() constructor to create an instance of the AlarmManager. Use the AlarmManager. newInstance() method to retrieve the singleton instance of the AlarmManager.


2 Answers

"Some sample code" is not that easy when it comes to AlarmManager.

Here is a snippet showing the setup of 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().

Here is a larger sample project showing this technique.

like image 110
CommonsWare Avatar answered Sep 23 '22 00:09

CommonsWare


There are some good examples in the android sample code

.\android-sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app

The ones to check out are:

  • AlarmController.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

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

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();      } } 
like image 29
default Avatar answered Sep 23 '22 00:09

default