blob: f116e133e3381caeaf2d526fd446061a6788ba1d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
17package android.app;
18
Hui Yu2d4207f2019-01-22 15:32:20 -080019import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
20
Dianne Hackborn67324c92016-04-18 13:55:25 -070021import android.annotation.IntDef;
Hui Yu2d4207f2019-01-22 15:32:20 -080022import android.annotation.NonNull;
Scott Kennedy7db73ed2015-02-19 15:31:11 -080023import android.annotation.Nullable;
Mathew Inwood4fb17d12018-08-14 14:25:44 +010024import android.annotation.UnsupportedAppUsage;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070025import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.Context;
kopriva762a08f2018-10-03 16:09:03 -070028import android.content.ContextWrapper;
29import android.content.Intent;
Hui Yub8dcbee2019-02-14 13:50:01 -080030import android.content.pm.ServiceInfo.ForegroundServiceType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.res.Configuration;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070032import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.os.IBinder;
kopriva762a08f2018-10-03 16:09:03 -070034import android.os.RemoteException;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070035import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
37import java.io.FileDescriptor;
38import java.io.PrintWriter;
Dianne Hackborn67324c92016-04-18 13:55:25 -070039import java.lang.annotation.Retention;
40import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
42/**
Dianne Hackbornee3bcc42010-04-15 11:33:38 -070043 * A Service is an application component representing either an application's desire
44 * to perform a longer-running operation while not interacting with the user
45 * or to supply functionality for other applications to use. Each service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046 * class must have a corresponding
47 * {@link android.R.styleable#AndroidManifestService <service>}
48 * declaration in its package's <code>AndroidManifest.xml</code>. Services
49 * can be started with
50 * {@link android.content.Context#startService Context.startService()} and
51 * {@link android.content.Context#bindService Context.bindService()}.
52 *
53 * <p>Note that services, like other application objects, run in the main
54 * thread of their hosting process. This means that, if your service is going
55 * to do any CPU intensive (such as MP3 playback) or blocking (such as
56 * networking) operations, it should spawn its own thread in which to do that
57 * work. More information on this can be found in
Scott Main7aee61f2011-02-08 11:25:01 -080058 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
59 * Threads</a>. The {@link IntentService} class is available
Dianne Hackbornee3bcc42010-04-15 11:33:38 -070060 * as a standard implementation of Service that has its own thread where it
61 * schedules its work to be done.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 *
63 * <p>Topics covered here:
64 * <ol>
Dianne Hackbornee3bcc42010-04-15 11:33:38 -070065 * <li><a href="#WhatIsAService">What is a Service?</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * <li><a href="#ServiceLifecycle">Service Lifecycle</a>
67 * <li><a href="#Permissions">Permissions</a>
68 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
Dianne Hackborn75288fa2010-02-16 18:01:18 -080069 * <li><a href="#LocalServiceSample">Local Service Sample</a>
70 * <li><a href="#RemoteMessengerServiceSample">Remote Messenger Service Sample</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * </ol>
Joe Fernandezb54e7a32011-10-03 15:09:50 -070072 *
73 * <div class="special reference">
74 * <h3>Developer Guides</h3>
75 * <p>For a detailed discussion about how to create services, read the
76 * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
77 * </div>
78 *
Dianne Hackbornee3bcc42010-04-15 11:33:38 -070079 * <a name="WhatIsAService"></a>
80 * <h3>What is a Service?</h3>
81 *
82 * <p>Most confusion about the Service class actually revolves around what
83 * it is <em>not</em>:</p>
84 *
85 * <ul>
86 * <li> A Service is <b>not</b> a separate process. The Service object itself
87 * does not imply it is running in its own process; unless otherwise specified,
88 * it runs in the same process as the application it is part of.
89 * <li> A Service is <b>not</b> a thread. It is not a means itself to do work off
90 * of the main thread (to avoid Application Not Responding errors).
91 * </ul>
92 *
93 * <p>Thus a Service itself is actually very simple, providing two main features:</p>
94 *
95 * <ul>
96 * <li>A facility for the application to tell the system <em>about</em>
97 * something it wants to be doing in the background (even when the user is not
98 * directly interacting with the application). This corresponds to calls to
99 * {@link android.content.Context#startService Context.startService()}, which
100 * ask the system to schedule work for the service, to be run until the service
101 * or someone else explicitly stop it.
102 * <li>A facility for an application to expose some of its functionality to
103 * other applications. This corresponds to calls to
104 * {@link android.content.Context#bindService Context.bindService()}, which
105 * allows a long-standing connection to be made to the service in order to
106 * interact with it.
107 * </ul>
108 *
109 * <p>When a Service component is actually created, for either of these reasons,
110 * all that the system actually does is instantiate the component
111 * and call its {@link #onCreate} and any other appropriate callbacks on the
112 * main thread. It is up to the Service to implement these with the appropriate
113 * behavior, such as creating a secondary thread in which it does its work.</p>
114 *
115 * <p>Note that because Service itself is so simple, you can make your
116 * interaction with it as simple or complicated as you want: from treating it
117 * as a local Java object that you make direct method calls on (as illustrated
118 * by <a href="#LocalServiceSample">Local Service Sample</a>), to providing
119 * a full remoteable interface using AIDL.</p>
120 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * <a name="ServiceLifecycle"></a>
122 * <h3>Service Lifecycle</h3>
123 *
124 * <p>There are two reasons that a service can be run by the system. If someone
125 * calls {@link android.content.Context#startService Context.startService()} then the system will
126 * retrieve the service (creating it and calling its {@link #onCreate} method
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700127 * if needed) and then call its {@link #onStartCommand} method with the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 * arguments supplied by the client. The service will at this point continue
129 * running until {@link android.content.Context#stopService Context.stopService()} or
130 * {@link #stopSelf()} is called. Note that multiple calls to
131 * Context.startService() do not nest (though they do result in multiple corresponding
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700132 * calls to onStartCommand()), so no matter how many times it is started a service
133 * will be stopped once Context.stopService() or stopSelf() is called; however,
134 * services can use their {@link #stopSelf(int)} method to ensure the service is
135 * not stopped until started intents have been processed.
136 *
137 * <p>For started services, there are two additional major modes of operation
138 * they can decide to run in, depending on the value they return from
139 * onStartCommand(): {@link #START_STICKY} is used for services that are
140 * explicitly started and stopped as needed, while {@link #START_NOT_STICKY}
141 * or {@link #START_REDELIVER_INTENT} are used for services that should only
142 * remain running while processing any commands sent to them. See the linked
143 * documentation for more detail on the semantics.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 *
145 * <p>Clients can also use {@link android.content.Context#bindService Context.bindService()} to
146 * obtain a persistent connection to a service. This likewise creates the
147 * service if it is not already running (calling {@link #onCreate} while
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700148 * doing so), but does not call onStartCommand(). The client will receive the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 * {@link android.os.IBinder} object that the service returns from its
150 * {@link #onBind} method, allowing the client to then make calls back
151 * to the service. The service will remain running as long as the connection
152 * is established (whether or not the client retains a reference on the
153 * service's IBinder). Usually the IBinder returned is for a complex
Scott Main40eee612012-08-06 17:48:37 -0700154 * interface that has been <a href="{@docRoot}guide/components/aidl.html">written
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 * in aidl</a>.
156 *
157 * <p>A service can be both started and have connections bound to it. In such
158 * a case, the system will keep the service running as long as either it is
159 * started <em>or</em> there are one or more connections to it with the
160 * {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE}
161 * flag. Once neither
162 * of these situations hold, the service's {@link #onDestroy} method is called
163 * and the service is effectively terminated. All cleanup (stopping threads,
164 * unregistering receivers) should be complete upon returning from onDestroy().
165 *
166 * <a name="Permissions"></a>
167 * <h3>Permissions</h3>
168 *
169 * <p>Global access to a service can be enforced when it is declared in its
170 * manifest's {@link android.R.styleable#AndroidManifestService &lt;service&gt;}
171 * tag. By doing so, other applications will need to declare a corresponding
172 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
173 * element in their own manifest to be able to start, stop, or bind to
174 * the service.
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800175 *
176 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, when using
177 * {@link Context#startService(Intent) Context.startService(Intent)}, you can
178 * also set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
179 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
180 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
181 * Service temporary access to the specific URIs in the Intent. Access will
182 * remain until the Service has called {@link #stopSelf(int)} for that start
183 * command or a later one, or until the Service has been completely stopped.
184 * This works for granting access to the other apps that have not requested
185 * the permission protecting the Service, or even when the Service is not
186 * exported at all.
187 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 * <p>In addition, a service can protect individual IPC calls into it with
189 * permissions, by calling the
190 * {@link #checkCallingPermission}
191 * method before executing the implementation of that call.
192 *
193 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
194 * document for more information on permissions and security in general.
195 *
196 * <a name="ProcessLifecycle"></a>
197 * <h3>Process Lifecycle</h3>
198 *
199 * <p>The Android system will attempt to keep the process hosting a service
200 * around as long as the service has been started or has clients bound to it.
201 * When running low on memory and needing to kill existing processes, the
202 * priority of a process hosting the service will be the higher of the
203 * following possibilities:
Dianne Hackbornab4a81b2014-10-09 17:59:38 -0700204 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 * <ul>
206 * <li><p>If the service is currently executing code in its
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700207 * {@link #onCreate onCreate()}, {@link #onStartCommand onStartCommand()},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 * or {@link #onDestroy onDestroy()} methods, then the hosting process will
209 * be a foreground process to ensure this code can execute without
210 * being killed.
211 * <li><p>If the service has been started, then its hosting process is considered
212 * to be less important than any processes that are currently visible to the
213 * user on-screen, but more important than any process not visible. Because
214 * only a few processes are generally visible to the user, this means that
Dianne Hackbornab4a81b2014-10-09 17:59:38 -0700215 * the service should not be killed except in low memory conditions. However, since
216 * the user is not directly aware of a background service, in that state it <em>is</em>
217 * considered a valid candidate to kill, and you should be prepared for this to
218 * happen. In particular, long-running services will be increasingly likely to
219 * kill and are guaranteed to be killed (and restarted if appropriate) if they
220 * remain started long enough.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 * <li><p>If there are clients bound to the service, then the service's hosting
222 * process is never less important than the most important client. That is,
223 * if one of its clients is visible to the user, then the service itself is
Dianne Hackbornab4a81b2014-10-09 17:59:38 -0700224 * considered to be visible. The way a client's importance impacts the service's
225 * importance can be adjusted through {@link Context#BIND_ABOVE_CLIENT},
226 * {@link Context#BIND_ALLOW_OOM_MANAGEMENT}, {@link Context#BIND_WAIVE_PRIORITY},
227 * {@link Context#BIND_IMPORTANT}, and {@link Context#BIND_ADJUST_WITH_ACTIVITY}.
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700228 * <li><p>A started service can use the {@link #startForeground(int, Notification)}
229 * API to put the service in a foreground state, where the system considers
230 * it to be something the user is actively aware of and thus not a candidate
231 * for killing when low on memory. (It is still theoretically possible for
232 * the service to be killed under extreme memory pressure from the current
233 * foreground application, but in practice this should not be a concern.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 * </ul>
235 *
236 * <p>Note this means that most of the time your service is running, it may
237 * be killed by the system if it is under heavy memory pressure. If this
238 * happens, the system will later try to restart the service. An important
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700239 * consequence of this is that if you implement {@link #onStartCommand onStartCommand()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 * to schedule work to be done asynchronously or in another thread, then you
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700241 * may want to use {@link #START_FLAG_REDELIVERY} to have the system
242 * re-deliver an Intent for you so that it does not get lost if your service
243 * is killed while processing it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 *
245 * <p>Other application components running in the same process as the service
246 * (such as an {@link android.app.Activity}) can, of course, increase the
247 * importance of the overall
248 * process beyond just the importance of the service itself.
Dianne Hackborn75288fa2010-02-16 18:01:18 -0800249 *
250 * <a name="LocalServiceSample"></a>
251 * <h3>Local Service Sample</h3>
252 *
253 * <p>One of the most common uses of a Service is as a secondary component
254 * running alongside other parts of an application, in the same process as
255 * the rest of the components. All components of an .apk run in the same
256 * process unless explicitly stated otherwise, so this is a typical situation.
257 *
258 * <p>When used in this way, by assuming the
259 * components are in the same process, you can greatly simplify the interaction
260 * between them: clients of the service can simply cast the IBinder they
261 * receive from it to a concrete class published by the service.
262 *
263 * <p>An example of this use of a Service is shown here. First is the Service
264 * itself, publishing a custom class when bound:
265 *
266 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalService.java
267 * service}
268 *
269 * <p>With that done, one can now write client code that directly accesses the
270 * running service, such as:
271 *
272 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.java
273 * bind}
274 *
275 * <a name="RemoteMessengerServiceSample"></a>
276 * <h3>Remote Messenger Service Sample</h3>
277 *
278 * <p>If you need to be able to write a Service that can perform complicated
279 * communication with clients in remote processes (beyond simply the use of
280 * {@link Context#startService(Intent) Context.startService} to send
281 * commands to it), then you can use the {@link android.os.Messenger} class
282 * instead of writing full AIDL files.
283 *
284 * <p>An example of a Service that uses Messenger as its client interface
285 * is shown here. First is the Service itself, publishing a Messenger to
286 * an internal Handler when bound:
287 *
288 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.java
289 * service}
290 *
291 * <p>If we want to make this service run in a remote process (instead of the
292 * standard one for its .apk), we can use <code>android:process</code> in its
293 * manifest tag to specify one:
294 *
295 * {@sample development/samples/ApiDemos/AndroidManifest.xml remote_service_declaration}
296 *
297 * <p>Note that the name "remote" chosen here is arbitrary, and you can use
298 * other names if you want additional processes. The ':' prefix appends the
299 * name to your package's standard process name.
300 *
301 * <p>With that done, clients can now bind to the service and send messages
302 * to it. Note that this allows clients to register with it to receive
303 * messages back as well:
304 *
305 * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java
306 * bind}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700308public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 private static final String TAG = "Service";
310
Dianne Hackborn67324c92016-04-18 13:55:25 -0700311 /**
312 * Flag for {@link #stopForeground(int)}: if set, the notification previously provided
313 * to {@link #startForeground} will be removed. Otherwise it will remain
314 * until a later call (to {@link #startForeground(int, Notification)} or
315 * {@link #stopForeground(int)} removes it, or the service is destroyed.
316 */
317 public static final int STOP_FOREGROUND_REMOVE = 1<<0;
318
319 /**
320 * Flag for {@link #stopForeground(int)}: if set, the notification previously provided
321 * to {@link #startForeground} will be detached from the service. Only makes sense
322 * when {@link #STOP_FOREGROUND_REMOVE} is <b>not</b> set -- in this case, the notification
323 * will remain shown, but be completely detached from the service and so no longer changed
324 * except through direct calls to the notification manager.
325 */
326 public static final int STOP_FOREGROUND_DETACH = 1<<1;
327
328 /** @hide */
Jeff Sharkey6503bd82017-04-19 23:24:18 -0600329 @IntDef(flag = true, prefix = { "STOP_FOREGROUND_" }, value = {
330 STOP_FOREGROUND_REMOVE,
331 STOP_FOREGROUND_DETACH
332 })
Dianne Hackborn67324c92016-04-18 13:55:25 -0700333 @Retention(RetentionPolicy.SOURCE)
334 public @interface StopForegroundFlags {}
335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 public Service() {
337 super(null);
338 }
339
340 /** Return the application that owns this service. */
341 public final Application getApplication() {
342 return mApplication;
343 }
344
345 /**
346 * Called by the system when the service is first created. Do not call this method directly.
347 */
348 public void onCreate() {
349 }
350
351 /**
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700352 * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 */
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700354 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 public void onStart(Intent intent, int startId) {
356 }
357
358 /**
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700359 * Bits returned by {@link #onStartCommand} describing how to continue
360 * the service if it is killed. May be {@link #START_STICKY},
361 * {@link #START_NOT_STICKY}, {@link #START_REDELIVER_INTENT},
362 * or {@link #START_STICKY_COMPATIBILITY}.
363 */
364 public static final int START_CONTINUATION_MASK = 0xf;
365
366 /**
367 * Constant to return from {@link #onStartCommand}: compatibility
368 * version of {@link #START_STICKY} that does not guarantee that
369 * {@link #onStartCommand} will be called again after being killed.
370 */
371 public static final int START_STICKY_COMPATIBILITY = 0;
372
373 /**
374 * Constant to return from {@link #onStartCommand}: if this service's
375 * process is killed while it is started (after returning from
376 * {@link #onStartCommand}), then leave it in the started state but
377 * don't retain this delivered intent. Later the system will try to
Dianne Hackbornfed534e2009-09-23 00:42:12 -0700378 * re-create the service. Because it is in the started state, it will
379 * guarantee to call {@link #onStartCommand} after creating the new
380 * service instance; if there are not any pending start commands to be
381 * delivered to the service, it will be called with a null intent
382 * object, so you must take care to check for this.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700383 *
384 * <p>This mode makes sense for things that will be explicitly started
385 * and stopped to run for arbitrary periods of time, such as a service
386 * performing background music playback.
387 */
388 public static final int START_STICKY = 1;
389
390 /**
391 * Constant to return from {@link #onStartCommand}: if this service's
392 * process is killed while it is started (after returning from
393 * {@link #onStartCommand}), and there are no new start intents to
394 * deliver to it, then take the service out of the started state and
395 * don't recreate until a future explicit call to
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700396 * {@link Context#startService Context.startService(Intent)}. The
397 * service will not receive a {@link #onStartCommand(Intent, int, int)}
kopriva762a08f2018-10-03 16:09:03 -0700398 * call with a null Intent because it will not be restarted if there
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700399 * are no pending Intents to deliver.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700400 *
401 * <p>This mode makes sense for things that want to do some work as a
402 * result of being started, but can be stopped when under memory pressure
403 * and will explicit start themselves again later to do more work. An
404 * example of such a service would be one that polls for data from
405 * a server: it could schedule an alarm to poll every N minutes by having
406 * the alarm start its service. When its {@link #onStartCommand} is
407 * called from the alarm, it schedules a new alarm for N minutes later,
408 * and spawns a thread to do its networking. If its process is killed
409 * while doing that check, the service will not be restarted until the
410 * alarm goes off.
411 */
412 public static final int START_NOT_STICKY = 2;
Dianne Hackborn67324c92016-04-18 13:55:25 -0700413
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700414 /**
415 * Constant to return from {@link #onStartCommand}: if this service's
416 * process is killed while it is started (after returning from
417 * {@link #onStartCommand}), then it will be scheduled for a restart
418 * and the last delivered Intent re-delivered to it again via
419 * {@link #onStartCommand}. This Intent will remain scheduled for
420 * redelivery until the service calls {@link #stopSelf(int)} with the
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700421 * start ID provided to {@link #onStartCommand}. The
422 * service will not receive a {@link #onStartCommand(Intent, int, int)}
kopriva762a08f2018-10-03 16:09:03 -0700423 * call with a null Intent because it will only be restarted if
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700424 * it is not finished processing all Intents sent to it (and any such
425 * pending events will be delivered at the point of restart).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700426 */
427 public static final int START_REDELIVER_INTENT = 3;
Dianne Hackborn67324c92016-04-18 13:55:25 -0700428
429 /** @hide */
Jeff Sharkey6503bd82017-04-19 23:24:18 -0600430 @IntDef(flag = false, prefix = { "START_" }, value = {
431 START_STICKY_COMPATIBILITY,
432 START_STICKY,
433 START_NOT_STICKY,
434 START_REDELIVER_INTENT,
435 })
Dianne Hackborn67324c92016-04-18 13:55:25 -0700436 @Retention(RetentionPolicy.SOURCE)
437 public @interface StartResult {}
438
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700439 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700440 * Special constant for reporting that we are done processing
441 * {@link #onTaskRemoved(Intent)}.
442 * @hide
443 */
444 public static final int START_TASK_REMOVED_COMPLETE = 1000;
445
446 /**
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700447 * This flag is set in {@link #onStartCommand} if the Intent is a
448 * re-delivery of a previously delivered intent, because the service
449 * had previously returned {@link #START_REDELIVER_INTENT} but had been
450 * killed before calling {@link #stopSelf(int)} for that Intent.
451 */
452 public static final int START_FLAG_REDELIVERY = 0x0001;
453
454 /**
455 * This flag is set in {@link #onStartCommand} if the Intent is a
Evan Charltonb8d07172014-07-31 09:09:54 -0700456 * retry because the original attempt never got to or returned from
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700457 * {@link #onStartCommand(Intent, int, int)}.
458 */
459 public static final int START_FLAG_RETRY = 0x0002;
Dianne Hackborn67324c92016-04-18 13:55:25 -0700460
461 /** @hide */
Jeff Sharkey6503bd82017-04-19 23:24:18 -0600462 @IntDef(flag = true, prefix = { "START_FLAG_" }, value = {
463 START_FLAG_REDELIVERY,
464 START_FLAG_RETRY,
465 })
Dianne Hackborn67324c92016-04-18 13:55:25 -0700466 @Retention(RetentionPolicy.SOURCE)
467 public @interface StartArgFlags {}
468
469
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700470 /**
471 * Called by the system every time a client explicitly starts the service by calling
472 * {@link android.content.Context#startService}, providing the arguments it supplied and a
473 * unique integer token representing the start request. Do not call this method directly.
474 *
475 * <p>For backwards compatibility, the default implementation calls
476 * {@link #onStart} and returns either {@link #START_STICKY}
477 * or {@link #START_STICKY_COMPATIBILITY}.
478 *
Brad Fitzpatrick0166c352010-07-27 14:37:02 -0700479 * <p class="caution">Note that the system calls this on your
480 * service's main thread. A service's main thread is the same
Brad Fitzpatrickee34a492010-08-02 07:54:18 -0700481 * thread where UI operations take place for Activities running in the
Brad Fitzpatrick0166c352010-07-27 14:37:02 -0700482 * same process. You should always avoid stalling the main
483 * thread's event loop. When doing long-running operations,
484 * network calls, or heavy disk I/O, you should kick off a new
485 * thread, or use {@link android.os.AsyncTask}.</p>
486 *
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700487 * @param intent The Intent supplied to {@link android.content.Context#startService},
488 * as given. This may be null if the service is being restarted after
489 * its process has gone away, and it had previously returned anything
490 * except {@link #START_STICKY_COMPATIBILITY}.
Jeff Sharkey6503bd82017-04-19 23:24:18 -0600491 * @param flags Additional data about this start request.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700492 * @param startId A unique integer representing this specific request to
493 * start. Use with {@link #stopSelfResult(int)}.
494 *
495 * @return The return value indicates what semantics the system should
496 * use for the service's current started state. It may be one of the
497 * constants associated with the {@link #START_CONTINUATION_MASK} bits.
498 *
499 * @see #stopSelfResult(int)
500 */
Dianne Hackborn67324c92016-04-18 13:55:25 -0700501 public @StartResult int onStartCommand(Intent intent, @StartArgFlags int flags, int startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700502 onStart(intent, startId);
503 return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
504 }
505
506 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 * Called by the system to notify a Service that it is no longer used and is being removed. The
Ken Wakasaf76a50c2012-03-09 19:56:35 +0900508 * service should clean up any resources it holds (threads, registered
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 * receivers, etc) at this point. Upon return, there will be no more calls
510 * in to this Service object and it is effectively dead. Do not call this method directly.
511 */
512 public void onDestroy() {
513 }
514
515 public void onConfigurationChanged(Configuration newConfig) {
516 }
517
518 public void onLowMemory() {
519 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700520
521 public void onTrimMemory(int level) {
522 }
523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 /**
525 * Return the communication channel to the service. May return null if
526 * clients can not bind to the service. The returned
527 * {@link android.os.IBinder} is usually for a complex interface
Scott Main40eee612012-08-06 17:48:37 -0700528 * that has been <a href="{@docRoot}guide/components/aidl.html">described using
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 * aidl</a>.
530 *
531 * <p><em>Note that unlike other application components, calls on to the
532 * IBinder interface returned here may not happen on the main thread
Scott Main7aee61f2011-02-08 11:25:01 -0800533 * of the process</em>. More information about the main thread can be found in
534 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
535 * Threads</a>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 *
537 * @param intent The Intent that was used to bind to this service,
538 * as given to {@link android.content.Context#bindService
539 * Context.bindService}. Note that any extras that were included with
540 * the Intent at that point will <em>not</em> be seen here.
541 *
542 * @return Return an IBinder through which clients can call on to the
543 * service.
544 */
Scott Kennedy7db73ed2015-02-19 15:31:11 -0800545 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 public abstract IBinder onBind(Intent intent);
547
548 /**
549 * Called when all clients have disconnected from a particular interface
550 * published by the service. The default implementation does nothing and
551 * returns false.
552 *
553 * @param intent The Intent that was used to bind to this service,
554 * as given to {@link android.content.Context#bindService
555 * Context.bindService}. Note that any extras that were included with
556 * the Intent at that point will <em>not</em> be seen here.
557 *
558 * @return Return true if you would like to have the service's
559 * {@link #onRebind} method later called when new clients bind to it.
560 */
561 public boolean onUnbind(Intent intent) {
562 return false;
563 }
564
565 /**
566 * Called when new clients have connected to the service, after it had
567 * previously been notified that all had disconnected in its
568 * {@link #onUnbind}. This will only be called if the implementation
569 * of {@link #onUnbind} was overridden to return true.
570 *
571 * @param intent The Intent that was used to bind to this service,
572 * as given to {@link android.content.Context#bindService
573 * Context.bindService}. Note that any extras that were included with
574 * the Intent at that point will <em>not</em> be seen here.
575 */
576 public void onRebind(Intent intent) {
577 }
578
579 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700580 * This is called if the service is currently running and the user has
581 * removed a task that comes from the service's application. If you have
582 * set {@link android.content.pm.ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
583 * then you will not receive this callback; instead, the service will simply
584 * be stopped.
585 *
586 * @param rootIntent The original root Intent that was used to launch
587 * the task that is being removed.
588 */
589 public void onTaskRemoved(Intent rootIntent) {
590 }
591
592 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 * Stop the service, if it was previously started. This is the same as
594 * calling {@link android.content.Context#stopService} for this particular service.
595 *
596 * @see #stopSelfResult(int)
597 */
598 public final void stopSelf() {
599 stopSelf(-1);
600 }
601
602 /**
603 * Old version of {@link #stopSelfResult} that doesn't return a result.
604 *
605 * @see #stopSelfResult
606 */
607 public final void stopSelf(int startId) {
608 if (mActivityManager == null) {
609 return;
610 }
611 try {
612 mActivityManager.stopServiceToken(
613 new ComponentName(this, mClassName), mToken, startId);
614 } catch (RemoteException ex) {
615 }
616 }
617
618 /**
The Android Open Source Project10592532009-03-18 17:39:46 -0700619 * Stop the service if the most recent time it was started was
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * <var>startId</var>. This is the same as calling {@link
621 * android.content.Context#stopService} for this particular service but allows you to
622 * safely avoid stopping if there is a start request from a client that you
The Android Open Source Project10592532009-03-18 17:39:46 -0700623 * haven't yet seen in {@link #onStart}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 *
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700625 * <p><em>Be careful about ordering of your calls to this function.</em>.
626 * If you call this function with the most-recently received ID before
627 * you have called it for previously received IDs, the service will be
628 * immediately stopped anyway. If you may end up processing IDs out
629 * of order (such as by dispatching them on separate threads), then you
630 * are responsible for stopping them in the same order you received them.</p>
631 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 * @param startId The most recent start identifier received in {@link
633 * #onStart}.
634 * @return Returns true if the startId matches the last start request
635 * and the service will be stopped, else false.
636 *
637 * @see #stopSelf()
638 */
639 public final boolean stopSelfResult(int startId) {
640 if (mActivityManager == null) {
641 return false;
642 }
643 try {
644 return mActivityManager.stopServiceToken(
645 new ComponentName(this, mClassName), mToken, startId);
646 } catch (RemoteException ex) {
647 }
648 return false;
649 }
650
651 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700652 * @deprecated This is a now a no-op, use
Dianne Hackborn29e4a3c2009-09-30 22:35:40 -0700653 * {@link #startForeground(int, Notification)} instead. This method
654 * has been turned into a no-op rather than simply being deprecated
655 * because analysis of numerous poorly behaving devices has shown that
656 * increasingly often the trouble is being caused in part by applications
657 * that are abusing it. Thus, given a choice between introducing
658 * problems in existing applications using this API (by allowing them to
659 * be killed when they would like to avoid it), vs allowing the performance
660 * of the entire system to be decreased, this method was deemed less
661 * important.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -0800662 *
663 * @hide
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700664 */
665 @Deprecated
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100666 @UnsupportedAppUsage
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700667 public final void setForeground(boolean isForeground) {
668 Log.w(TAG, "setForeground: ignoring old API call on " + getClass().getName());
669 }
670
671 /**
Dianne Hackborn4ae51e02017-05-04 16:53:11 -0700672 * If your service is started (running through {@link Context#startService(Intent)}), then
673 * also make this service run in the foreground, supplying the ongoing
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700674 * notification to be shown to the user while in this state.
Dianne Hackborn4ae51e02017-05-04 16:53:11 -0700675 * By default started services are background, meaning that their process won't be given
676 * foreground CPU scheduling (unless something else in that process is foreground) and,
677 * if the system needs to kill them to reclaim more memory (such as to display a large page in a
678 * web browser), they can be killed without too much harm. You use
679 * {@link #startForeground} if killing your service would be disruptive to the user, such as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 * if your service is performing background music playback, so the user
681 * would notice if their music stopped playing.
Dianne Hackborn4ae51e02017-05-04 16:53:11 -0700682 *
683 * <p>Note that calling this method does <em>not</em> put the service in the started state
684 * itself, even though the name sounds like it. You must always call
685 * {@link #startService(Intent)} first to tell the system it should keep the service running,
686 * and then use this method to tell it to keep it running harder.</p>
687 *
Dianne Hackborndd027b32018-01-19 17:44:46 -0800688 * <p>Apps targeting API {@link android.os.Build.VERSION_CODES#P} or later must request
689 * the permission {@link android.Manifest.permission#FOREGROUND_SERVICE} in order to use
690 * this API.</p>
691 *
Hui Yu2d4207f2019-01-22 15:32:20 -0800692 * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
693 * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
694 * service element of manifest file. The value of attribute
695 * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
Hui Yu1ea85522018-12-06 16:59:18 -0800696 *
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700697 * @param id The identifier for this notification as per
698 * {@link NotificationManager#notify(int, Notification)
Scott Main2e6de8f2013-04-30 10:51:12 -0700699 * NotificationManager.notify(int, Notification)}; must not be 0.
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700700 * @param notification The Notification to be displayed.
Sudheer Shankac9d94072017-02-22 22:13:55 +0000701 *
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700702 * @see #stopForeground(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 */
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700704 public final void startForeground(int id, Notification notification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 try {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000706 mActivityManager.setServiceForeground(
707 new ComponentName(this, mClassName), mToken, id,
Hui Yu2d4207f2019-01-22 15:32:20 -0800708 notification, 0, FOREGROUND_SERVICE_TYPE_MANIFEST);
709 } catch (RemoteException ex) {
710 }
711 }
712
713 /**
714 * An overloaded version of {@link #startForeground(int, Notification)} with additional
715 * foregroundServiceType parameter.
716 *
717 * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
718 * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
719 * service element of manifest file. The value of attribute
720 * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
721 *
722 * <p>The foregroundServiceType parameter must be a subset flags of what is specified in manifest
723 * attribute {@link android.R.attr#foregroundServiceType}, if not, an IllegalArgumentException is
724 * thrown. Specify foregroundServiceType parameter as
725 * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST} to use all flags that
726 * is specified in manifest attribute foregroundServiceType.</p>
727 *
728 * @param id The identifier for this notification as per
729 * {@link NotificationManager#notify(int, Notification)
730 * NotificationManager.notify(int, Notification)}; must not be 0.
731 * @param notification The Notification to be displayed.
732 * @param foregroundServiceType must be a subset flags of manifest attribute
733 * {@link android.R.attr#foregroundServiceType} flags.
734 * @throws IllegalArgumentException if param foregroundServiceType is not subset of manifest
735 * attribute {@link android.R.attr#foregroundServiceType}.
736 * @see {@link android.content.pm.ServiceInfo} for the set of FOREGROUND_SERVICE_TYPE flags.
737 */
738 public final void startForeground(int id, @NonNull Notification notification,
Hui Yub8dcbee2019-02-14 13:50:01 -0800739 @ForegroundServiceType int foregroundServiceType) {
Hui Yu2d4207f2019-01-22 15:32:20 -0800740 try {
741 mActivityManager.setServiceForeground(
742 new ComponentName(this, mClassName), mToken, id,
743 notification, 0, foregroundServiceType);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700744 } catch (RemoteException ex) {
745 }
746 }
Hui Yu1ea85522018-12-06 16:59:18 -0800747
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700748 /**
Dianne Hackborn67324c92016-04-18 13:55:25 -0700749 * Synonym for {@link #stopForeground(int)}.
750 * @param removeNotification If true, the {@link #STOP_FOREGROUND_REMOVE} flag
751 * will be supplied.
752 * @see #stopForeground(int)
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700753 * @see #startForeground(int, Notification)
754 */
755 public final void stopForeground(boolean removeNotification) {
Dianne Hackborn67324c92016-04-18 13:55:25 -0700756 stopForeground(removeNotification ? STOP_FOREGROUND_REMOVE : 0);
757 }
758
759 /**
760 * Remove this service from foreground state, allowing it to be killed if
Dianne Hackborn4ae51e02017-05-04 16:53:11 -0700761 * more memory is needed. This does not stop the service from running (for that
762 * you use {@link #stopSelf()} or related methods), just takes it out of the
763 * foreground state.
Jeff Sharkey6503bd82017-04-19 23:24:18 -0600764 *
765 * @param flags additional behavior options.
Dianne Hackborn67324c92016-04-18 13:55:25 -0700766 * @see #startForeground(int, Notification)
767 */
768 public final void stopForeground(@StopForegroundFlags int flags) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -0700769 try {
770 mActivityManager.setServiceForeground(
Hui Yu2d4207f2019-01-22 15:32:20 -0800771 new ComponentName(this, mClassName), mToken, 0, null,
772 flags, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 } catch (RemoteException ex) {
774 }
775 }
Dianne Hackborn67324c92016-04-18 13:55:25 -0700776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 /**
778 * Print the Service's state into the given stream. This gets invoked if
kmccormickf6dc1072013-03-29 16:00:50 -0700779 * you run "adb shell dumpsys activity service &lt;yourservicename&gt;"
780 * (note that for this command to work, the service must be running, and
781 * you must specify a fully-qualified service name).
Jeff Sharkey5554b702012-04-11 18:30:51 -0700782 * This is distinct from "dumpsys &lt;servicename&gt;", which only works for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 * named system services and which invokes the {@link IBinder#dump} method
784 * on the {@link IBinder} interface registered with ServiceManager.
785 *
786 * @param fd The raw file descriptor that the dump is being sent to.
787 * @param writer The PrintWriter to which you should dump your state. This will be
788 * closed for you after you return.
789 * @param args additional arguments to the dump request.
790 */
791 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
792 writer.println("nothing to dump");
793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794
795 // ------------------ Internal API ------------------
796
797 /**
798 * @hide
799 */
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100800 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 public final void attach(
802 Context context,
803 ActivityThread thread, String className, IBinder token,
804 Application application, Object activityManager) {
805 attachBaseContext(context);
806 mThread = thread; // NOTE: unused - remove?
807 mClassName = className;
808 mToken = token;
809 mApplication = application;
810 mActivityManager = (IActivityManager)activityManager;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700811 mStartCompatibility = getApplicationInfo().targetSdkVersion
812 < Build.VERSION_CODES.ECLAIR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 }
Amith Yamasani75928252017-05-22 15:10:47 -0700814
815 /**
816 * @hide
817 * Clean up any references to avoid leaks.
818 */
819 public final void detachAndCleanUp() {
820 mToken = null;
821 }
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 final String getClassName() {
824 return mClassName;
825 }
826
827 // set by the thread after the constructor and before onCreate(Bundle icicle) is called.
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100828 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 private ActivityThread mThread = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100830 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 private String mClassName = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100832 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 private IBinder mToken = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100834 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 private Application mApplication = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100836 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 private IActivityManager mActivityManager = null;
Mathew Inwood4fb17d12018-08-14 14:25:44 +0100838 @UnsupportedAppUsage
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -0700839 private boolean mStartCompatibility = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840}