Home » Android » Android Core » Scheduling Repeated Tasks in Android

About Bozhidar Bozhanov

Bozhidar Bozhanov
Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE, as well as Android, Scala and any framework you throw at him. creator of Computoser - an algorithmic music composer. Worked on telecom projects, e-government and large-scale online recruitment and navigation platforms.

Scheduling Repeated Tasks in Android

A somewhat common usecase for android applications is to have them launched when the phone is started, and execute some piece of code periodically.

Sounds straightforward, but there are some pitfalls, so here are a couple of steps to take in order to achieve that. Start with the trivial stuff:

In your manifest you need the following in order to be able to receive the boot event:
 
 
 
 

<uses-permission 
    android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Then, again in the manifest, you need two receivers:

<receiver android:name=".StartupLauncher">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</receiver>
<receiver android:name=".Notifier">
  <intent-filter>
    <action android:name="com.yourpackage.HOURLY_CHECK" />
  </intent-filter>
</receiver>

What are all these? You will see what HOURLY_CHECK is in a minute. The entries in the .StartupLauncher I gathered from multiple StackOverflow answers, claiming to work on multiple devices. What you are normally required to consume is just BOOT_COMPLETED, but put the rest just in case. Note the enabled attribute of the receiver – they are normally not needed, but make sure the recieve is not disabled by the parent application. Honestly, I wouldn’t advise for putting useless stuff “just in case”, but given the quirks of android devices, I’d keep them.

Now implement the Service that will receive the BOOT_COMPLETED event:

public class StartupLauncher extends BroadcastReceiver {
  @Override
  public void onReceive(final Context ctx, Intent intent) {
    AlarmManager alarmManager = (AlarmManager) ctx.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent("com.yourpackage.HOURLY_CHECK");
    PendingIntent notificationIntent = PendingIntent.getBroadcast(ctx.getApplicationContext(), 1, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 0, TimeUnit.MILLISECONDS.convert(60, TimeUnit.MINUTES), notificationIntent);
  }
}

Why not do it with a ScheduledExecutorService? Because once you schedule a Runnable, your BroadcastReceiver dies, and the executor dies with it, so the runnable is never invoked.

Now you have a scheduled Alarm, where you perform your actual logic:

public class Notifier extends BroadcastReceiver {
  @Override
  public void onReceive(Context ctx, Intent intent) {
    // ...
  }
}

You can of course have a single BroadcastReceiver and distinguish based on the intent, but I think that’s cleaner.

Overall, it’s a process that may be tricky – as it usually happens with Android, unfortunately.

Reference: Scheduling Repeated Tasks in Android from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Leave a Reply

Your email address will not be published. Required fields are marked *

*


× four = 8

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close