Android Background Processing

Sep 23 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk 2021.2.1

Part 4: Implement Legacy Background Processing

26. Schedule Work With AlarmManager

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 25. Use the JobScheduler Next episode: 27. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

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.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

After learning about the AsyncTask and JobScheduler, it’s time for the AlarmManager!

val alarmManager = getSystemService(AlarmManager::class.java) ?: return
val currentTime = System.currentTimeMillis()
    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+
    )
    alarmManager.setExact(
        AlarmManager.RTC_WAKEUP,
        currentTime + TimeUnit.MILLISECONDS.toSeconds(10_000),
        pendingIntent
    )
  override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
  }
  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()
  }
  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()
  }