1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.car.builtin.job;
18 
19 import android.annotation.SystemApi;
20 import android.app.job.JobInfo;
21 import android.app.job.JobScheduler;
22 import android.app.job.JobSnapshot;
23 import android.content.Context;
24 
25 import java.util.ArrayList;
26 import java.util.List;
27 
28 /**
29  * Helper for JobScheduler related operations.
30  *
31  * @hide
32  */
33 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
34 public final class JobSchedulerHelper {
35 
JobSchedulerHelper()36     private JobSchedulerHelper() {
37         throw new UnsupportedOperationException("contains only static members");
38     }
39 
40     /** Gets the running jobs which are executed when a device goes idle. */
getRunningJobsAtIdle(Context context)41     public static List<JobInfo> getRunningJobsAtIdle(Context context) {
42         List<JobInfo> startedJobs = context.getSystemService(JobScheduler.class).getStartedJobs();
43         if (startedJobs == null) {
44             return new ArrayList<>();
45         }
46         List<JobInfo> deviceIdleJobs = new ArrayList<>();
47         for (int idx = 0; idx < startedJobs.size(); idx++) {
48             JobInfo jobInfo = startedJobs.get(idx);
49             if (jobInfo.isRequireDeviceIdle()) {
50                 deviceIdleJobs.add(jobInfo);
51             }
52         }
53         return deviceIdleJobs;
54     }
55 
56     /** Gets the jobs which are scheduled for execution at idle but not finished. */
getPendingJobs(Context context)57     public static List<JobInfo> getPendingJobs(Context context) {
58         List<JobSnapshot> allScheduledJobs =
59                 context.getSystemService(JobScheduler.class).getAllJobSnapshots();
60         if (allScheduledJobs == null) {
61             return new ArrayList<>();
62         }
63         List<JobInfo> idleJobs = new ArrayList<>();
64         for (int idx = 0; idx < allScheduledJobs.size(); idx++) {
65             JobSnapshot scheduledJob = allScheduledJobs.get(idx);
66             JobInfo jobInfo = scheduledJob.getJobInfo();
67             if (scheduledJob.isRunnable() && jobInfo.isRequireDeviceIdle()) {
68                 idleJobs.add(jobInfo);
69             }
70         }
71         return idleJobs;
72     }
73 }
74