Scheduling Work

To schedule a Worker to execute, you need a WorkRequest. The WorkRequest class itself is abstract, so you need to use one of its subclasses depending on the type of work you need to execute. If you have something that only needs to execute once, use a OneTimeWorkRequest. If your work is something that must execute periodically, use a PeriodicWorkRequest.

For now, you are going to use the OneTimeWorkRequest. This will let you verify that your PollWorker is functioning correctly and learn more about creating and controlling the requests. Later you will update your app to use a PeriodicWorkRequest.

Open PhotoGalleryFragment.kt, create a work request, and schedule it for execution.

Listing 27.3  Scheduling a WorkRequest (PhotoGalleryFragment.kt)

class PhotoGalleryFragment : Fragment() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        lifecycle.addObserver(thumbnailDownloader.fragmentLifecycleObserver)

        val workRequest = OneTimeWorkRequest
            .Builder(PollWorker::class.java)
            .build()
        WorkManager.getInstance()
            .enqueue(workRequest)
    }
    ...
}

The OneTimeWorkRequest uses a builder to construct an instance. You provide the Worker class to the builder that the work request will fire. Once your work request is ready, you need to schedule it with the WorkManager class. You call the getInstance() function to access the WorkManager, then call enqueue(…) with the work request as a parameter. This will schedule your work request to execute based on the request type and any constraints you add to the request.

Run your app and search for PollWorker in Logcat. You should see your log statement soon after your app starts up (Figure 27.1).

Figure 27.1  Work log

Work log

In many cases, the work you want to execute in the background is tied to the network. Maybe you are polling for new information the user has not seen yet, or you are pushing updates from the local database to save them on a remote server. While this work is important, you should make sure you are not needlessly using costly data. The best time for these requests is when the device is connected to an unmetered network.

You can use the Constraints class to add this information to your work requests. With this class, you can require certain conditions be met before your work can execute. Requiring a certain network type is one case. You can also require things like a sufficiently charged battery or that the device be charging.

Edit your OneTimeWorkRequest in PhotoGalleryFragment to add constraints to the request.

Listing 27.4  Adding work constraints (PhotoGalleryFragment.kt)

class PhotoGalleryFragment : Fragment() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        lifecycle.addObserver(thumbnailDownloader.fragmentLifecycleObserver)

        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED)
            .build()
        val workRequest = OneTimeWorkRequest
            .Builder(PollWorker::class.java)
            .setConstraints(constraints)
            .build()
        WorkManager.getInstance()
            .enqueue(workRequest)
    }
    ...
}

Similar to the work request, the Constraints object uses a builder to configure a new instance. In this case, you specify that the device must be on an unmetered network for the work request to execute.

To test this functionality, you will need to simulate different network types on your emulator. By default, an emulator connects to a simulated WiFi network. Since WiFi is an unmetered network, if you run your app now, with the constraints in place, you should see the log message from your PollWorker.

To verify that the work request does not execute when the device is on a metered network, you will need to modify the network settings for your emulator. Quit PhotoGallery and pull down on the notification shade to expose the device’s Quick Settings. Swiping down a second time once the notification shade is open exposes a larger, more descriptive version of the Quick Settings (Figure 27.2). It usually does not matter which version you use, but some older versions of Android require a double swipe to access network settings.

Figure 27.2  Accessing Quick Settings

Accessing Quick Settings

Press the WiFi icon in the Quick Settings to disable the WiFi network and force the emulator to use its (simulated) cellular network, which is metered.

With the WiFi disabled, run PhotoGallery and verify that the log from PollWorker does not appear. Before moving on, return to the Quick Settings and re-enable the WiFi network.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.193.80.126