Chapters

Hide chapters

Android Debugging by Tutorials

First Edition · Android 12 · Kotlin 1.6 · Android Studio Chipmunk (2021.2.1)

Section I: Debugging Basics

Section 1: 8 chapters
Show chapters Hide chapters

8. Debugging WorkManager Jobs With Background Task Inspector
Written by Zahidur Rahman Faisal

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous chapter, you found out how to use the Database Inspector to investigate your database and the Live Updates feature to observe data changes. You learned how to use a query for previewing results while debugging the app and you got familiar with exporting your database to make sharing easier.

All this sounds really great, but you’re probably wondering where to find the data for populating your local database and how to download it. That could become a demanding task if the data is big and you need to sync it often. You need to think about user experience as well. Therefore, the solution is to run complex tasks in the background.

Performing long-running operations and processing data in the background is very common for mobile applications. Whether syncing your everyday tasks in the calendar or backing up your contacts and images to the cloud, they’re all background tasks, a basic and necessary part of your smartphone usage habit.

Here are the conditions one task needs to meet to become a background task:

  • None of the ongoing activities are currently visible to the user.
  • The task isn’t running any foreground services that the user explicitly started.

Common Types of Background Tasks

A background task includes additional processes like scheduling, monitoring, logging and user notification separately from the actual work it’s supposed to do. Considering the type of work it does, a background task can be any of the three types below:

  1. Immediate: Expedited tasks that must begin immediately and complete quickly, e.g. fetching data from the server.
  2. Long-Running: Tasks that run for a more extended period, usually more than 10 minutes, e.g. downloading big files.
  3. Deferrable: Scheduled tasks that start at a later point in time or run periodically, e.g. periodic sync with the server.

PodPlay relies on Android WorkManager to handle all types of background tasks. The app is smart enough to regularly check your subscribed channels and update the episode list if new episodes are published. This job runs in the background without you even realizing it’s happening!

This is great, but it can take a toll on your mobile data and CPU usage if the background operation is frequently running. In this chapter, you’ll inspect background tasks and schedule them to use optimal resources. You’ll learn how to:

  • List currently running or scheduled background tasks.
  • Find details of a background task.
  • Check the execution flow of background tasks.

Starting the Background Task Inspector

The scheduling of background tasks happens when you launch PodPlay. You can then see what’s happening by starting the Background Task Inspector.

Viewing and Inspecting Workers

PodPlay contains three different workers that check for new episodes in your subscribed channels:

The Work Table

Background Task Inspector displays a table listing all the tasks which WorkManager assigns.

Extracting Work Details

The table does a lot more than just show you a list of works; it allows you to filter each individual work by its tag and extract task details.

Finding a Work by Tag

When your WorkManager is executing a whole lot of work, the easiest way to find one of them from the table is to use the Tag Filter.

Anatomy of a Worker

Now that you’ve filtered GetNewEpisodesWorker from the table, click the row to reveal details about the work. The Task Details panel will open next to the row.

Navigating Through Works

The WorkContinuation section is interactive; You can easily navigate to any worker in the work chain simply by clicking on the worker’s UUID.

The Flow Diagram

The table can generate a nice graph of workers for better visualization. Click any of the highlighted areas below to bring out the Graph View:

Practical Example: A Simplified Work-Chain

In a real-world app, you might need to combine all the tasks of loading podcasts, fetching episodes, and saving updates in a single worker. The worker should run periodically in the background and only notify the user if new episodes have been added.

override suspend fun doWork(): Result = coroutineScope {
  val job = async {
    // 1
    val db = PodPlayDatabase.getInstance(applicationContext, this)
    val repo = PodcastRepo(RssFeedService.instance, db.podcastDao())
    // 2
    val podcastUpdates = repo.updatePodcastEpisodes()
    // 3
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      createNotificationChannel()
    }
    for (podcastUpdate in podcastUpdates) {
      displayNotification(podcastUpdate)
    }
  }
  job.await()
  Result.success()
}
private fun scheduleJobs() {
  // 1
  val constraints: Constraints = Constraints.Builder().apply {
    setRequiredNetworkType(NetworkType.CONNECTED)
    setRequiresBatteryNotLow(true)
  }.build()
  // 2
  val request = PeriodicWorkRequestBuilder<EpisodeUpdateWorker>(
      repeatInterval = 1,
      repeatIntervalTimeUnit = TimeUnit.HOURS)
      .setConstraints(constraints)
      .build()
  // 3
  WorkManager.getInstance(this).enqueueUniquePeriodicWork(TAG_EPISODE_UPDATE_JOB,
      ExistingPeriodicWorkPolicy.REPLACE, request)
}

Canceling a Worker

Sometimes you may want to cancel a worker which is scheduled to run in future. It’s easy to stop a currently running or enqueued worker using Background Task Inspector. Select EpisodeUpdateWorker and click the highlighted icon from the toolbar:

Key Points

  • You can easily inspect WorkManager workers using Background Task Inspector.
  • Background Task Inspector contains a table with all workers.
  • You can find a specific worker using tags.
  • The Task Details panel reveals the current state, execution flow, work continuation and results of background work.
  • You can see a detailed work chain graph using Graph View.

Where to Go From Here?

You’ve now mastered inspecting background tasks in Android! To learn how to utilize Background Task Inspector more, check out View and inspect Jobs, Alarms, and Wakelocks.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now