Scheduling code execution on Android using AlarmManager
One of the advantages android gives developers over iOS is the ability to schedule code execution. This means your app can do something in the background at a specific time. In this example Im going to create a sample app that puts your phone on silent at midnight, and unsilences it at 6AM. This can be very useful for developers who need their app to do something more complex than popping up a notification at a specific time. Lets get into it!
The first thing you will need to do in your app is create two classes that extend the BroadcastReceiver class, and give them some code you want to schedule in the onReceive method:
Next we want to make an entry in our manifest so that we can point to these Broadcast Receivers in our scheduling code. Add the nodes for these receivers inside of the Application tag in the manifest file:
Next we’re going to write the code that sets the schedule. Here you’ll notice when we touch the “Schedule” button it schedules two repeating events to run at midnight and at 6 AM:
Thats a lot so let me explain whats going on here. We are creating the intent to run the silence code. However we are making it a pending intent to run at a future date. Next we get an instance of “Alarm Manager” which will take a calendar object and a Pending Intent and run the code accordingly. You may also notice I’ve set the interval to “AlarmManager.INTERVAL_DAY” which repeats this alarm daily, however you can also set alarms that repeat every 15 minutes, every half hour, every hour, and every half day. You can also set this property as NULL to have it fire once (no repeat).
And finally we write the code for the second button (unschedule) which removes the schedule :