Android fundamentals 08.3:JobScheduler
Tutorial source : Google CodeLab
Date : 2021/04/06
Complete course : 教程目录 (java).
Note : The link in this article requires Google access
1、Welcome
This practical codelab is part of Unit 3: Working in the background in the Android Developer Fundamentals (Version 2) course. You will get the most value out of this course if you work through the codelabs in sequence:
- For the complete list of codelabs in the course, see Codelabs for Android Developer Fundamentals (V2).
- For details about the course, including links to all the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).
Note: This course uses the terms “codelab” and “practical” interchangeably.
Introduction
You’ve seen that you can use the AlarmManager
class to trigger events based on the real-time clock, or based on elapsed time since boot. Most tasks, however, do not require an exact time, but should be scheduled based on a combination of system and user requirements. For example, to preserve the user’s data and system resources, a news app could wait until the device is charging and connected to Wi-Fi to update the news.
The JobScheduler
class allows you to set the conditions, or parameters, for when to run your task. Given these conditions, JobScheduler
calculates the best time to schedule the execution of the job. For example, job parameters can include the persistence of the job across reboots, whether the device is plugged in, or whether the device is idle.
The task to be run is implemented as a JobService
subclass and executed according to the specified parameters.
JobScheduler
is only available on devices running API 21 and higher, and is currently not available in the support library. For backward compatibility, use WorkManager
. The WorkManager
API lets you schedule background tasks that need guaranteed completion, whether or not the app process is around. For devices running API 14 and higher, including devices without Google Play services, WorkManager
provides capabilities that are like those provided by JobScheduler
.
In this practical, you create an app that schedules a notification. The notification is posted when the parameters set by the user are fulfilled and the system requirements are met.
What you should already know
You should be able to:
- Create an app that delivers a notification.
- Get an integer value from a
Spinner
view. - Use
Switch
views for user input. - Create
PendingIntents
.
What you’ll learn
- How to implement a
JobService
. - How to construct a
JobInfo
object with specific constraints. - How to schedule a
JobService
based on theJobInfo
object.
What you’ll do
- Implement a
JobService
that delivers a simple notification to let the user know the job is running. - Get user input to configure constraints (such as waiting until the device is charging) on the
JobService
. - Schedule the job using
JobScheduler
.
2、App overview
For this practical you create an app called Notification Scheduler. Your app will demonstrate the JobScheduler
framework by allowing the user to select constraints and schedule a job. When that job is executed, the app posts a notification. (In this app, the notification is effectively the “job.”)
To use JobScheduler
, you need to use JobService
and JobInfo
:
- A
JobInfo
object contains the set of conditions that trigger a job to run. - A
JobService
is the implementation of the job that runs under the conditions set in theJobInfo
object.
3、Task 1: Implement a JobService
To begin with, create a service that will run at a time determined by the conditions. The system automatically executes the JobService
. The only parts you need to implement are the onStartJob()
callback and the onStopJob()
callback.
About the onStartJob()
callback:
- Called when the system determines that your task should be run. In this method, you implement the job to be done.
- Returns a
boolean
indicating whether the job needs to continue on a separate thread. Iftrue
, the work is offloaded to a different thread, and your app must calljobFinished()
explicitly in that thread to indicate that the job is complete. Iffalse
, the system knows that the job is completed by the end ofonStartJob()
, and the system callsjobFinished()
on your behalf.
Note: The onStartJob()
method is executed on the main thread, and therefore any long-running tasks must be offloaded to a different thread. In this app, you are simply posting a notification, which can be done safely on the main thread.
About the onStopJob()
callback:
- If the conditions described in the
JobInfo
are no longer met, the job must be stopped, and the system callsonStopJob()
. - The
onStopJob()
callback returns aboolean
that determines what to do if the job is not finished. If the return value istrue
, the job is rescheduled; otherwise, the job is dropped.
1.1 Create the project and the NotificationJobService class
Verify that the minimum SDK you are using is API 21. Prior to API 21, JobScheduler
does not work, because it is missing some of the required APIs.
- Create a new Java project called “Notification Scheduler”. Use API 21 as the target SDK, and use the Empty Activity template.
- Inside the
com.android.example.notificationscheduler
package, create a new Java class that extendsJobService
. Call the new classNotificationJobService
. - Add the required methods, which are
onStartJob()
andonStopJob()
. Click the red light bulb next to the class declaration and select Implement methods, then select OK. - In your
AndroidManfest.xml
file, inside the<application>
tag, register yourJobService
with the following permission:
<service
android:name=".NotificationJobService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
1.2 Implement onStartJob()
Implement the following steps in NotificationJobService.java
:
- Add an image asset to use as a notification icon for the “Job” notification. Name the image
ic_job_running
. - Declare a member variable for the notification manager and a constant for the notification channel ID.
NotificationManager mNotifyManager;
// Notification channel ID.
private static final String PRIMARY_CHANNEL_ID =
"primary_notification_channel";
- Inside the
onStartJob()
method, define a method to cr