1 /*
2  * Copyright (C) 2019 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 package com.android.car.bugreport;
17 
18 import android.app.job.JobInfo;
19 import android.app.job.JobScheduler;
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.util.Log;
23 
24 /**
25  * Utilities for scheduling upload jobs.
26  */
27 class JobSchedulingUtils {
28     private static final String TAG = JobSchedulingUtils.class.getSimpleName();
29 
30     private static final int UPLOAD_JOB_ID = 1;
31     private static final int RETRY_DELAY_IN_MS = 5_000;
32 
33     /**
34      * Schedules {@link UploadJob} under the current user.
35      *
36      * <p>Make sure this method is called under the primary user.
37      *
38      * <ul>
39      *   <li>require network connectivity
40      *   <li>good quality network (large upload size)
41      *   <li>persist across reboots
42      * </ul>
43      */
scheduleUploadJob(Context context)44     static void scheduleUploadJob(Context context) {
45         JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
46         if (jobScheduler == null) {
47             Log.w(TAG, "Cannot get JobScheduler from context.");
48             return;
49         }
50 
51         JobInfo pendingJob = jobScheduler.getPendingJob(UPLOAD_JOB_ID);
52         // if there is already a pending job, do not schedule a new one.
53         if (pendingJob != null) {
54             Log.d(TAG, "Upload job is already active, not re-scheduling");
55             return;
56         }
57 
58         // NOTE: Don't set estimated network bytes, because we want bug reports to be uploaded
59         //       without any constraints.
60         jobScheduler.schedule(new JobInfo.Builder(UPLOAD_JOB_ID,
61                 new ComponentName(context, UploadJob.class))
62                 .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
63                 .setBackoffCriteria(RETRY_DELAY_IN_MS, JobInfo.BACKOFF_POLICY_LINEAR)
64                 .build());
65     }
66 }
67