1 /*
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 
17 package android.app;
18 
19 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
20 
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.content.ComponentCallbacks2;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.ContextWrapper;
29 import android.content.Intent;
30 import android.content.pm.ServiceInfo;
31 import android.content.pm.ServiceInfo.ForegroundServiceType;
32 import android.content.res.Configuration;
33 import android.os.Build;
34 import android.os.IBinder;
35 import android.os.RemoteException;
36 import android.util.Log;
37 
38 import java.io.FileDescriptor;
39 import java.io.PrintWriter;
40 import java.lang.annotation.Retention;
41 import java.lang.annotation.RetentionPolicy;
42 
43 /**
44  * A Service is an application component representing either an application's desire
45  * to perform a longer-running operation while not interacting with the user
46  * or to supply functionality for other applications to use.  Each service
47  * class must have a corresponding
48  * {@link android.R.styleable#AndroidManifestService <service>}
49  * declaration in its package's <code>AndroidManifest.xml</code>.  Services
50  * can be started with
51  * {@link android.content.Context#startService Context.startService()} and
52  * {@link android.content.Context#bindService Context.bindService()}.
53  *
54  * <p>Note that services, like other application objects, run in the main
55  * thread of their hosting process.  This means that, if your service is going
56  * to do any CPU intensive (such as MP3 playback) or blocking (such as
57  * networking) operations, it should spawn its own thread in which to do that
58  * work.  More information on this can be found in
59  * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
60  * Threads</a>.  The {@link androidx.core.app.JobIntentService} class is available
61  * as a standard implementation of Service that has its own thread where it
62  * schedules its work to be done.</p>
63  *
64  * <p>Topics covered here:
65  * <ol>
66  * <li><a href="#WhatIsAService">What is a Service?</a>
67  * <li><a href="#ServiceLifecycle">Service Lifecycle</a>
68  * <li><a href="#Permissions">Permissions</a>
69  * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
70  * <li><a href="#LocalServiceSample">Local Service Sample</a>
71  * <li><a href="#RemoteMessengerServiceSample">Remote Messenger Service Sample</a>
72  * </ol>
73  *
74  * <div class="special reference">
75  * <h3>Developer Guides</h3>
76  * <p>For a detailed discussion about how to create services, read the
77  * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
78  * </div>
79  *
80  * <a name="WhatIsAService"></a>
81  * <h3>What is a Service?</h3>
82  *
83  * <p>Most confusion about the Service class actually revolves around what
84  * it is <em>not</em>:</p>
85  *
86  * <ul>
87  * <li> A Service is <b>not</b> a separate process.  The Service object itself
88  * does not imply it is running in its own process; unless otherwise specified,
89  * it runs in the same process as the application it is part of.
90  * <li> A Service is <b>not</b> a thread.  It is not a means itself to do work off
91  * of the main thread (to avoid Application Not Responding errors).
92  * </ul>
93  *
94  * <p>Thus a Service itself is actually very simple, providing two main features:</p>
95  *
96  * <ul>
97  * <li>A facility for the application to tell the system <em>about</em>
98  * something it wants to be doing in the background (even when the user is not
99  * directly interacting with the application).  This corresponds to calls to
100  * {@link android.content.Context#startService Context.startService()}, which
101  * ask the system to schedule work for the service, to be run until the service
102  * or someone else explicitly stop it.
103  * <li>A facility for an application to expose some of its functionality to
104  * other applications.  This corresponds to calls to
105  * {@link android.content.Context#bindService Context.bindService()}, which
106  * allows a long-standing connection to be made to the service in order to
107  * interact with it.
108  * </ul>
109  *
110  * <p>When a Service component is actually created, for either of these reasons,
111  * all that the system actually does is instantiate the component
112  * and call its {@link #onCreate} and any other appropriate callbacks on the
113  * main thread.  It is up to the Service to implement these with the appropriate
114  * behavior, such as creating a secondary thread in which it does its work.</p>
115  *
116  * <p>Note that because Service itself is so simple, you can make your
117  * interaction with it as simple or complicated as you want: from treating it
118  * as a local Java object that you make direct method calls on (as illustrated
119  * by <a href="#LocalServiceSample">Local Service Sample</a>), to providing
120  * a full remoteable interface using AIDL.</p>
121  *
122  * <a name="ServiceLifecycle"></a>
123  * <h3>Service Lifecycle</h3>
124  *
125  * <p>There are two reasons that a service can be run by the system.  If someone
126  * calls {@link android.content.Context#startService Context.startService()} then the system will
127  * retrieve the service (creating it and calling its {@link #onCreate} method
128  * if needed) and then call its {@link #onStartCommand} method with the
129  * arguments supplied by the client.  The service will at this point continue
130  * running until {@link android.content.Context#stopService Context.stopService()} or
131  * {@link #stopSelf()} is called.  Note that multiple calls to
132  * Context.startService() do not nest (though they do result in multiple corresponding
133  * calls to onStartCommand()), so no matter how many times it is started a service
134  * will be stopped once Context.stopService() or stopSelf() is called; however,
135  * services can use their {@link #stopSelf(int)} method to ensure the service is
136  * not stopped until started intents have been processed.
137  *
138  * <p>For started services, there are two additional major modes of operation
139  * they can decide to run in, depending on the value they return from
140  * onStartCommand(): {@link #START_STICKY} is used for services that are
141  * explicitly started and stopped as needed, while {@link #START_NOT_STICKY}
142  * or {@link #START_REDELIVER_INTENT} are used for services that should only
143  * remain running while processing any commands sent to them.  See the linked
144  * documentation for more detail on the semantics.
145  *
146  * <p>Clients can also use {@link android.content.Context#bindService Context.bindService()} to
147  * obtain a persistent connection to a service.  This likewise creates the
148  * service if it is not already running (calling {@link #onCreate} while
149  * doing so), but does not call onStartCommand().  The client will receive the
150  * {@link android.os.IBinder} object that the service returns from its
151  * {@link #onBind} method, allowing the client to then make calls back
152  * to the service.  The service will remain running as long as the connection
153  * is established (whether or not the client retains a reference on the
154  * service's IBinder).  Usually the IBinder returned is for a complex
155  * interface that has been <a href="{@docRoot}guide/components/aidl.html">written
156  * in aidl</a>.
157  *
158  * <p>A service can be both started and have connections bound to it.  In such
159  * a case, the system will keep the service running as long as either it is
160  * started <em>or</em> there are one or more connections to it with the
161  * {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE}
162  * flag.  Once neither
163  * of these situations hold, the service's {@link #onDestroy} method is called
164  * and the service is effectively terminated.  All cleanup (stopping threads,
165  * unregistering receivers) should be complete upon returning from onDestroy().
166  *
167  * <a name="Permissions"></a>
168  * <h3>Permissions</h3>
169  *
170  * <p>Global access to a service can be enforced when it is declared in its
171  * manifest's {@link android.R.styleable#AndroidManifestService &lt;service&gt;}
172  * tag.  By doing so, other applications will need to declare a corresponding
173  * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
174  * element in their own manifest to be able to start, stop, or bind to
175  * the service.
176  *
177  * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, when using
178  * {@link Context#startService(Intent) Context.startService(Intent)}, you can
179  * also set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
180  * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
181  * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent.  This will grant the
182  * Service temporary access to the specific URIs in the Intent.  Access will
183  * remain until the Service has called {@link #stopSelf(int)} for that start
184  * command or a later one, or until the Service has been completely stopped.
185  * This works for granting access to the other apps that have not requested
186  * the permission protecting the Service, or even when the Service is not
187  * exported at all.
188  *
189  * <p>In addition, a service can protect individual IPC calls into it with
190  * permissions, by calling the
191  * {@link #checkCallingPermission}
192  * method before executing the implementation of that call.
193  *
194  * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
195  * document for more information on permissions and security in general.
196  *
197  * <a name="ProcessLifecycle"></a>
198  * <h3>Process Lifecycle</h3>
199  *
200  * <p>The Android system will attempt to keep the process hosting a service
201  * around as long as the service has been started or has clients bound to it.
202  * When running low on memory and needing to kill existing processes, the
203  * priority of a process hosting the service will be the higher of the
204  * following possibilities:
205  *
206  * <ul>
207  * <li><p>If the service is currently executing code in its
208  * {@link #onCreate onCreate()}, {@link #onStartCommand onStartCommand()},
209  * or {@link #onDestroy onDestroy()} methods, then the hosting process will
210  * be a foreground process to ensure this code can execute without
211  * being killed.
212  * <li><p>If the service has been started, then its hosting process is considered
213  * to be less important than any processes that are currently visible to the
214  * user on-screen, but more important than any process not visible.  Because
215  * only a few processes are generally visible to the user, this means that
216  * the service should not be killed except in low memory conditions.  However, since
217  * the user is not directly aware of a background service, in that state it <em>is</em>
218  * considered a valid candidate to kill, and you should be prepared for this to
219  * happen.  In particular, long-running services will be increasingly likely to
220  * kill and are guaranteed to be killed (and restarted if appropriate) if they
221  * remain started long enough.
222  * <li><p>If there are clients bound to the service, then the service's hosting
223  * process is never less important than the most important client.  That is,
224  * if one of its clients is visible to the user, then the service itself is
225  * considered to be visible.  The way a client's importance impacts the service's
226  * importance can be adjusted through {@link Context#BIND_ABOVE_CLIENT},
227  * {@link Context#BIND_ALLOW_OOM_MANAGEMENT}, {@link Context#BIND_WAIVE_PRIORITY},
228  * {@link Context#BIND_IMPORTANT}, and {@link Context#BIND_ADJUST_WITH_ACTIVITY}.
229  * <li><p>A started service can use the {@link #startForeground(int, Notification)}
230  * API to put the service in a foreground state, where the system considers
231  * it to be something the user is actively aware of and thus not a candidate
232  * for killing when low on memory.  (It is still theoretically possible for
233  * the service to be killed under extreme memory pressure from the current
234  * foreground application, but in practice this should not be a concern.)
235  * </ul>
236  *
237  * <p>Note this means that most of the time your service is running, it may
238  * be killed by the system if it is under heavy memory pressure.  If this
239  * happens, the system will later try to restart the service.  An important
240  * consequence of this is that if you implement {@link #onStartCommand onStartCommand()}
241  * to schedule work to be done asynchronously or in another thread, then you
242  * may want to use {@link #START_FLAG_REDELIVERY} to have the system
243  * re-deliver an Intent for you so that it does not get lost if your service
244  * is killed while processing it.
245  *
246  * <p>Other application components running in the same process as the service
247  * (such as an {@link android.app.Activity}) can, of course, increase the
248  * importance of the overall
249  * process beyond just the importance of the service itself.
250  *
251  * <a name="LocalServiceSample"></a>
252  * <h3>Local Service Sample</h3>
253  *
254  * <p>One of the most common uses of a Service is as a secondary component
255  * running alongside other parts of an application, in the same process as
256  * the rest of the components.  All components of an .apk run in the same
257  * process unless explicitly stated otherwise, so this is a typical situation.
258  *
259  * <p>When used in this way, by assuming the
260  * components are in the same process, you can greatly simplify the interaction
261  * between them: clients of the service can simply cast the IBinder they
262  * receive from it to a concrete class published by the service.
263  *
264  * <p>An example of this use of a Service is shown here.  First is the Service
265  * itself, publishing a custom class when bound:
266  *
267  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalService.java
268  *      service}
269  *
270  * <p>With that done, one can now write client code that directly accesses the
271  * running service, such as:
272  *
273  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.java
274  *      bind}
275  *
276  * <a name="RemoteMessengerServiceSample"></a>
277  * <h3>Remote Messenger Service Sample</h3>
278  *
279  * <p>If you need to be able to write a Service that can perform complicated
280  * communication with clients in remote processes (beyond simply the use of
281  * {@link Context#startService(Intent) Context.startService} to send
282  * commands to it), then you can use the {@link android.os.Messenger} class
283  * instead of writing full AIDL files.
284  *
285  * <p>An example of a Service that uses Messenger as its client interface
286  * is shown here.  First is the Service itself, publishing a Messenger to
287  * an internal Handler when bound:
288  *
289  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.java
290  *      service}
291  *
292  * <p>If we want to make this service run in a remote process (instead of the
293  * standard one for its .apk), we can use <code>android:process</code> in its
294  * manifest tag to specify one:
295  *
296  * {@sample development/samples/ApiDemos/AndroidManifest.xml remote_service_declaration}
297  *
298  * <p>Note that the name "remote" chosen here is arbitrary, and you can use
299  * other names if you want additional processes.  The ':' prefix appends the
300  * name to your package's standard process name.
301  *
302  * <p>With that done, clients can now bind to the service and send messages
303  * to it.  Note that this allows clients to register with it to receive
304  * messages back as well:
305  *
306  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java
307  *      bind}
308  */
309 public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
310     private static final String TAG = "Service";
311 
312     /**
313      * Flag for {@link #stopForeground(int)}: if set, the notification previously provided
314      * to {@link #startForeground} will be removed.  Otherwise it will remain
315      * until a later call (to {@link #startForeground(int, Notification)} or
316      * {@link #stopForeground(int)} removes it, or the service is destroyed.
317      */
318     public static final int STOP_FOREGROUND_REMOVE = 1<<0;
319 
320     /**
321      * Flag for {@link #stopForeground(int)}: if set, the notification previously provided
322      * to {@link #startForeground} will be detached from the service.  Only makes sense
323      * when {@link #STOP_FOREGROUND_REMOVE} is <b>not</b> set -- in this case, the notification
324      * will remain shown, but be completely detached from the service and so no longer changed
325      * except through direct calls to the notification manager.
326      */
327     public static final int STOP_FOREGROUND_DETACH = 1<<1;
328 
329     /** @hide */
330     @IntDef(flag = true, prefix = { "STOP_FOREGROUND_" }, value = {
331             STOP_FOREGROUND_REMOVE,
332             STOP_FOREGROUND_DETACH
333     })
334     @Retention(RetentionPolicy.SOURCE)
335     public @interface StopForegroundFlags {}
336 
Service()337     public Service() {
338         super(null);
339     }
340 
341     /** Return the application that owns this service. */
getApplication()342     public final Application getApplication() {
343         return mApplication;
344     }
345 
346     /**
347      * Called by the system when the service is first created.  Do not call this method directly.
348      */
onCreate()349     public void onCreate() {
350     }
351 
352     /**
353      * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
354      */
355     @Deprecated
onStart(Intent intent, int startId)356     public void onStart(Intent intent, int startId) {
357     }
358 
359     /**
360      * Bits returned by {@link #onStartCommand} describing how to continue
361      * the service if it is killed.  May be {@link #START_STICKY},
362      * {@link #START_NOT_STICKY}, {@link #START_REDELIVER_INTENT},
363      * or {@link #START_STICKY_COMPATIBILITY}.
364      */
365     public static final int START_CONTINUATION_MASK = 0xf;
366 
367     /**
368      * Constant to return from {@link #onStartCommand}: compatibility
369      * version of {@link #START_STICKY} that does not guarantee that
370      * {@link #onStartCommand} will be called again after being killed.
371      */
372     public static final int START_STICKY_COMPATIBILITY = 0;
373 
374     /**
375      * Constant to return from {@link #onStartCommand}: if this service's
376      * process is killed while it is started (after returning from
377      * {@link #onStartCommand}), then leave it in the started state but
378      * don't retain this delivered intent.  Later the system will try to
379      * re-create the service.  Because it is in the started state, it will
380      * guarantee to call {@link #onStartCommand} after creating the new
381      * service instance; if there are not any pending start commands to be
382      * delivered to the service, it will be called with a null intent
383      * object, so you must take care to check for this.
384      *
385      * <p>This mode makes sense for things that will be explicitly started
386      * and stopped to run for arbitrary periods of time, such as a service
387      * performing background music playback.
388      */
389     public static final int START_STICKY = 1;
390 
391     /**
392      * Constant to return from {@link #onStartCommand}: if this service's
393      * process is killed while it is started (after returning from
394      * {@link #onStartCommand}), and there are no new start intents to
395      * deliver to it, then take the service out of the started state and
396      * don't recreate until a future explicit call to
397      * {@link Context#startService Context.startService(Intent)}.  The
398      * service will not receive a {@link #onStartCommand(Intent, int, int)}
399      * call with a null Intent because it will not be restarted if there
400      * are no pending Intents to deliver.
401      *
402      * <p>This mode makes sense for things that want to do some work as a
403      * result of being started, but can be stopped when under memory pressure
404      * and will explicit start themselves again later to do more work.  An
405      * example of such a service would be one that polls for data from
406      * a server: it could schedule an alarm to poll every N minutes by having
407      * the alarm start its service.  When its {@link #onStartCommand} is
408      * called from the alarm, it schedules a new alarm for N minutes later,
409      * and spawns a thread to do its networking.  If its process is killed
410      * while doing that check, the service will not be restarted until the
411      * alarm goes off.
412      */
413     public static final int START_NOT_STICKY = 2;
414 
415     /**
416      * Constant to return from {@link #onStartCommand}: if this service's
417      * process is killed while it is started (after returning from
418      * {@link #onStartCommand}), then it will be scheduled for a restart
419      * and the last delivered Intent re-delivered to it again via
420      * {@link #onStartCommand}.  This Intent will remain scheduled for
421      * redelivery until the service calls {@link #stopSelf(int)} with the
422      * start ID provided to {@link #onStartCommand}.  The
423      * service will not receive a {@link #onStartCommand(Intent, int, int)}
424      * call with a null Intent because it will only be restarted if
425      * it is not finished processing all Intents sent to it (and any such
426      * pending events will be delivered at the point of restart).
427      */
428     public static final int START_REDELIVER_INTENT = 3;
429 
430     /** @hide */
431     @IntDef(flag = false, prefix = { "START_" }, value = {
432             START_STICKY_COMPATIBILITY,
433             START_STICKY,
434             START_NOT_STICKY,
435             START_REDELIVER_INTENT,
436     })
437     @Retention(RetentionPolicy.SOURCE)
438     public @interface StartResult {}
439 
440     /**
441      * Special constant for reporting that we are done processing
442      * {@link #onTaskRemoved(Intent)}.
443      * @hide
444      */
445     public static final int START_TASK_REMOVED_COMPLETE = 1000;
446 
447     /**
448      * This flag is set in {@link #onStartCommand} if the Intent is a
449      * re-delivery of a previously delivered intent, because the service
450      * had previously returned {@link #START_REDELIVER_INTENT} but had been
451      * killed before calling {@link #stopSelf(int)} for that Intent.
452      */
453     public static final int START_FLAG_REDELIVERY = 0x0001;
454 
455     /**
456      * This flag is set in {@link #onStartCommand} if the Intent is a
457      * retry because the original attempt never got to or returned from
458      * {@link #onStartCommand(Intent, int, int)}.
459      */
460     public static final int START_FLAG_RETRY = 0x0002;
461 
462     /** @hide */
463     @IntDef(flag = true, prefix = { "START_FLAG_" }, value = {
464             START_FLAG_REDELIVERY,
465             START_FLAG_RETRY,
466     })
467     @Retention(RetentionPolicy.SOURCE)
468     public @interface StartArgFlags {}
469 
470 
471     /**
472      * Called by the system every time a client explicitly starts the service by calling
473      * {@link android.content.Context#startService}, providing the arguments it supplied and a
474      * unique integer token representing the start request.  Do not call this method directly.
475      *
476      * <p>For backwards compatibility, the default implementation calls
477      * {@link #onStart} and returns either {@link #START_STICKY}
478      * or {@link #START_STICKY_COMPATIBILITY}.
479      *
480      * <p class="caution">Note that the system calls this on your
481      * service's main thread.  A service's main thread is the same
482      * thread where UI operations take place for Activities running in the
483      * same process.  You should always avoid stalling the main
484      * thread's event loop.  When doing long-running operations,
485      * network calls, or heavy disk I/O, you should kick off a new
486      * thread, or use {@link android.os.AsyncTask}.</p>
487      *
488      * @param intent The Intent supplied to {@link android.content.Context#startService},
489      * as given.  This may be null if the service is being restarted after
490      * its process has gone away, and it had previously returned anything
491      * except {@link #START_STICKY_COMPATIBILITY}.
492      * @param flags Additional data about this start request.
493      * @param startId A unique integer representing this specific request to
494      * start.  Use with {@link #stopSelfResult(int)}.
495      *
496      * @return The return value indicates what semantics the system should
497      * use for the service's current started state.  It may be one of the
498      * constants associated with the {@link #START_CONTINUATION_MASK} bits.
499      *
500      * @see #stopSelfResult(int)
501      */
onStartCommand(Intent intent, @StartArgFlags int flags, int startId)502     public @StartResult int onStartCommand(Intent intent, @StartArgFlags int flags, int startId) {
503         onStart(intent, startId);
504         return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
505     }
506 
507     /**
508      * Called by the system to notify a Service that it is no longer used and is being removed.  The
509      * service should clean up any resources it holds (threads, registered
510      * receivers, etc) at this point.  Upon return, there will be no more calls
511      * in to this Service object and it is effectively dead.  Do not call this method directly.
512      */
onDestroy()513     public void onDestroy() {
514     }
515 
onConfigurationChanged(Configuration newConfig)516     public void onConfigurationChanged(Configuration newConfig) {
517     }
518 
onLowMemory()519     public void onLowMemory() {
520     }
521 
onTrimMemory(int level)522     public void onTrimMemory(int level) {
523     }
524 
525     /**
526      * Return the communication channel to the service.  May return null if
527      * clients can not bind to the service.  The returned
528      * {@link android.os.IBinder} is usually for a complex interface
529      * that has been <a href="{@docRoot}guide/components/aidl.html">described using
530      * aidl</a>.
531      *
532      * <p><em>Note that unlike other application components, calls on to the
533      * IBinder interface returned here may not happen on the main thread
534      * of the process</em>.  More information about the main thread can be found in
535      * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
536      * Threads</a>.</p>
537      *
538      * @param intent The Intent that was used to bind to this service,
539      * as given to {@link android.content.Context#bindService
540      * Context.bindService}.  Note that any extras that were included with
541      * the Intent at that point will <em>not</em> be seen here.
542      *
543      * @return Return an IBinder through which clients can call on to the
544      *         service.
545      */
546     @Nullable
onBind(Intent intent)547     public abstract IBinder onBind(Intent intent);
548 
549     /**
550      * Called when all clients have disconnected from a particular interface
551      * published by the service.  The default implementation does nothing and
552      * returns false.
553      *
554      * @param intent The Intent that was used to bind to this service,
555      * as given to {@link android.content.Context#bindService
556      * Context.bindService}.  Note that any extras that were included with
557      * the Intent at that point will <em>not</em> be seen here.
558      *
559      * @return Return true if you would like to have the service's
560      * {@link #onRebind} method later called when new clients bind to it.
561      */
onUnbind(Intent intent)562     public boolean onUnbind(Intent intent) {
563         return false;
564     }
565 
566     /**
567      * Called when new clients have connected to the service, after it had
568      * previously been notified that all had disconnected in its
569      * {@link #onUnbind}.  This will only be called if the implementation
570      * of {@link #onUnbind} was overridden to return true.
571      *
572      * @param intent The Intent that was used to bind to this service,
573      * as given to {@link android.content.Context#bindService
574      * Context.bindService}.  Note that any extras that were included with
575      * the Intent at that point will <em>not</em> be seen here.
576      */
onRebind(Intent intent)577     public void onRebind(Intent intent) {
578     }
579 
580     /**
581      * This is called if the service is currently running and the user has
582      * removed a task that comes from the service's application.  If you have
583      * set {@link android.content.pm.ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
584      * then you will not receive this callback; instead, the service will simply
585      * be stopped.
586      *
587      * @param rootIntent The original root Intent that was used to launch
588      * the task that is being removed.
589      */
onTaskRemoved(Intent rootIntent)590     public void onTaskRemoved(Intent rootIntent) {
591     }
592 
593     /**
594      * Stop the service, if it was previously started.  This is the same as
595      * calling {@link android.content.Context#stopService} for this particular service.
596      *
597      * @see #stopSelfResult(int)
598      */
stopSelf()599     public final void stopSelf() {
600         stopSelf(-1);
601     }
602 
603     /**
604      * Old version of {@link #stopSelfResult} that doesn't return a result.
605      *
606      * @see #stopSelfResult
607      */
stopSelf(int startId)608     public final void stopSelf(int startId) {
609         if (mActivityManager == null) {
610             return;
611         }
612         try {
613             mActivityManager.stopServiceToken(
614                     new ComponentName(this, mClassName), mToken, startId);
615         } catch (RemoteException ex) {
616         }
617     }
618 
619     /**
620      * Stop the service if the most recent time it was started was
621      * <var>startId</var>.  This is the same as calling {@link
622      * android.content.Context#stopService} for this particular service but allows you to
623      * safely avoid stopping if there is a start request from a client that you
624      * haven't yet seen in {@link #onStart}.
625      *
626      * <p><em>Be careful about ordering of your calls to this function.</em>.
627      * If you call this function with the most-recently received ID before
628      * you have called it for previously received IDs, the service will be
629      * immediately stopped anyway.  If you may end up processing IDs out
630      * of order (such as by dispatching them on separate threads), then you
631      * are responsible for stopping them in the same order you received them.</p>
632      *
633      * @param startId The most recent start identifier received in {@link
634      *                #onStart}.
635      * @return Returns true if the startId matches the last start request
636      * and the service will be stopped, else false.
637      *
638      * @see #stopSelf()
639      */
stopSelfResult(int startId)640     public final boolean stopSelfResult(int startId) {
641         if (mActivityManager == null) {
642             return false;
643         }
644         try {
645             return mActivityManager.stopServiceToken(
646                     new ComponentName(this, mClassName), mToken, startId);
647         } catch (RemoteException ex) {
648         }
649         return false;
650     }
651 
652     /**
653      * @deprecated This is a now a no-op, use
654      * {@link #startForeground(int, Notification)} instead.  This method
655      * has been turned into a no-op rather than simply being deprecated
656      * because analysis of numerous poorly behaving devices has shown that
657      * increasingly often the trouble is being caused in part by applications
658      * that are abusing it.  Thus, given a choice between introducing
659      * problems in existing applications using this API (by allowing them to
660      * be killed when they would like to avoid it), vs allowing the performance
661      * of the entire system to be decreased, this method was deemed less
662      * important.
663      *
664      * @hide
665      */
666     @Deprecated
667     @UnsupportedAppUsage
setForeground(boolean isForeground)668     public final void setForeground(boolean isForeground) {
669         Log.w(TAG, "setForeground: ignoring old API call on " + getClass().getName());
670     }
671 
672     /**
673      * If your service is started (running through {@link Context#startService(Intent)}), then
674      * also make this service run in the foreground, supplying the ongoing
675      * notification to be shown to the user while in this state.
676      * By default started services are background, meaning that their process won't be given
677      * foreground CPU scheduling (unless something else in that process is foreground) and,
678      * if the system needs to kill them to reclaim more memory (such as to display a large page in a
679      * web browser), they can be killed without too much harm.  You use
680      * {@link #startForeground} if killing your service would be disruptive to the user, such as
681      * if your service is performing background music playback, so the user
682      * would notice if their music stopped playing.
683      *
684      * <p>Note that calling this method does <em>not</em> put the service in the started state
685      * itself, even though the name sounds like it.  You must always call
686      * {@link #startService(Intent)} first to tell the system it should keep the service running,
687      * and then use this method to tell it to keep it running harder.</p>
688      *
689      * <p>Apps targeting API {@link android.os.Build.VERSION_CODES#P} or later must request
690      * the permission {@link android.Manifest.permission#FOREGROUND_SERVICE} in order to use
691      * this API.</p>
692      *
693      * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
694      * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
695      * service element of manifest file. The value of attribute
696      * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
697      *
698      * @param id The identifier for this notification as per
699      * {@link NotificationManager#notify(int, Notification)
700      * NotificationManager.notify(int, Notification)}; must not be 0.
701      * @param notification The Notification to be displayed.
702      *
703      * @see #stopForeground(boolean)
704      */
startForeground(int id, Notification notification)705     public final void startForeground(int id, Notification notification) {
706         try {
707             mActivityManager.setServiceForeground(
708                     new ComponentName(this, mClassName), mToken, id,
709                     notification, 0, FOREGROUND_SERVICE_TYPE_MANIFEST);
710         } catch (RemoteException ex) {
711         }
712     }
713 
714   /**
715    * An overloaded version of {@link #startForeground(int, Notification)} with additional
716    * foregroundServiceType parameter.
717    *
718    * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
719    * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
720    * service element of manifest file. The value of attribute
721    * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
722    *
723    * <p>The foregroundServiceType parameter must be a subset flags of what is specified in manifest
724    * attribute {@link android.R.attr#foregroundServiceType}, if not, an IllegalArgumentException is
725    * thrown. Specify foregroundServiceType parameter as
726    * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST} to use all flags that
727    * is specified in manifest attribute foregroundServiceType.</p>
728    *
729    * @param id The identifier for this notification as per
730    * {@link NotificationManager#notify(int, Notification)
731    * NotificationManager.notify(int, Notification)}; must not be 0.
732    * @param notification The Notification to be displayed.
733    * @param foregroundServiceType must be a subset flags of manifest attribute
734    * {@link android.R.attr#foregroundServiceType} flags.
735    * @throws IllegalArgumentException if param foregroundServiceType is not subset of manifest
736    *     attribute {@link android.R.attr#foregroundServiceType}.
737    * @see android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST
738    */
startForeground(int id, @NonNull Notification notification, @ForegroundServiceType int foregroundServiceType)739     public final void startForeground(int id, @NonNull Notification notification,
740             @ForegroundServiceType int foregroundServiceType) {
741         try {
742             mActivityManager.setServiceForeground(
743                     new ComponentName(this, mClassName), mToken, id,
744                     notification, 0, foregroundServiceType);
745         } catch (RemoteException ex) {
746         }
747     }
748 
749     /**
750      * Synonym for {@link #stopForeground(int)}.
751      * @param removeNotification If true, the {@link #STOP_FOREGROUND_REMOVE} flag
752      * will be supplied.
753      * @see #stopForeground(int)
754      * @see #startForeground(int, Notification)
755      */
stopForeground(boolean removeNotification)756     public final void stopForeground(boolean removeNotification) {
757         stopForeground(removeNotification ? STOP_FOREGROUND_REMOVE : 0);
758     }
759 
760     /**
761      * Remove this service from foreground state, allowing it to be killed if
762      * more memory is needed.  This does not stop the service from running (for that
763      * you use {@link #stopSelf()} or related methods), just takes it out of the
764      * foreground state.
765      *
766      * @param flags additional behavior options.
767      * @see #startForeground(int, Notification)
768      */
stopForeground(@topForegroundFlags int flags)769     public final void stopForeground(@StopForegroundFlags int flags) {
770         try {
771             mActivityManager.setServiceForeground(
772                     new ComponentName(this, mClassName), mToken, 0, null,
773                     flags, 0);
774         } catch (RemoteException ex) {
775         }
776     }
777 
778     /**
779      * If the service has become a foreground service by calling
780      * {@link #startForeground(int, Notification)}
781      * or {@link #startForeground(int, Notification, int)}, {@link #getForegroundServiceType()}
782      * returns the current foreground service type.
783      *
784      * <p>If there is no foregroundServiceType specified
785      * in manifest, {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned. </p>
786      *
787      * <p>If the service is not a foreground service,
788      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned.</p>
789      *
790      * @return current foreground service type flags.
791      */
getForegroundServiceType()792     public final @ForegroundServiceType int getForegroundServiceType() {
793         int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
794         try {
795             ret = mActivityManager.getForegroundServiceType(
796                     new ComponentName(this, mClassName), mToken);
797         } catch (RemoteException ex) {
798         }
799         return ret;
800     }
801 
802     /**
803      * Print the Service's state into the given stream.  This gets invoked if
804      * you run "adb shell dumpsys activity service &lt;yourservicename&gt;"
805      * (note that for this command to work, the service must be running, and
806      * you must specify a fully-qualified service name).
807      * This is distinct from "dumpsys &lt;servicename&gt;", which only works for
808      * named system services and which invokes the {@link IBinder#dump} method
809      * on the {@link IBinder} interface registered with ServiceManager.
810      *
811      * @param fd The raw file descriptor that the dump is being sent to.
812      * @param writer The PrintWriter to which you should dump your state.  This will be
813      * closed for you after you return.
814      * @param args additional arguments to the dump request.
815      */
dump(FileDescriptor fd, PrintWriter writer, String[] args)816     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
817         writer.println("nothing to dump");
818     }
819 
820     // ------------------ Internal API ------------------
821 
822     /**
823      * @hide
824      */
825     @UnsupportedAppUsage
attach( Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager)826     public final void attach(
827             Context context,
828             ActivityThread thread, String className, IBinder token,
829             Application application, Object activityManager) {
830         attachBaseContext(context);
831         mThread = thread;           // NOTE:  unused - remove?
832         mClassName = className;
833         mToken = token;
834         mApplication = application;
835         mActivityManager = (IActivityManager)activityManager;
836         mStartCompatibility = getApplicationInfo().targetSdkVersion
837                 < Build.VERSION_CODES.ECLAIR;
838     }
839 
840     /**
841      * @hide
842      * Clean up any references to avoid leaks.
843      */
844     public final void detachAndCleanUp() {
845         mToken = null;
846     }
847 
848     final String getClassName() {
849         return mClassName;
850     }
851 
852     // set by the thread after the constructor and before onCreate(Bundle icicle) is called.
853     @UnsupportedAppUsage
854     private ActivityThread mThread = null;
855     @UnsupportedAppUsage
856     private String mClassName = null;
857     @UnsupportedAppUsage
858     private IBinder mToken = null;
859     @UnsupportedAppUsage
860     private Application mApplication = null;
861     @UnsupportedAppUsage
862     private IActivityManager mActivityManager = null;
863     @UnsupportedAppUsage
864     private boolean mStartCompatibility = false;
865 }
866