• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 android.app.Service;
20 import android.content.Intent;
21 import android.os.Handler;
22 import android.os.IBinder;
23 import android.os.Looper;
24 import android.os.Message;
25 import android.os.RemoteException;
26 import android.util.Log;
27 
28 import com.android.internal.annotations.GuardedBy;
29 
30 import java.lang.ref.WeakReference;
31 
32 /**
33  * <p>Entry point for the callback from the {@link android.app.job.JobScheduler}.</p>
34  * <p>This is the base class that handles asynchronous requests that were previously scheduled. You
35  * are responsible for overriding {@link JobService#onStartJob(JobParameters)}, which is where
36  * you will implement your job logic.</p>
37  * <p>This service executes each incoming job on a {@link android.os.Handler} running on your
38  * application's main thread. This means that you <b>must</b> offload your execution logic to
39  * another thread/handler/{@link android.os.AsyncTask} of your choosing. Not doing so will result
40  * in blocking any future callbacks from the JobManager - specifically
41  * {@link #onStopJob(android.app.job.JobParameters)}, which is meant to inform you that the
42  * scheduling requirements are no longer being met.</p>
43  */
44 public abstract class JobService extends Service {
45     private static final String TAG = "JobService";
46 
47     /**
48      * Job services must be protected with this permission:
49      *
50      * <pre class="prettyprint">
51      *     &#60;service android:name="MyJobService"
52      *              android:permission="android.permission.BIND_JOB_SERVICE" &#62;
53      *         ...
54      *     &#60;/service&#62;
55      * </pre>
56      *
57      * <p>If a job service is declared in the manifest but not protected with this
58      * permission, that service will be ignored by the OS.
59      */
60     public static final String PERMISSION_BIND =
61             "android.permission.BIND_JOB_SERVICE";
62 
63     /**
64      * Identifier for a message that will result in a call to
65      * {@link #onStartJob(android.app.job.JobParameters)}.
66      */
67     private static final int MSG_EXECUTE_JOB = 0;
68     /**
69      * Message that will result in a call to {@link #onStopJob(android.app.job.JobParameters)}.
70      */
71     private static final int MSG_STOP_JOB = 1;
72     /**
73      * Message that the client has completed execution of this job.
74      */
75     private static final int MSG_JOB_FINISHED = 2;
76 
77     /** Lock object for {@link #mHandler}. */
78     private final Object mHandlerLock = new Object();
79 
80     /**
81      * Handler we post jobs to. Responsible for calling into the client logic, and handling the
82      * callback to the system.
83      */
84     @GuardedBy("mHandlerLock")
85     JobHandler mHandler;
86 
87     static final class JobInterface extends IJobService.Stub {
88         final WeakReference<JobService> mService;
89 
JobInterface(JobService service)90         JobInterface(JobService service) {
91             mService = new WeakReference<>(service);
92         }
93 
94         @Override
startJob(JobParameters jobParams)95         public void startJob(JobParameters jobParams) throws RemoteException {
96             JobService service = mService.get();
97             if (service != null) {
98                 service.ensureHandler();
99                 Message m = Message.obtain(service.mHandler, MSG_EXECUTE_JOB, jobParams);
100                 m.sendToTarget();
101             }
102         }
103 
104         @Override
stopJob(JobParameters jobParams)105         public void stopJob(JobParameters jobParams) throws RemoteException {
106             JobService service = mService.get();
107             if (service != null) {
108                 service.ensureHandler();
109                 Message m = Message.obtain(service.mHandler, MSG_STOP_JOB, jobParams);
110                 m.sendToTarget();
111             }
112 
113         }
114     }
115 
116     IJobService mBinder;
117 
118     /** @hide */
ensureHandler()119     void ensureHandler() {
120         synchronized (mHandlerLock) {
121             if (mHandler == null) {
122                 mHandler = new JobHandler(getMainLooper());
123             }
124         }
125     }
126 
127     /**
128      * Runs on application's main thread - callbacks are meant to offboard work to some other
129      * (app-specified) mechanism.
130      * @hide
131      */
132     class JobHandler extends Handler {
JobHandler(Looper looper)133         JobHandler(Looper looper) {
134             super(looper);
135         }
136 
137         @Override
handleMessage(Message msg)138         public void handleMessage(Message msg) {
139             final JobParameters params = (JobParameters) msg.obj;
140             switch (msg.what) {
141                 case MSG_EXECUTE_JOB:
142                     try {
143                         boolean workOngoing = JobService.this.onStartJob(params);
144                         ackStartMessage(params, workOngoing);
145                     } catch (Exception e) {
146                         Log.e(TAG, "Error while executing job: " + params.getJobId());
147                         throw new RuntimeException(e);
148                     }
149                     break;
150                 case MSG_STOP_JOB:
151                     try {
152                         boolean ret = JobService.this.onStopJob(params);
153                         ackStopMessage(params, ret);
154                     } catch (Exception e) {
155                         Log.e(TAG, "Application unable to handle onStopJob.", e);
156                         throw new RuntimeException(e);
157                     }
158                     break;
159                 case MSG_JOB_FINISHED:
160                     final boolean needsReschedule = (msg.arg2 == 1);
161                     IJobCallback callback = params.getCallback();
162                     if (callback != null) {
163                         try {
164                             callback.jobFinished(params.getJobId(), needsReschedule);
165                         } catch (RemoteException e) {
166                             Log.e(TAG, "Error reporting job finish to system: binder has gone" +
167                                     "away.");
168                         }
169                     } else {
170                         Log.e(TAG, "finishJob() called for a nonexistent job id.");
171                     }
172                     break;
173                 default:
174                     Log.e(TAG, "Unrecognised message received.");
175                     break;
176             }
177         }
178 
ackStartMessage(JobParameters params, boolean workOngoing)179         private void ackStartMessage(JobParameters params, boolean workOngoing) {
180             final IJobCallback callback = params.getCallback();
181             final int jobId = params.getJobId();
182             if (callback != null) {
183                 try {
184                      callback.acknowledgeStartMessage(jobId, workOngoing);
185                 } catch(RemoteException e) {
186                     Log.e(TAG, "System unreachable for starting job.");
187                 }
188             } else {
189                 if (Log.isLoggable(TAG, Log.DEBUG)) {
190                     Log.d(TAG, "Attempting to ack a job that has already been processed.");
191                 }
192             }
193         }
194 
ackStopMessage(JobParameters params, boolean reschedule)195         private void ackStopMessage(JobParameters params, boolean reschedule) {
196             final IJobCallback callback = params.getCallback();
197             final int jobId = params.getJobId();
198             if (callback != null) {
199                 try {
200                     callback.acknowledgeStopMessage(jobId, reschedule);
201                 } catch(RemoteException e) {
202                     Log.e(TAG, "System unreachable for stopping job.");
203                 }
204             } else {
205                 if (Log.isLoggable(TAG, Log.DEBUG)) {
206                     Log.d(TAG, "Attempting to ack a job that has already been processed.");
207                 }
208             }
209         }
210     }
211 
212     /** @hide */
onBind(Intent intent)213     public final IBinder onBind(Intent intent) {
214         if (mBinder == null) {
215             mBinder = new JobInterface(this);
216         }
217         return mBinder.asBinder();
218     }
219 
220     /**
221      * Override this method with the callback logic for your job. Any such logic needs to be
222      * performed on a separate thread, as this function is executed on your application's main
223      * thread.
224      *
225      * @param params Parameters specifying info about this job, including the extras bundle you
226      *               optionally provided at job-creation time.
227      * @return True if your service needs to process the work (on a separate thread). False if
228      * there's no more work to be done for this job.
229      */
onStartJob(JobParameters params)230     public abstract boolean onStartJob(JobParameters params);
231 
232     /**
233      * This method is called if the system has determined that you must stop execution of your job
234      * even before you've had a chance to call {@link #jobFinished(JobParameters, boolean)}.
235      *
236      * <p>This will happen if the requirements specified at schedule time are no longer met. For
237      * example you may have requested WiFi with
238      * {@link android.app.job.JobInfo.Builder#setRequiredNetworkType(int)}, yet while your
239      * job was executing the user toggled WiFi. Another example is if you had specified
240      * {@link android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)}, and the phone left its
241      * idle maintenance window. You are solely responsible for the behaviour of your application
242      * upon receipt of this message; your app will likely start to misbehave if you ignore it. One
243      * immediate repercussion is that the system will cease holding a wakelock for you.</p>
244      *
245      * @param params Parameters specifying info about this job.
246      * @return True to indicate to the JobManager whether you'd like to reschedule this job based
247      * on the retry criteria provided at job creation-time. False to drop the job. Regardless of
248      * the value returned, your job must stop executing.
249      */
onStopJob(JobParameters params)250     public abstract boolean onStopJob(JobParameters params);
251 
252     /**
253      * Callback to inform the JobManager you've finished executing. This can be called from any
254      * thread, as it will ultimately be run on your application's main thread. When the system
255      * receives this message it will release the wakelock being held.
256      * <p>
257      *     You can specify post-execution behaviour to the scheduler here with
258      *     <code>needsReschedule </code>. This will apply a back-off timer to your job based on
259      *     the default, or what was set with
260      *     {@link android.app.job.JobInfo.Builder#setBackoffCriteria(long, int)}. The original
261      *     requirements are always honoured even for a backed-off job. Note that a job running in
262      *     idle mode will not be backed-off. Instead what will happen is the job will be re-added
263      *     to the queue and re-executed within a future idle maintenance window.
264      * </p>
265      *
266      * @param params Parameters specifying system-provided info about this job, this was given to
267      *               your application in {@link #onStartJob(JobParameters)}.
268      * @param needsReschedule True if this job should be rescheduled according to the back-off
269      *                        criteria specified at schedule-time. False otherwise.
270      */
jobFinished(JobParameters params, boolean needsReschedule)271     public final void jobFinished(JobParameters params, boolean needsReschedule) {
272         ensureHandler();
273         Message m = Message.obtain(mHandler, MSG_JOB_FINISHED, params);
274         m.arg2 = needsReschedule ? 1 : 0;
275         m.sendToTarget();
276     }
277 }