Marko Jerkić

Learner's Deep Learning Blog

Background Task – How To Start An Activity At A Certain Time

Background tasks have many usages. Android provides you with a couple of ways of creating a background task.In this blog post, we’re going to focus on how to create an app that starts an activity at a certain time. This time can be a set time of the day (for example, 4:00 PM), or it can be some time relative to another. For example you could set this to happen one hour after the user has pressed a button. Some of you might be thinking, “Why couldn’t use a simple CountDown Timer, set it to 60000 ms and start the activity in the onFinish method?”. Well, you could use this method, but this works only of your user stays in that app until the CountDown Timer is finished. The standard Thread and Handler methods are restricted to the app’s and activity’s lifetime cycle. The method that we’re going to be covering in this post isn’t.

Alarm types

AlarmManager provides you with a couple of types of alarms. Those are:

  • ELAPSED_REALTIME—Fires the pending intent based on the amount of time since the device was booted, but doesn’t wake up the device. The elapsed time includes any time during which the device was asleep.
  • ELAPSED_REALTIME_WAKEUP—Wakes up the device and fires the pending intent after the specified length of time has elapsed since device boot.
  • RTC—Fires the pending intent at the specified time but does not wake up the device.
  • RTC_WAKEUP—Wakes up the device to fire the pending intent at the specified time.

Setup

You will need to add a few changes to the AndroidManifest.xml file in order for this example to work. Those are:

https://gist.github.com/markojerkic/41a207d4c9fdf171f514fd3fbc993b38

ELAPSED_REALTIME example

Create a standard project. In the MainActivity create an instance of the AlarmManager class an Intent and a PendingIntent.

https://gist.github.com/markojerkic/a9d52bf81ba844fb5bf81a0597982c53

We need another class to make this work. That is a class that extends the BroadcastReceiver class. In this class we’re going to respond to the pendingIntent.

https://gist.github.com/markojerkic/93fdd3cdec8e53f1de26d61091acb4b4

And now we’re going to edit the MainActivity class to check if the activity has been started from the class we wrote a minute ago.

https://gist.github.com/markojerkic/753ad1f15c0ecc20f5de2d4e1165d400

RTC example

RTC enables you to do something at a certain time of the day. For example, if you want to send a notification at exactly 9:00 PM, then you would use this feature of the AlarmManager class. A lot of the code is going to be the same as the previous example, and the only change is going to happen when you’re calling the set() method. It’s going to look something like this.

https://gist.github.com/markojerkic/0578a9c971675ae16cfbca994023d807

Learn more

Leave a Reply

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

Back to top