A Broadcast receiver in Android is capable of receiving different notifications from inside and outside the processes. This is a very simple code snippet for those who are searching for A Scheduled Broadcast receiver in android using setRepeating or setInexactRepeating timer calls. I could find a number of articles & questions with lots of information. But I could not get one simple snippet which I can wholly use for this purpose.
There are 2 simple steps of creating a repeating timer or alarm calls.
- Create a class which will set and handle your alarms. Please find the snippet to set alarm and receive broadcast messages. The detailed project with full source can be downloaded from the project downloads.
@Override public void onReceive(Context context, Intent intent) { Log.d(strLogTag, String.format("Alarm received Broadcast message - %s", intent.getAction())); //DO SOME WORK Like start a service for download/upload etc., } public void SetAlarm(Context context) { AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent("com.sample.timerproject.START_ALARM"); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); am.cancel(pi); //am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); Log.i(strLogTag, "Alarm Setting Done."); }
- In the above sample for SetAlarm function we can either use setRepeating or setInexactRepeating function. setInexactRepeating is supposedly more power-efficient and uses the system alarms to wake-up and go to sleep mode, but the alarms may not always happen at the exact intervals as we expect. So these alarms can be used for non-critical applications without draining the battery. But on the other hand setRepeating is very accurate but always keeps the phone on, which means it drains the battery of the phone.
- The next section of the code is in our AndroidManifest.xml as below.
<receiver android:name=".TimerAlarm" android:exported="true"> <intent-filter> <action android:name="com.sample.timerproject.START_ALARM" ></action> </intent-filter> </receiver>
- Now we can set this alarm using a button click. You can also do this via some other broadcasts like BOOT_COMPLETED or during some other events etc.,
TimerAlarm ta = new TimerAlarm(); ta.SetAlarm(getApplicationContext());
Attachments
The sample project can be downloaded here.