CodeLab:Android fundamentals 08.3:JobScheduler

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:

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 the JobInfo 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 the JobInfo 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. If true, the work is offloaded to a different thread, and your app must call jobFinished() explicitly in that thread to indicate that the job is complete. If false, the system knows that the job is completed by the end of onStartJob(), and the system calls jobFinished() 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 calls onStopJob().
  • The onStopJob() callback returns a boolean that determines what to do if the job is not finished. If the return value is true, 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.

  1. Create a new Java project called “Notification Scheduler”. Use API 21 as the target SDK, and use the Empty Activity template.
  2. Inside the com.android.example.notificationscheduler package, create a new Java class that extends JobService. Call the new class NotificationJobService.
  3. Add the required methods, which are onStartJob() and onStopJob(). Click the red light bulb next to the class declaration and select Implement methods, then select OK.
  4. In your AndroidManfest.xml file, inside the <application> tag, register your JobService 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:

  1. Add an image asset to use as a notification icon for the “Job” notification. Name the image ic_job_running.
  2. 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";
  1. Inside the onStartJob() method, define a method to cr
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值