Alarm Manager Example
I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples. Can anyone help me with a basic alarm manager program?
10 Answers 10
This is working code. It wakes CPU every 10 minutes until the phone turns off.
package yourPackage; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.widget.Toast; public class Alarm extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""); wl.acquire(); // Put here YOUR code. Toast.makeText(context, "Alarm . ", Toast.LENGTH_LONG).show(); // For example wl.release(); >public void setAlarm(Context context) < AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, Alarm.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute >public void cancelAlarm(Context context) < Intent intent = new Intent(context, Alarm.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); >>
Set Alarm from Service:
package yourPackage; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; public class YourService extends Service < Alarm alarm = new Alarm(); public void onCreate() < super.onCreate(); >@Override public int onStartCommand(Intent intent, int flags, int startId) < alarm.setAlarm(this); return START_STICKY; >@Override public void onStart(Intent intent, int startId) < alarm.setAlarm(this); >@Override public IBinder onBind(Intent intent) < return null; >>
If you want to set alarm repeating at phone boot time:
Add permission and the service to Manifest.xml:
package yourPackage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AutoStart extends BroadcastReceiver < Alarm alarm = new Alarm(); @Override public void onReceive(Context context, Intent intent) < if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) < alarm.setAlarm(context); >> >
How this setAlarm method will be called. If i would like to call it from service class ? Is it automatically called?
This is very helpful, but a few things: 1. It might be better to use am.setInexactRepeating(. ) so the phone isn’t needlessly woken up because of the service. Other programmers should take note of this fact. 2. Instead of creating a new Alarm in AutoStart upon receiving the RECEIVE_BOOT_COMPLETED intent, it might make more sense to start YourService from AutoStart , as shown here: stackoverflow.com/a/5439320/198348
I think acquiring the lock on the onReceive method is not mandatory since android will do it for you. See here: developer.android.com/reference/android/app/AlarmManager.html
WakeLock not needed in a BroadcastReceiver. Android uses its own one util broadcastReceiver finishes.
Great answer, but is better extend from WakefulBroadcastReceiver instead of BroadcastReceiver, WakefulBroadcastReceiver manages the wake lock itself. See link for more info.
I tried the solution from XXX and while it did initially work, at some point it stopped working. The onReceive never got called again. I spent hours trying to figure out what it could be. What I came to realize is that the Intent for whatever mysterious reason was no longer being called. To get around this, I discovered that you really do need to specify an action for the receiver in the manifest. Example:
Note that the name is «.Alarm» with the period. In XXX’s setAlarm method, create the Intent as follows:
Intent i = new Intent("mypackage.START_ALARM");
The START_ALARM message can be whatever you want it to be. I just gave it that name for demonstration purposes.
I have not seen receivers defined in the manifest without an intent filter that specifies the action. Creating them the way XXX has specified it seems kind of bogus. By specifying the action name, Android will be forced to create an instance of the BroadcastReceiver using the class that corresponds to the action. If you rely upon context, be aware that Android has several different objects that are ALL called context and may not result in getting your BroadcastReceiver created. Forcing Android to create an instance of your class using only the action message is far better than relying upon some iffy context that may never work.
@AndroidDev According to PendingIntent.getBroadcast documentation, For security reasons, the Intent you supply here should almost always be an explicit intent, that is specify an explicit component to be delivered to through Intent.setClass .
No matter what documentation says, this should be the accepted answer because it actually works contrary to the accepted answer.
Here’s a fairly self-contained example. It turns a button red after 5sec.
public void SetAlarm() < final Button button = buttons[2]; // replace with a button from your own UI BroadcastReceiver receiver = new BroadcastReceiver() < @Override public void onReceive( Context context, Intent _ ) < button.setBackgroundColor( Color.RED ); context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity >>; this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") ); PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 ); AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE )); // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime()) manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent ); >
Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.
I don’t know what kind of behavior you would get if your app isn’t in memory at all, so be careful with what kind of state you try to preserve.
This (with RTC_WAKEUP instead of ELAPSED_REALTIME_WAKEUP ) doesn’t appear to trigger the receiver in an app which has apparently been unloaded by the system for power saving, although it does work shortly after the Home screen has been brought to foreground.
package com.example.alarmexample; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity < Button b1; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startAlert(); >public void startAlert() < int timeInSec = 2; Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent); Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show(); >>
package com.example.alarmexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver < MediaPlayer mp; @Override public void onReceive(Context context, Intent intent) < mp=MediaPlayer.create(context, R.raw.alarm); mp.start(); Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show(); >>
Try alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), timeInSec * 1000, pendingIntent); instead of alarmManager.set() if you want to run a method periodically.
Please refer to the official guide for more information, developer.android.com/training/scheduling/alarms
• AlarmManager in combination with IntentService
I think the best pattern for using AlarmManager is its collaboration with an IntentService . The IntentService is triggered by the AlarmManager and it handles the required actions through the receiving intent. This structure has not performance impact like using BroadcastReceiver . I have developed a sample code for this idea in kotlin which is available here:
MyAlarmManager.kt
import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent object MyAlarmManager < private var pendingIntent: PendingIntent? = null fun setAlarm(context: Context, alarmTime: Long, message: String) < val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val intent = Intent(context, MyIntentService::class.java) intent.action = MyIntentService.ACTION_SEND_TEST_MESSAGE intent.putExtra(MyIntentService.EXTRA_MESSAGE, message) pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent) >fun cancelAlarm(context: Context) < pendingIntent?.let < val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(it) >> >
MyIntentService.kt
import android.app.IntentService import android.content.Intent class MyIntentService : IntentService("MyIntentService") < override fun onHandleIntent(intent: Intent?) < intent?.apply < when (intent.action) < ACTION_SEND_TEST_MESSAGE -> < val message = getStringExtra(EXTRA_MESSAGE) println(message) >> > > companion object < const val ACTION_SEND_TEST_MESSAGE = "ACTION_SEND_TEST_MESSAGE" const val EXTRA_MESSAGE = "EXTRA_MESSAGE" >>
manifest.xml
val calendar = Calendar.getInstance() calendar.add(Calendar.SECOND, 10) MyAlarmManager.setAlarm(applicationContext, calendar.timeInMillis, "Test Message!")
If you want to to cancel the scheduled alarm, try this:
MyAlarmManager.cancelAlarm(applicationContext)
Add To XML Layout (*init these view on create in main activity)
Add To Manifest (Inside application tag && outside activity)
Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)
public class AlarmBroadcastManager extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI); mediaPlayer.start(); >>
In Main Activity (Add these Functions):
@RequiresApi(api = Build.VERSION_CODES.M) public void start_alarm_event(View view) < Calendar calendar=Calendar.getInstance(); calendar.set( calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), timePicker.getHour(), timePicker.getMinute(), 0 ); setAlarm(calendar.getTimeInMillis()); >public void setAlarm(long timeInMillis)
This code will help you to make a repeating alarm. The repeating time can set by you.
public class MainActivity extends Activity < int hr = 0; int min = 0; int sec = 0; int result = 1; AlarmManager alarmManager; PendingIntent pendingIntent; BroadcastReceiver mReceiver; EditText ethr; EditText etmin; EditText etsec; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ethr = (EditText) findViewById(R.id.ethr); etmin = (EditText) findViewById(R.id.etmin); etsec = (EditText) findViewById(R.id.etsec); RegisterAlarmBroadcast(); >@Override public boolean onCreateOptionsMenu(Menu menu) < getMenuInflater().inflate(R.menu.main, menu); return true; >@Override protected void onDestroy() < unregisterReceiver(mReceiver); super.onDestroy(); >public void onClickSetAlarm(View v) < String shr = ethr.getText().toString(); String smin = etmin.getText().toString(); String ssec = etsec.getText().toString(); if(shr.equals("")) hr = 0; else < hr = Integer.parseInt(ethr.getText().toString()); hr=hr*60*60*1000; >if(smin.equals("")) min = 0; else < min = Integer.parseInt(etmin.getText().toString()); min = min*60*1000; >if(ssec.equals("")) sec = 0; else < sec = Integer.parseInt(etsec.getText().toString()); sec = sec * 1000; >result = hr+min+sec; alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent); > private void RegisterAlarmBroadcast() < mReceiver = new BroadcastReceiver() < // private static final String TAG = "Alarm Example Receiver"; @Override public void onReceive(Context context, Intent intent) < Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show(); >>; registerReceiver(mReceiver, new IntentFilter("sample")); pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0); alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE)); > private void UnregisterAlarmBroadcast() < alarmManager.cancel(pendingIntent); getBaseContext().unregisterReceiver(mReceiver); >>
If you need alarm only for a single time then replace
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);
alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );
I have made my own implementation to do this on the simplest way as possible.
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import junit.framework.Assert; /** * Created by Daniel on 28/08/2016. */ public abstract class AbstractSystemServiceTask < private final Context context; private final AlarmManager alarmManager; private final BroadcastReceiver broadcastReceiver; private final PendingIntent pendingIntent; public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) < Assert.assertNotNull("ApplicationContext can't be null", context); Assert.assertNotNull("ID can't be null", id); this.context = context; this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE); this.context.registerReceiver( this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener), new IntentFilter(id)); this.configAlarmManager( this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0), time, alarmType); >public void stop() < this.alarmManager.cancel(this.pendingIntent); this.context.unregisterReceiver(this.broadcastReceiver); >private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) < Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener); return new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < backgroundTaskListener.perform(context, intent); >>; > private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) < long ensurePositiveTime = Math.max(time, 0L); switch (alarmType) < case REPEAT: this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent); break; case ONE_TIME: default: this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent); >> public interface BackgroundTaskListener < void perform(Context context, Intent intent); >public enum AlarmType < REPEAT, ONE_TIME; >>
The only next step, implement it.
import android.content.Context; import android.content.Intent; import android.util.Log; import . AbstractSystemServiceTask; import java.util.concurrent.TimeUnit; /** * Created by Daniel on 28/08/2016. */ public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask < private final static String ; private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10); private final static AlarmType ALARM_TYPE = AlarmType.REPEAT; public UpdateInfoSystemServiceTask(Context context) < super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() < @Override public void perform(Context context, Intent intent) < Log.i("MyAppLog", "----->UpdateInfoSystemServiceTask"); //DO HERE WHATEVER YOU WANT. > >); Log.i("MyAppLog", "UpdateInfoSystemServiceTask started."); > >
I like to work with this implementation, but another possible good way, it’s don’t make the AbstractSystemServiceTask class abstract, and build it through a Builder.
UPDATED Improved to allow several BackgroundTaskListener on the same BroadCastReceiver .
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import junit.framework.Assert; import java.util.HashSet; import java.util.Set; /** * Created by Daniel on 28/08/2016. */ public abstract class AbstractSystemServiceTask < private final Context context; private final AlarmManager alarmManager; private final BroadcastReceiver broadcastReceiver; private final PendingIntent pendingIntent; private final SetbackgroundTaskListenerSet; public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) < Assert.assertNotNull("ApplicationContext can't be null", context); Assert.assertNotNull("ID can't be null", id); this.backgroundTaskListenerSet = new HashSet<>(); this.context = context; this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE); this.context.registerReceiver( this.broadcastReceiver = this.getBroadcastReceiver(), new IntentFilter(id)); this.configAlarmManager( this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0), time, alarmType); > public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) < Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener); this.backgroundTaskListenerSet.add(backgroundTaskListener); >public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) < Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener); this.backgroundTaskListenerSet.remove(backgroundTaskListener); >public void stop() < this.backgroundTaskListenerSet.clear(); this.alarmManager.cancel(this.pendingIntent); this.context.unregisterReceiver(this.broadcastReceiver); >private BroadcastReceiver getBroadcastReceiver() < return new BroadcastReceiver() < @Override public void onReceive(final Context context, final Intent intent) < for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) < backgroundTaskListener.perform(context, intent); >> >; > private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) < long ensurePositiveTime = Math.max(time, 0L); switch (alarmType) < case REPEAT: this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent); break; case ONE_TIME: default: this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent); >> public interface BackgroundTaskListener < void perform(Context context, Intent intent); >public enum AlarmType < REPEAT, ONE_TIME; >>