1 /*
2  * Copyright (C) 2014 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.app.job;
18 
19 import static android.app.job.JobScheduler.THROW_ON_INVALID_DATA_TRANSFER_IMPLEMENTATION;
20 
21 import android.annotation.BytesLong;
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.app.Notification;
26 import android.app.Service;
27 import android.compat.Compatibility;
28 import android.content.Intent;
29 import android.os.IBinder;
30 import android.util.Log;
31 
32 import java.lang.annotation.Retention;
33 import java.lang.annotation.RetentionPolicy;
34 
35 /**
36  * <p>Entry point for the callback from the {@link android.app.job.JobScheduler}.</p>
37  * <p>This is the base class that handles asynchronous requests that were previously scheduled. You
38  * are responsible for overriding {@link JobService#onStartJob(JobParameters)}, which is where
39  * you will implement your job logic.</p>
40  * <p>This service executes each incoming job on a {@link android.os.Handler} running on your
41  * application's main thread. This means that you <b>must</b> offload your execution logic to
42  * another thread/handler/{@link android.os.AsyncTask} of your choosing. Not doing so will result
43  * in blocking any future callbacks from the JobManager - specifically
44  * {@link #onStopJob(android.app.job.JobParameters)}, which is meant to inform you that the
45  * scheduling requirements are no longer being met.</p>
46  *
47  * <p>As a subclass of {@link Service}, there will only be one active instance of any JobService
48  * subclasses, regardless of job ID. This means that if you schedule multiple jobs with different
49  * job IDs but using the same JobService class, that JobService may receive multiple calls to
50  * {@link #onStartJob(JobParameters)} and {@link #onStopJob(JobParameters)}, with each call being
51  * for the separate jobs.</p>
52  */
53 public abstract class JobService extends Service {
54     private static final String TAG = "JobService";
55 
56     /**
57      * Job services must be protected with this permission:
58      *
59      * <pre class="prettyprint">
60      *     &#60;service android:name="MyJobService"
61      *              android:permission="android.permission.BIND_JOB_SERVICE" &#62;
62      *         ...
63      *     &#60;/service&#62;
64      * </pre>
65      *
66      * <p>If a job service is declared in the manifest but not protected with this
67      * permission, that service will be ignored by the system.
68      */
69     public static final String PERMISSION_BIND =
70             "android.permission.BIND_JOB_SERVICE";
71 
72     /**
73      * Detach the notification supplied to
74      * {@link #setNotification(JobParameters, int, Notification, int)} when the job ends.
75      * The notification will remain shown even after JobScheduler stops the job.
76      */
77     public static final int JOB_END_NOTIFICATION_POLICY_DETACH = 0;
78     /**
79      * Cancel and remove the notification supplied to
80      * {@link #setNotification(JobParameters, int, Notification, int)} when the job ends.
81      * The notification will be removed from the notification shade.
82      */
83     public static final int JOB_END_NOTIFICATION_POLICY_REMOVE = 1;
84 
85     /** @hide */
86     @IntDef(prefix = {"JOB_END_NOTIFICATION_POLICY_"}, value = {
87             JOB_END_NOTIFICATION_POLICY_DETACH,
88             JOB_END_NOTIFICATION_POLICY_REMOVE,
89     })
90     @Retention(RetentionPolicy.SOURCE)
91     public @interface JobEndNotificationPolicy {
92     }
93 
94     private JobServiceEngine mEngine;
95 
96     /** @hide */
onBind(Intent intent)97     public final IBinder onBind(Intent intent) {
98         if (mEngine == null) {
99             mEngine = new JobServiceEngine(this) {
100                 @Override
101                 public boolean onStartJob(JobParameters params) {
102                     return JobService.this.onStartJob(params);
103                 }
104 
105                 @Override
106                 public boolean onStopJob(JobParameters params) {
107                     return JobService.this.onStopJob(params);
108                 }
109 
110                 @Override
111                 @BytesLong
112                 public long getTransferredDownloadBytes(@NonNull JobParameters params,
113                         @Nullable JobWorkItem item) {
114                     if (item == null) {
115                         return JobService.this.getTransferredDownloadBytes(params);
116                     } else {
117                         return JobService.this.getTransferredDownloadBytes(params, item);
118                     }
119                 }
120 
121                 @Override
122                 @BytesLong
123                 public long getTransferredUploadBytes(@NonNull JobParameters params,
124                         @Nullable JobWorkItem item) {
125                     if (item == null) {
126                         return JobService.this.getTransferredUploadBytes(params);
127                     } else {
128                         return JobService.this.getTransferredUploadBytes(params, item);
129                     }
130                 }
131 
132                 @Override
133                 public void onNetworkChanged(@NonNull JobParameters params) {
134                     JobService.this.onNetworkChanged(params);
135                 }
136             };
137         }
138         return mEngine.getBinder();
139     }
140 
141     /**
142      * Call this to inform the JobScheduler that the job has finished its work.  When the
143      * system receives this message, it releases the wakelock being held for the job.
144      * This does not need to be called if {@link #onStopJob(JobParameters)} has been called.
145      * <p>
146      * You can request that the job be scheduled again by passing {@code true} as
147      * the <code>wantsReschedule</code> parameter. This will apply back-off policy
148      * for the job; this policy can be adjusted through the
149      * {@link android.app.job.JobInfo.Builder#setBackoffCriteria(long, int)} method
150      * when the job is originally scheduled.  The job's initial
151      * requirements are preserved when jobs are rescheduled, regardless of backed-off
152      * policy.
153      * <p class="note">
154      * A job running while the device is dozing will not be rescheduled with the normal back-off
155      * policy.  Instead, the job will be re-added to the queue and executed again during
156      * a future idle maintenance window.
157      * </p>
158      *
159      * <p class="note">
160      * Any {@link JobInfo.Builder#setUserInitiated(boolean) user-initiated job}
161      * cannot be rescheduled when the user has asked to stop the app
162      * via a system provided affordance (such as the Task Manager).
163      * In such situations, the value of {@code wantsReschedule} is always treated as {@code false}.
164      *
165      * @param params The parameters identifying this job, as supplied to
166      *               the job in the {@link #onStartJob(JobParameters)} callback.
167      * @param wantsReschedule {@code true} if this job should be rescheduled according
168      *     to the back-off criteria specified when it was first scheduled; {@code false}
169      *     otherwise. When {@code false} is returned for a periodic job,
170      *     the job will be rescheduled according to its periodic policy.
171      */
jobFinished(JobParameters params, boolean wantsReschedule)172     public final void jobFinished(JobParameters params, boolean wantsReschedule) {
173         mEngine.jobFinished(params, wantsReschedule);
174     }
175 
176     /**
177      * Called to indicate that the job has begun executing.  Override this method with the
178      * logic for your job.  Like all other component lifecycle callbacks, this method executes
179      * on your application's main thread.
180      * <p>
181      * Return {@code true} from this method if your job needs to continue running.  If you
182      * do this, the job remains active until you call
183      * {@link #jobFinished(JobParameters, boolean)} to tell the system that it has completed
184      * its work, or until the job's required constraints are no longer satisfied.  For
185      * example, if the job was scheduled using
186      * {@link JobInfo.Builder#setRequiresCharging(boolean) setRequiresCharging(true)},
187      * it will be immediately halted by the system if the user unplugs the device from power,
188      * the job's {@link #onStopJob(JobParameters)} callback will be invoked, and the app
189      * will be expected to shut down all ongoing work connected with that job.
190      * <p>
191      * The system holds a wakelock on behalf of your app as long as your job is executing.
192      * This wakelock is acquired before this method is invoked, and is not released until either
193      * you call {@link #jobFinished(JobParameters, boolean)}, or after the system invokes
194      * {@link #onStopJob(JobParameters)} to notify your job that it is being shut down
195      * prematurely.
196      * <p>
197      * Returning {@code false} from this method means your job is already finished.  The
198      * system's wakelock for the job will be released, and {@link #onStopJob(JobParameters)}
199      * will not be invoked.
200      *
201      * @param params Parameters specifying info about this job, including the optional
202      *     extras configured with {@link JobInfo.Builder#setExtras(android.os.PersistableBundle)}.
203      *     This object serves to identify this specific running job instance when calling
204      *     {@link #jobFinished(JobParameters, boolean)}.
205      * @return {@code true} if your service will continue running, using a separate thread
206      *     when appropriate.  {@code false} means that this job has completed its work.
207      */
onStartJob(JobParameters params)208     public abstract boolean onStartJob(JobParameters params);
209 
210     /**
211      * This method is called if the system has determined that you must stop execution of your job
212      * even before you've had a chance to call {@link #jobFinished(JobParameters, boolean)}.
213      * Once this method is called, you no longer need to call
214      * {@link #jobFinished(JobParameters, boolean)}.
215      *
216      * <p>This may happen if the requirements specified at schedule time are no longer met. For
217      * example you may have requested WiFi with
218      * {@link android.app.job.JobInfo.Builder#setRequiredNetworkType(int)}, yet while your
219      * job was executing the user toggled WiFi. Another example is if you had specified
220      * {@link android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)}, and the phone left
221      * its idle state. There are many other reasons a job can be stopped early besides
222      * constraints no longer being satisfied. {@link JobParameters#getStopReason()} will return the
223      * reason this method was called. You are solely responsible for the behavior of your
224      * application upon receipt of this message; your app will likely start to misbehave if you
225      * ignore it.
226      * <p>
227      * Once this method returns (or times out), the system releases the wakelock that it is holding
228      * on behalf of the job.</p>
229      *
230      * <p class="note">
231      * Any {@link JobInfo.Builder#setUserInitiated(boolean) user-initiated job}
232      * cannot be rescheduled when stopped by the user via a system provided affordance (such as
233      * the Task Manager). In such situations, the returned value from this method call is always
234      * treated as {@code false}.
235      *
236      * <p class="caution"><strong>Note:</strong> When a job is stopped and rescheduled via this
237      * method call, the deadline constraint is excluded from the rescheduled job's constraint set.
238      * The rescheduled job will run again once all remaining constraints are satisfied.
239      *
240      * @param params The parameters identifying this job, similar to what was supplied to the job in
241      *               the {@link #onStartJob(JobParameters)} callback, but with the stop reason
242      *               included.
243      * @return {@code true} to indicate to the JobManager whether you'd like to reschedule
244      * this job based on the retry criteria provided at job creation-time; or {@code false}
245      * to end the job entirely (or, for a periodic job, to reschedule it according to its
246      * requested periodic criteria). Regardless of the value returned, your job must stop executing.
247      */
onStopJob(JobParameters params)248     public abstract boolean onStopJob(JobParameters params);
249 
250     /**
251      * This method is called that for a job that has a network constraint when the network
252      * to be used by the job changes. The new network object will be available via
253      * {@link JobParameters#getNetwork()}. Any network that results in this method call will
254      * match the job's requested network constraints.
255      *
256      * <p>
257      * For example, if a device is on a metered mobile network and then connects to an
258      * unmetered WiFi network, and the job has indicated that both networks satisfy its
259      * network constraint, then this method will be called to notify the job of the new
260      * unmetered WiFi network.
261      *
262      * @param params The parameters identifying this job, similar to what was supplied to the job in
263      *               the {@link #onStartJob(JobParameters)} callback, but with an updated network.
264      * @see JobInfo.Builder#setRequiredNetwork(android.net.NetworkRequest)
265      * @see JobInfo.Builder#setRequiredNetworkType(int)
266      */
onNetworkChanged(@onNull JobParameters params)267     public void onNetworkChanged(@NonNull JobParameters params) {
268         Log.w(TAG, "onNetworkChanged() not implemented in " + getClass().getName()
269                 + ". Must override in a subclass.");
270     }
271 
272     /**
273      * Update the amount of data this job is estimated to transfer after the job has started.
274      *
275      * @see JobInfo.Builder#setEstimatedNetworkBytes(long, long)
276      */
updateEstimatedNetworkBytes(@onNull JobParameters params, @BytesLong long downloadBytes, @BytesLong long uploadBytes)277     public final void updateEstimatedNetworkBytes(@NonNull JobParameters params,
278             @BytesLong long downloadBytes, @BytesLong long uploadBytes) {
279         mEngine.updateEstimatedNetworkBytes(params, null, downloadBytes, uploadBytes);
280     }
281 
282     /**
283      * Update the amount of data this JobWorkItem is estimated to transfer after the job has
284      * started.
285      *
286      * @see JobInfo.Builder#setEstimatedNetworkBytes(long, long)
287      */
updateEstimatedNetworkBytes(@onNull JobParameters params, @NonNull JobWorkItem jobWorkItem, @BytesLong long downloadBytes, @BytesLong long uploadBytes)288     public final void updateEstimatedNetworkBytes(@NonNull JobParameters params,
289             @NonNull JobWorkItem jobWorkItem,
290             @BytesLong long downloadBytes, @BytesLong long uploadBytes) {
291         mEngine.updateEstimatedNetworkBytes(params, jobWorkItem, downloadBytes, uploadBytes);
292     }
293 
294     /**
295      * Tell JobScheduler how much data has successfully been transferred for the data transfer job.
296      */
updateTransferredNetworkBytes(@onNull JobParameters params, @BytesLong long transferredDownloadBytes, @BytesLong long transferredUploadBytes)297     public final void updateTransferredNetworkBytes(@NonNull JobParameters params,
298             @BytesLong long transferredDownloadBytes, @BytesLong long transferredUploadBytes) {
299         mEngine.updateTransferredNetworkBytes(params, null,
300                 transferredDownloadBytes, transferredUploadBytes);
301     }
302 
303     /**
304      * Tell JobScheduler how much data has been transferred for the data transfer
305      * {@link JobWorkItem}.
306      */
updateTransferredNetworkBytes(@onNull JobParameters params, @NonNull JobWorkItem item, @BytesLong long transferredDownloadBytes, @BytesLong long transferredUploadBytes)307     public final void updateTransferredNetworkBytes(@NonNull JobParameters params,
308             @NonNull JobWorkItem item,
309             @BytesLong long transferredDownloadBytes, @BytesLong long transferredUploadBytes) {
310         mEngine.updateTransferredNetworkBytes(params, item,
311                 transferredDownloadBytes, transferredUploadBytes);
312     }
313 
314     /**
315      * Get the number of bytes the app has successfully downloaded for this job. JobScheduler
316      * will call this if the job has specified positive estimated download bytes and
317      * {@link #updateTransferredNetworkBytes(JobParameters, long, long)}
318      * hasn't been called recently.
319      *
320      * <p>
321      * This must be implemented for all data transfer jobs.
322      *
323      * @hide
324      * @see JobInfo.Builder#setEstimatedNetworkBytes(long, long)
325      * @see JobInfo#NETWORK_BYTES_UNKNOWN
326      */
327     // TODO(255371817): specify the actual time JS will wait for progress before requesting
328     @BytesLong
getTransferredDownloadBytes(@onNull JobParameters params)329     public long getTransferredDownloadBytes(@NonNull JobParameters params) {
330         if (Compatibility.isChangeEnabled(THROW_ON_INVALID_DATA_TRANSFER_IMPLEMENTATION)) {
331             // Regular jobs don't have to implement this and JobScheduler won't call this API for
332             // non-data transfer jobs.
333             throw new RuntimeException("Not implemented. Must override in a subclass.");
334         }
335         return 0;
336     }
337 
338     /**
339      * Get the number of bytes the app has successfully downloaded for this job. JobScheduler
340      * will call this if the job has specified positive estimated upload bytes and
341      * {@link #updateTransferredNetworkBytes(JobParameters, long, long)}
342      * hasn't been called recently.
343      *
344      * <p>
345      * This must be implemented for all data transfer jobs.
346      *
347      * @hide
348      * @see JobInfo.Builder#setEstimatedNetworkBytes(long, long)
349      * @see JobInfo#NETWORK_BYTES_UNKNOWN
350      */
351     // TODO(255371817): specify the actual time JS will wait for progress before requesting
352     @BytesLong
getTransferredUploadBytes(@onNull JobParameters params)353     public long getTransferredUploadBytes(@NonNull JobParameters params) {
354         if (Compatibility.isChangeEnabled(THROW_ON_INVALID_DATA_TRANSFER_IMPLEMENTATION)) {
355             // Regular jobs don't have to implement this and JobScheduler won't call this API for
356             // non-data transfer jobs.
357             throw new RuntimeException("Not implemented. Must override in a subclass.");
358         }
359         return 0;
360     }
361 
362     /**
363      * Get the number of bytes the app has successfully downloaded for this job. JobScheduler
364      * will call this if the job has specified positive estimated download bytes and
365      * {@link #updateTransferredNetworkBytes(JobParameters, JobWorkItem, long, long)}
366      * hasn't been called recently and the job has
367      * {@link JobWorkItem JobWorkItems} that have been
368      * {@link JobParameters#dequeueWork dequeued} but not
369      * {@link JobParameters#completeWork(JobWorkItem) completed}.
370      *
371      * <p>
372      * This must be implemented for all data transfer jobs.
373      *
374      * @hide
375      * @see JobInfo#NETWORK_BYTES_UNKNOWN
376      */
377     // TODO(255371817): specify the actual time JS will wait for progress before requesting
378     @BytesLong
getTransferredDownloadBytes(@onNull JobParameters params, @NonNull JobWorkItem item)379     public long getTransferredDownloadBytes(@NonNull JobParameters params,
380             @NonNull JobWorkItem item) {
381         if (item == null) {
382             return getTransferredDownloadBytes(params);
383         }
384         if (Compatibility.isChangeEnabled(THROW_ON_INVALID_DATA_TRANSFER_IMPLEMENTATION)) {
385             // Regular jobs don't have to implement this and JobScheduler won't call this API for
386             // non-data transfer jobs.
387             throw new RuntimeException("Not implemented. Must override in a subclass.");
388         }
389         return 0;
390     }
391 
392     /**
393      * Get the number of bytes the app has successfully downloaded for this job. JobScheduler
394      * will call this if the job has specified positive estimated upload bytes and
395      * {@link #updateTransferredNetworkBytes(JobParameters, JobWorkItem, long, long)}
396      * hasn't been called recently and the job has
397      * {@link JobWorkItem JobWorkItems} that have been
398      * {@link JobParameters#dequeueWork dequeued} but not
399      * {@link JobParameters#completeWork(JobWorkItem) completed}.
400      *
401      * <p>
402      * This must be implemented for all data transfer jobs.
403      *
404      * @hide
405      * @see JobInfo#NETWORK_BYTES_UNKNOWN
406      */
407     // TODO(255371817): specify the actual time JS will wait for progress before requesting
408     @BytesLong
getTransferredUploadBytes(@onNull JobParameters params, @NonNull JobWorkItem item)409     public long getTransferredUploadBytes(@NonNull JobParameters params,
410             @NonNull JobWorkItem item) {
411         if (item == null) {
412             return getTransferredUploadBytes(params);
413         }
414         if (Compatibility.isChangeEnabled(THROW_ON_INVALID_DATA_TRANSFER_IMPLEMENTATION)) {
415             // Regular jobs don't have to implement this and JobScheduler won't call this API for
416             // non-data transfer jobs.
417             throw new RuntimeException("Not implemented. Must override in a subclass.");
418         }
419         return 0;
420     }
421 
422     /**
423      * Provide JobScheduler with a notification to post and tie to this job's lifecycle.
424      * This is only required for those user-initiated jobs which return {@code true} via
425      * {@link JobParameters#isUserInitiatedJob()}.
426      * If the app does not call this method for a required notification within
427      * 10 seconds after {@link #onStartJob(JobParameters)} is called,
428      * the system will trigger an ANR and stop this job.
429      *
430      * The notification must provide an accurate description of the work that the job is doing
431      * and, if possible, the state of the work.
432      *
433      * <p>
434      * Note that certain types of jobs
435      * (e.g. {@link JobInfo.Builder#setEstimatedNetworkBytes(long, long) data transfer jobs})
436      * may require the notification to have certain characteristics
437      * and their documentation will state any such requirements.
438      *
439      * <p>
440      * JobScheduler will not remember this notification after the job has finished running,
441      * so apps must call this every time the job is started (if required or desired).
442      *
443      * <p>
444      * If separate jobs use the same notification ID with this API, the most recently provided
445      * notification will be shown to the user, and the
446      * {@code jobEndNotificationPolicy} of the last job to stop will be applied.
447      *
448      * @param params                   The parameters identifying this job, as supplied to
449      *                                 the job in the {@link #onStartJob(JobParameters)} callback.
450      * @param notificationId           The ID for this notification, as per
451      *                                 {@link android.app.NotificationManager#notify(int,
452      *                                 Notification)}.
453      * @param notification             The notification to be displayed.
454      * @param jobEndNotificationPolicy The policy to apply to the notification when the job stops.
455      */
setNotification(@onNull JobParameters params, int notificationId, @NonNull Notification notification, @JobEndNotificationPolicy int jobEndNotificationPolicy)456     public final void setNotification(@NonNull JobParameters params, int notificationId,
457             @NonNull Notification notification,
458             @JobEndNotificationPolicy int jobEndNotificationPolicy) {
459         mEngine.setNotification(params, notificationId, notification, jobEndNotificationPolicy);
460     }
461 }
462