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 :
Thats awsome sir… actually this app is verry usefull.. thanks for explaining it so well…
Thanks dude.This helps me alot to solve my problem.
nice code..it help me to resolve the issue in my app.i am trying to solve since 3 days..thank you so much..for this awsome code..
very helpful and nice explanation, really helped
Sir i want to do it in silent mode after receiving signal of particular frequency. how to do it?
Thanks sir for useful tutorial, but I have a little confusion that what will be written in the manifest file? If anyone have complete code of this application kindly mail it to me at [redacted] …. Millions of thanks in Advance.
Thanks sir, It is very helpful and nicely explained.