Notes: 26. Schedule Work With AlarmManager
The student materials have been reviewed and are updated as of SEPTEMBER 2022. Keep in mind that we now need to add an extra flag to our pending intent to make it work with the latest versions of Android. You also need an extra permission to create exact alarms.
After learning about the AsyncTask and JobScheduler, it’s time for the AlarmManager!
AlarmManager is super useful when you have to run a piece of work at a specific time. It’s one of the oldest APIs in Android, and you can achieve a lot with it.
It’s important to understand that you can use the AlarmManager in so many useful ways, where each way is specific to the project using it This would be too much to cover in one course.
For this reason, you’ll cover only a small portion of the API, that will give you the gist of things! Let’s see how to use the very basic way of scheduling work at an exact time, using AlarmManager!
Open the MainActivity.kt, and start off with this piece of code:
val alarmManager = getSystemService(AlarmManager::class.java) ?: return
val currentTime = System.currentTimeMillis()
Just like with all the system services Android offers, you first have to retrieve the AlarmManager. You also store the currentTime, because you’ll use this to schedule an alarm after a certain amount of time has passed. Next, create a pending intent for the manager:
val alarmManager = getSystemService(AlarmManager::class.java) ?: return
val currentTime = System.currentTimeMillis()
val pendingIntent = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
},
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE //Update Note: Adds mutability flag needed when targeting Android 31+
)
The AlarmManager works by scheduling a pending intent, which can then start a new component, like a service, refresh an activity, force-open the app by waking up the device, and similar.
In this case, you’ll start the MainActivity.kt with the FLAG_ACTIVITY_SINGLE_TOP, which means that the onNewIntent() function will be called in this Activity. You now have to schedule an alarm, like so:
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
currentTime + TimeUnit.MILLISECONDS.toSeconds(10_000),
pendingIntent
)
Using setExact() gives you the ability to set an alarm for the exact moment you want. In this case, you’re saying you want the alarm to wake up the device if it’s asleep.
You then provide the time at which the alarm should go off, which is roughly 10 seconds after the onCreate() function finishes. And finally, you give the alarmManager a pending intent to launch when the alarm happens. Because the intent will trigger the onNewIntent() function, override it:
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
}
Every time an activity gets launched again, with the SINGLE_TOP flag, it will update the current activity, with a new intent, and this function. Now add the code to open a network connection to the image:
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Thread(Runnable {
val imageUrl = URL("https://wallpaperplay.com/walls/full/1/c/7/38027.jpg")
val connection = imageUrl.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
}).start()
}
Like before, you’re connecting to the image URL, in order to download and display it. Then decode the stream of bytes into a Bitmap, and display it:
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Thread(Runnable {
val imageUrl = URL("https://wallpaperplay.com/walls/full/1/c/7/38027.jpg")
val connection = imageUrl.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val inputStream = connection.inputStream
val bitmap = BitmapFactory.decodeStream(inputStream)
runOnUiThread { image.setImageBitmap(bitmap) }
}).start()
}
Instead of downloading the image to a file, you’ll just display it here directly, for the sake of simplicity. What will happen here with the code being finished is next: you’ll schedule an alarm signal to trigger after ten seconds, which will update the current activity, with a new intent.
After you receive the newIntent, you’ll know that you need to start the download image process, which you do, in a new thread. After downloading the image to a Bitmap object, you display it, using an ImageView.
Very simple and straightforward! It’s a good way to see how the AlarmManager can schedule some work any time you need! Now run the project, and you’ll see the image appear after a while, one last time! :]