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 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
21 import static android.text.TextUtils.formatSimple;
22 
23 import android.annotation.IntDef;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.RequiresPermission;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.content.ComponentCallbacks2;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.ContextWrapper;
32 import android.content.Intent;
33 import android.content.pm.ServiceInfo;
34 import android.content.pm.ServiceInfo.ForegroundServiceType;
35 import android.content.res.Configuration;
36 import android.os.Build;
37 import android.os.IBinder;
38 import android.os.RemoteException;
39 import android.os.Trace;
40 import android.util.ArrayMap;
41 import android.util.Log;
42 import android.view.contentcapture.ContentCaptureManager;
43 
44 import com.android.internal.annotations.GuardedBy;
45 
46 import java.io.FileDescriptor;
47 import java.io.PrintWriter;
48 import java.lang.annotation.Retention;
49 import java.lang.annotation.RetentionPolicy;
50 
51 /**
52  * A Service is an application component representing either an application's desire
53  * to perform a longer-running operation while not interacting with the user
54  * or to supply functionality for other applications to use.  Each service
55  * class must have a corresponding
56  * {@link android.R.styleable#AndroidManifestService <service>}
57  * declaration in its package's <code>AndroidManifest.xml</code>.  Services
58  * can be started with
59  * {@link android.content.Context#startService Context.startService()} and
60  * {@link android.content.Context#bindService Context.bindService()}.
61  *
62  * <p>Note that services, like other application objects, run in the main
63  * thread of their hosting process.  This means that, if your service is going
64  * to do any CPU intensive (such as MP3 playback) or blocking (such as
65  * networking) operations, it should spawn its own thread in which to do that
66  * work.  More information on this can be found in
67  * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
68  * Threads</a>.  The {@link androidx.core.app.JobIntentService} class is available
69  * as a standard implementation of Service that has its own thread where it
70  * schedules its work to be done.</p>
71  *
72  * <p>Topics covered here:
73  * <ol>
74  * <li><a href="#WhatIsAService">What is a Service?</a>
75  * <li><a href="#ServiceLifecycle">Service Lifecycle</a>
76  * <li><a href="#Permissions">Permissions</a>
77  * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
78  * <li><a href="#LocalServiceSample">Local Service Sample</a>
79  * <li><a href="#RemoteMessengerServiceSample">Remote Messenger Service Sample</a>
80  * </ol>
81  *
82  * <div class="special reference">
83  * <h3>Developer Guides</h3>
84  * <p>For a detailed discussion about how to create services, read the
85  * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
86  * </div>
87  *
88  * <a name="WhatIsAService"></a>
89  * <h3>What is a Service?</h3>
90  *
91  * <p>Most confusion about the Service class actually revolves around what
92  * it is <em>not</em>:</p>
93  *
94  * <ul>
95  * <li> A Service is <b>not</b> a separate process.  The Service object itself
96  * does not imply it is running in its own process; unless otherwise specified,
97  * it runs in the same process as the application it is part of.
98  * <li> A Service is <b>not</b> a thread.  It is not a means itself to do work off
99  * of the main thread (to avoid Application Not Responding errors).
100  * </ul>
101  *
102  * <p>Thus a Service itself is actually very simple, providing two main features:</p>
103  *
104  * <ul>
105  * <li>A facility for the application to tell the system <em>about</em>
106  * something it wants to be doing in the background (even when the user is not
107  * directly interacting with the application).  This corresponds to calls to
108  * {@link android.content.Context#startService Context.startService()}, which
109  * ask the system to schedule work for the service, to be run until the service
110  * or someone else explicitly stop it.
111  * <li>A facility for an application to expose some of its functionality to
112  * other applications.  This corresponds to calls to
113  * {@link android.content.Context#bindService Context.bindService()}, which
114  * allows a long-standing connection to be made to the service in order to
115  * interact with it.
116  * </ul>
117  *
118  * <p>When a Service component is actually created, for either of these reasons,
119  * all that the system actually does is instantiate the component
120  * and call its {@link #onCreate} and any other appropriate callbacks on the
121  * main thread.  It is up to the Service to implement these with the appropriate
122  * behavior, such as creating a secondary thread in which it does its work.</p>
123  *
124  * <p>Note that because Service itself is so simple, you can make your
125  * interaction with it as simple or complicated as you want: from treating it
126  * as a local Java object that you make direct method calls on (as illustrated
127  * by <a href="#LocalServiceSample">Local Service Sample</a>), to providing
128  * a full remoteable interface using AIDL.</p>
129  *
130  * <a name="ServiceLifecycle"></a>
131  * <h3>Service Lifecycle</h3>
132  *
133  * <p>There are two reasons that a service can be run by the system.  If someone
134  * calls {@link android.content.Context#startService Context.startService()} then the system will
135  * retrieve the service (creating it and calling its {@link #onCreate} method
136  * if needed) and then call its {@link #onStartCommand} method with the
137  * arguments supplied by the client.  The service will at this point continue
138  * running until {@link android.content.Context#stopService Context.stopService()} or
139  * {@link #stopSelf()} is called.  Note that multiple calls to
140  * Context.startService() do not nest (though they do result in multiple corresponding
141  * calls to onStartCommand()), so no matter how many times it is started a service
142  * will be stopped once Context.stopService() or stopSelf() is called; however,
143  * services can use their {@link #stopSelf(int)} method to ensure the service is
144  * not stopped until started intents have been processed.
145  *
146  * <p>For started services, there are two additional major modes of operation
147  * they can decide to run in, depending on the value they return from
148  * onStartCommand(): {@link #START_STICKY} is used for services that are
149  * explicitly started and stopped as needed, while {@link #START_NOT_STICKY}
150  * or {@link #START_REDELIVER_INTENT} are used for services that should only
151  * remain running while processing any commands sent to them.  See the linked
152  * documentation for more detail on the semantics.
153  *
154  * <p>Clients can also use {@link android.content.Context#bindService Context.bindService()} to
155  * obtain a persistent connection to a service.  This likewise creates the
156  * service if it is not already running (calling {@link #onCreate} while
157  * doing so), but does not call onStartCommand().  The client will receive the
158  * {@link android.os.IBinder} object that the service returns from its
159  * {@link #onBind} method, allowing the client to then make calls back
160  * to the service.  The service will remain running as long as the connection
161  * is established (whether or not the client retains a reference on the
162  * service's IBinder).  Usually the IBinder returned is for a complex
163  * interface that has been <a href="{@docRoot}guide/components/aidl.html">written
164  * in aidl</a>.
165  *
166  * <p>A service can be both started and have connections bound to it.  In such
167  * a case, the system will keep the service running as long as either it is
168  * started <em>or</em> there are one or more connections to it with the
169  * {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE}
170  * flag.  Once neither
171  * of these situations hold, the service's {@link #onDestroy} method is called
172  * and the service is effectively terminated.  All cleanup (stopping threads,
173  * unregistering receivers) should be complete upon returning from onDestroy().
174  *
175  * <a name="Permissions"></a>
176  * <h3>Permissions</h3>
177  *
178  * <p>Global access to a service can be enforced when it is declared in its
179  * manifest's {@link android.R.styleable#AndroidManifestService &lt;service&gt;}
180  * tag.  By doing so, other applications will need to declare a corresponding
181  * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
182  * element in their own manifest to be able to start, stop, or bind to
183  * the service.
184  *
185  * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, when using
186  * {@link Context#startService(Intent) Context.startService(Intent)}, you can
187  * also set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
188  * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
189  * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent.  This will grant the
190  * Service temporary access to the specific URIs in the Intent.  Access will
191  * remain until the Service has called {@link #stopSelf(int)} for that start
192  * command or a later one, or until the Service has been completely stopped.
193  * This works for granting access to the other apps that have not requested
194  * the permission protecting the Service, or even when the Service is not
195  * exported at all.
196  *
197  * <p>In addition, a service can protect individual IPC calls into it with
198  * permissions, by calling the
199  * {@link #checkCallingPermission}
200  * method before executing the implementation of that call.
201  *
202  * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
203  * document for more information on permissions and security in general.
204  *
205  * <a name="ProcessLifecycle"></a>
206  * <h3>Process Lifecycle</h3>
207  *
208  * <p>The Android system will attempt to keep the process hosting a service
209  * around as long as the service has been started or has clients bound to it.
210  * When running low on memory and needing to kill existing processes, the
211  * priority of a process hosting the service will be the higher of the
212  * following possibilities:
213  *
214  * <ul>
215  * <li><p>If the service is currently executing code in its
216  * {@link #onCreate onCreate()}, {@link #onStartCommand onStartCommand()},
217  * or {@link #onDestroy onDestroy()} methods, then the hosting process will
218  * be a foreground process to ensure this code can execute without
219  * being killed.
220  * <li><p>If the service has been started, then its hosting process is considered
221  * to be less important than any processes that are currently visible to the
222  * user on-screen, but more important than any process not visible.  Because
223  * only a few processes are generally visible to the user, this means that
224  * the service should not be killed except in low memory conditions.  However, since
225  * the user is not directly aware of a background service, in that state it <em>is</em>
226  * considered a valid candidate to kill, and you should be prepared for this to
227  * happen.  In particular, long-running services will be increasingly likely to
228  * kill and are guaranteed to be killed (and restarted if appropriate) if they
229  * remain started long enough.
230  * <li><p>If there are clients bound to the service, then the service's hosting
231  * process is never less important than the most important client.  That is,
232  * if one of its clients is visible to the user, then the service itself is
233  * considered to be visible.  The way a client's importance impacts the service's
234  * importance can be adjusted through {@link Context#BIND_ABOVE_CLIENT},
235  * {@link Context#BIND_ALLOW_OOM_MANAGEMENT}, {@link Context#BIND_WAIVE_PRIORITY},
236  * {@link Context#BIND_IMPORTANT}, and {@link Context#BIND_ADJUST_WITH_ACTIVITY}.
237  * <li><p>A started service can use the {@link #startForeground(int, Notification)}
238  * API to put the service in a foreground state, where the system considers
239  * it to be something the user is actively aware of and thus not a candidate
240  * for killing when low on memory.  (It is still theoretically possible for
241  * the service to be killed under extreme memory pressure from the current
242  * foreground application, but in practice this should not be a concern.)
243  * </ul>
244  *
245  * <p>Note this means that most of the time your service is running, it may
246  * be killed by the system if it is under heavy memory pressure.  If this
247  * happens, the system will later try to restart the service.  An important
248  * consequence of this is that if you implement {@link #onStartCommand onStartCommand()}
249  * to schedule work to be done asynchronously or in another thread, then you
250  * may want to use {@link #START_FLAG_REDELIVERY} to have the system
251  * re-deliver an Intent for you so that it does not get lost if your service
252  * is killed while processing it.
253  *
254  * <p>Other application components running in the same process as the service
255  * (such as an {@link android.app.Activity}) can, of course, increase the
256  * importance of the overall
257  * process beyond just the importance of the service itself.
258  *
259  * <a name="LocalServiceSample"></a>
260  * <h3>Local Service Sample</h3>
261  *
262  * <p>One of the most common uses of a Service is as a secondary component
263  * running alongside other parts of an application, in the same process as
264  * the rest of the components.  All components of an .apk run in the same
265  * process unless explicitly stated otherwise, so this is a typical situation.
266  *
267  * <p>When used in this way, by assuming the
268  * components are in the same process, you can greatly simplify the interaction
269  * between them: clients of the service can simply cast the IBinder they
270  * receive from it to a concrete class published by the service.
271  *
272  * <p>An example of this use of a Service is shown here.  First is the Service
273  * itself, publishing a custom class when bound:
274  *
275  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalService.java
276  *      service}
277  *
278  * <p>With that done, one can now write client code that directly accesses the
279  * running service, such as:
280  *
281  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.java
282  *      bind}
283  *
284  * <a name="RemoteMessengerServiceSample"></a>
285  * <h3>Remote Messenger Service Sample</h3>
286  *
287  * <p>If you need to be able to write a Service that can perform complicated
288  * communication with clients in remote processes (beyond simply the use of
289  * {@link Context#startService(Intent) Context.startService} to send
290  * commands to it), then you can use the {@link android.os.Messenger} class
291  * instead of writing full AIDL files.
292  *
293  * <p>An example of a Service that uses Messenger as its client interface
294  * is shown here.  First is the Service itself, publishing a Messenger to
295  * an internal Handler when bound:
296  *
297  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.java
298  *      service}
299  *
300  * <p>If we want to make this service run in a remote process (instead of the
301  * standard one for its .apk), we can use <code>android:process</code> in its
302  * manifest tag to specify one:
303  *
304  * {@sample development/samples/ApiDemos/AndroidManifest.xml remote_service_declaration}
305  *
306  * <p>Note that the name "remote" chosen here is arbitrary, and you can use
307  * other names if you want additional processes.  The ':' prefix appends the
308  * name to your package's standard process name.
309  *
310  * <p>With that done, clients can now bind to the service and send messages
311  * to it.  Note that this allows clients to register with it to receive
312  * messages back as well:
313  *
314  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.java
315  *      bind}
316  */
317 public abstract class Service extends ContextWrapper implements ComponentCallbacks2,
318         ContentCaptureManager.ContentCaptureClient {
319     private static final String TAG = "Service";
320 
321     /**
322      * Selector for {@link #stopForeground(int)}:  equivalent to passing {@code false}
323      * to the legacy API {@link #stopForeground(boolean)}.
324      *
325      * @deprecated Use {@link #STOP_FOREGROUND_DETACH} instead.  The legacy
326      * behavior was inconsistent, leading to bugs around unpredictable results.
327      */
328     @Deprecated
329     public static final int STOP_FOREGROUND_LEGACY = 0;
330 
331     /**
332      * Selector for {@link #stopForeground(int)}: if supplied, the notification previously
333      * supplied to {@link #startForeground} will be cancelled and removed from display.
334      */
335     public static final int STOP_FOREGROUND_REMOVE = 1<<0;
336 
337     /**
338      * Selector for {@link #stopForeground(int)}: if set, the notification previously supplied
339      * to {@link #startForeground} will be detached from the service's lifecycle.  The notification
340      * will remain shown even after the service is stopped and destroyed.
341      */
342     public static final int STOP_FOREGROUND_DETACH = 1<<1;
343 
344     /** @hide */
345     @IntDef(flag = false, prefix = { "STOP_FOREGROUND_" }, value = {
346             STOP_FOREGROUND_LEGACY,
347             STOP_FOREGROUND_REMOVE,
348             STOP_FOREGROUND_DETACH
349     })
350     @Retention(RetentionPolicy.SOURCE)
351     public @interface StopForegroundSelector {}
352 
Service()353     public Service() {
354         super(null);
355     }
356 
357     /** Return the application that owns this service. */
getApplication()358     public final Application getApplication() {
359         return mApplication;
360     }
361 
362     /**
363      * Called by the system when the service is first created.  Do not call this method directly.
364      */
onCreate()365     public void onCreate() {
366     }
367 
368     /**
369      * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
370      */
371     @Deprecated
onStart(Intent intent, int startId)372     public void onStart(Intent intent, int startId) {
373     }
374 
375     /**
376      * Bits returned by {@link #onStartCommand} describing how to continue
377      * the service if it is killed.  May be {@link #START_STICKY},
378      * {@link #START_NOT_STICKY}, {@link #START_REDELIVER_INTENT},
379      * or {@link #START_STICKY_COMPATIBILITY}.
380      */
381     public static final int START_CONTINUATION_MASK = 0xf;
382 
383     /**
384      * Constant to return from {@link #onStartCommand}: compatibility
385      * version of {@link #START_STICKY} that does not guarantee that
386      * {@link #onStartCommand} will be called again after being killed.
387      */
388     public static final int START_STICKY_COMPATIBILITY = 0;
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}), then leave it in the started state but
394      * don't retain this delivered intent.  Later the system will try to
395      * re-create the service.  Because it is in the started state, it will
396      * guarantee to call {@link #onStartCommand} after creating the new
397      * service instance; if there are not any pending start commands to be
398      * delivered to the service, it will be called with a null intent
399      * object, so you must take care to check for this.
400      *
401      * <p>This mode makes sense for things that will be explicitly started
402      * and stopped to run for arbitrary periods of time, such as a service
403      * performing background music playback.
404      *
405      * <p>Since Android version {@link Build.VERSION_CODES#S}, apps
406      * targeting {@link Build.VERSION_CODES#S} or above are disallowed
407      * to start a foreground service from the background, but the restriction
408      * doesn't impact <em>restarts</em> of a sticky foreground service. However,
409      * when apps start a sticky foreground service from the background,
410      * the same restriction still applies.
411      */
412     public static final int START_STICKY = 1;
413 
414     /**
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}), and there are no new start intents to
418      * deliver to it, then take the service out of the started state and
419      * don't recreate until a future explicit call to
420      * {@link Context#startService Context.startService(Intent)}.  The
421      * service will not receive a {@link #onStartCommand(Intent, int, int)}
422      * call with a null Intent because it will not be restarted if there
423      * are no pending Intents to deliver.
424      *
425      * <p>This mode makes sense for things that want to do some work as a
426      * result of being started, but can be stopped when under memory pressure
427      * and will explicit start themselves again later to do more work.  An
428      * example of such a service would be one that polls for data from
429      * a server: it could schedule an alarm to poll every N minutes by having
430      * the alarm start its service.  When its {@link #onStartCommand} is
431      * called from the alarm, it schedules a new alarm for N minutes later,
432      * and spawns a thread to do its networking.  If its process is killed
433      * while doing that check, the service will not be restarted until the
434      * alarm goes off.
435      */
436     public static final int START_NOT_STICKY = 2;
437 
438     /**
439      * Constant to return from {@link #onStartCommand}: if this service's
440      * process is killed while it is started (after returning from
441      * {@link #onStartCommand}), then it will be scheduled for a restart
442      * and the last delivered Intent re-delivered to it again via
443      * {@link #onStartCommand}.  This Intent will remain scheduled for
444      * redelivery until the service calls {@link #stopSelf(int)} with the
445      * start ID provided to {@link #onStartCommand}.  The
446      * service will not receive a {@link #onStartCommand(Intent, int, int)}
447      * call with a null Intent because it will only be restarted if
448      * it is not finished processing all Intents sent to it (and any such
449      * pending events will be delivered at the point of restart).
450      */
451     public static final int START_REDELIVER_INTENT = 3;
452 
453     /** @hide */
454     @IntDef(flag = false, prefix = { "START_" }, value = {
455             START_STICKY_COMPATIBILITY,
456             START_STICKY,
457             START_NOT_STICKY,
458             START_REDELIVER_INTENT,
459     })
460     @Retention(RetentionPolicy.SOURCE)
461     public @interface StartResult {}
462 
463     /**
464      * Special constant for reporting that we are done processing
465      * {@link #onTaskRemoved(Intent)}.
466      * @hide
467      */
468     public static final int START_TASK_REMOVED_COMPLETE = 1000;
469 
470     /**
471      * This flag is set in {@link #onStartCommand} if the Intent is a
472      * re-delivery of a previously delivered intent, because the service
473      * had previously returned {@link #START_REDELIVER_INTENT} but had been
474      * killed before calling {@link #stopSelf(int)} for that Intent.
475      */
476     public static final int START_FLAG_REDELIVERY = 0x0001;
477 
478     /**
479      * This flag is set in {@link #onStartCommand} if the Intent is a
480      * retry because the original attempt never got to or returned from
481      * {@link #onStartCommand(Intent, int, int)}.
482      */
483     public static final int START_FLAG_RETRY = 0x0002;
484 
485     /** @hide */
486     @IntDef(flag = true, prefix = { "START_FLAG_" }, value = {
487             START_FLAG_REDELIVERY,
488             START_FLAG_RETRY,
489     })
490     @Retention(RetentionPolicy.SOURCE)
491     public @interface StartArgFlags {}
492 
493 
494     /**
495      * Called by the system every time a client explicitly starts the service by calling
496      * {@link android.content.Context#startService}, providing the arguments it supplied and a
497      * unique integer token representing the start request.  Do not call this method directly.
498      *
499      * <p>For backwards compatibility, the default implementation calls
500      * {@link #onStart} and returns either {@link #START_STICKY}
501      * or {@link #START_STICKY_COMPATIBILITY}.
502      *
503      * <p class="caution">Note that the system calls this on your
504      * service's main thread.  A service's main thread is the same
505      * thread where UI operations take place for Activities running in the
506      * same process.  You should always avoid stalling the main
507      * thread's event loop.  When doing long-running operations,
508      * network calls, or heavy disk I/O, you should kick off a new
509      * thread, or use {@link android.os.AsyncTask}.</p>
510      *
511      * @param intent The Intent supplied to {@link android.content.Context#startService},
512      * as given.  This may be null if the service is being restarted after
513      * its process has gone away, and it had previously returned anything
514      * except {@link #START_STICKY_COMPATIBILITY}.
515      * @param flags Additional data about this start request.
516      * @param startId A unique integer representing this specific request to
517      * start.  Use with {@link #stopSelfResult(int)}.
518      *
519      * @return The return value indicates what semantics the system should
520      * use for the service's current started state.  It may be one of the
521      * constants associated with the {@link #START_CONTINUATION_MASK} bits.
522      *
523      * @see #stopSelfResult(int)
524      */
onStartCommand(Intent intent, @StartArgFlags int flags, int startId)525     public @StartResult int onStartCommand(Intent intent, @StartArgFlags int flags, int startId) {
526         onStart(intent, startId);
527         return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
528     }
529 
530     /**
531      * Called by the system to notify a Service that it is no longer used and is being removed.  The
532      * service should clean up any resources it holds (threads, registered
533      * receivers, etc) at this point.  Upon return, there will be no more calls
534      * in to this Service object and it is effectively dead.  Do not call this method directly.
535      */
onDestroy()536     public void onDestroy() {
537     }
538 
onConfigurationChanged(Configuration newConfig)539     public void onConfigurationChanged(Configuration newConfig) {
540     }
541 
onLowMemory()542     public void onLowMemory() {
543     }
544 
onTrimMemory(int level)545     public void onTrimMemory(int level) {
546     }
547 
548     /**
549      * Return the communication channel to the service.  May return null if
550      * clients can not bind to the service.  The returned
551      * {@link android.os.IBinder} is usually for a complex interface
552      * that has been <a href="{@docRoot}guide/components/aidl.html">described using
553      * aidl</a>.
554      *
555      * <p><em>Note that unlike other application components, calls on to the
556      * IBinder interface returned here may not happen on the main thread
557      * of the process</em>.  More information about the main thread can be found in
558      * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
559      * Threads</a>.</p>
560      *
561      * @param intent The Intent that was used to bind to this service,
562      * as given to {@link android.content.Context#bindService
563      * Context.bindService}.  Note that any extras that were included with
564      * the Intent at that point will <em>not</em> be seen here.
565      *
566      * @return Return an IBinder through which clients can call on to the
567      *         service.
568      */
569     @Nullable
onBind(Intent intent)570     public abstract IBinder onBind(Intent intent);
571 
572     /**
573      * Called when all clients have disconnected from a particular interface
574      * published by the service.  The default implementation does nothing and
575      * returns false.
576      *
577      * @param intent The Intent that was used to bind to this service,
578      * as given to {@link android.content.Context#bindService
579      * Context.bindService}.  Note that any extras that were included with
580      * the Intent at that point will <em>not</em> be seen here.
581      *
582      * @return Return true if you would like to have the service's
583      * {@link #onRebind} method later called when new clients bind to it.
584      */
onUnbind(Intent intent)585     public boolean onUnbind(Intent intent) {
586         return false;
587     }
588 
589     /**
590      * Called when new clients have connected to the service, after it had
591      * previously been notified that all had disconnected in its
592      * {@link #onUnbind}.  This will only be called if the implementation
593      * of {@link #onUnbind} was overridden to return true.
594      *
595      * @param intent The Intent that was used to bind to this service,
596      * as given to {@link android.content.Context#bindService
597      * Context.bindService}.  Note that any extras that were included with
598      * the Intent at that point will <em>not</em> be seen here.
599      */
onRebind(Intent intent)600     public void onRebind(Intent intent) {
601     }
602 
603     /**
604      * This is called if the service is currently running and the user has
605      * removed a task that comes from the service's application.  If you have
606      * set {@link android.content.pm.ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
607      * then you will not receive this callback; instead, the service will simply
608      * be stopped.
609      *
610      * @param rootIntent The original root Intent that was used to launch
611      * the task that is being removed.
612      */
onTaskRemoved(Intent rootIntent)613     public void onTaskRemoved(Intent rootIntent) {
614     }
615 
616     /**
617      * Stop the service, if it was previously started.  This is the same as
618      * calling {@link android.content.Context#stopService} for this particular service.
619      *
620      * @see #stopSelfResult(int)
621      */
stopSelf()622     public final void stopSelf() {
623         stopSelf(-1);
624     }
625 
626     /**
627      * Old version of {@link #stopSelfResult} that doesn't return a result.
628      *
629      * @see #stopSelfResult
630      */
stopSelf(int startId)631     public final void stopSelf(int startId) {
632         if (mActivityManager == null) {
633             return;
634         }
635         try {
636             mActivityManager.stopServiceToken(
637                     new ComponentName(this, mClassName), mToken, startId);
638         } catch (RemoteException ex) {
639         }
640     }
641 
642     /**
643      * Stop the service if the most recent time it was started was
644      * <var>startId</var>.  This is the same as calling {@link
645      * android.content.Context#stopService} for this particular service but allows you to
646      * safely avoid stopping if there is a start request from a client that you
647      * haven't yet seen in {@link #onStart}.
648      *
649      * <p><em>Be careful about ordering of your calls to this function.</em>.
650      * If you call this function with the most-recently received ID before
651      * you have called it for previously received IDs, the service will be
652      * immediately stopped anyway.  If you may end up processing IDs out
653      * of order (such as by dispatching them on separate threads), then you
654      * are responsible for stopping them in the same order you received them.</p>
655      *
656      * @param startId The most recent start identifier received in {@link
657      *                #onStart}.
658      * @return Returns true if the startId matches the last start request
659      * and the service will be stopped, else false.
660      *
661      * @see #stopSelf()
662      */
stopSelfResult(int startId)663     public final boolean stopSelfResult(int startId) {
664         if (mActivityManager == null) {
665             return false;
666         }
667         try {
668             return mActivityManager.stopServiceToken(
669                     new ComponentName(this, mClassName), mToken, startId);
670         } catch (RemoteException ex) {
671         }
672         return false;
673     }
674 
675     /**
676      * @deprecated This is a now a no-op, use
677      * {@link #startForeground(int, Notification)} instead.  This method
678      * has been turned into a no-op rather than simply being deprecated
679      * because analysis of numerous poorly behaving devices has shown that
680      * increasingly often the trouble is being caused in part by applications
681      * that are abusing it.  Thus, given a choice between introducing
682      * problems in existing applications using this API (by allowing them to
683      * be killed when they would like to avoid it), vs allowing the performance
684      * of the entire system to be decreased, this method was deemed less
685      * important.
686      *
687      * @hide
688      */
689     @Deprecated
690     @UnsupportedAppUsage
setForeground(boolean isForeground)691     public final void setForeground(boolean isForeground) {
692         Log.w(TAG, "setForeground: ignoring old API call on " + getClass().getName());
693     }
694 
695     /**
696      * If your service is started (running through {@link Context#startService(Intent)}), then
697      * also make this service run in the foreground, supplying the ongoing
698      * notification to be shown to the user while in this state.
699      * By default started services are background, meaning that their process won't be given
700      * foreground CPU scheduling (unless something else in that process is foreground) and,
701      * if the system needs to kill them to reclaim more memory (such as to display a large page in a
702      * web browser), they can be killed without too much harm.  You use
703      * {@link #startForeground} if killing your service would be disruptive to the user, such as
704      * if your service is performing background music playback, so the user
705      * would notice if their music stopped playing.
706      *
707      * <p>Note that calling this method does <em>not</em> put the service in the started state
708      * itself, even though the name sounds like it.  You must always call
709      * {@link #startService(Intent)} first to tell the system it should keep the service running,
710      * and then use this method to tell it to keep it running harder.</p>
711      *
712      * <p>Apps targeting API {@link android.os.Build.VERSION_CODES#P} or later must request
713      * the permission {@link android.Manifest.permission#FOREGROUND_SERVICE} in order to use
714      * this API.</p>
715      *
716      * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
717      * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
718      * service element of manifest file. The value of attribute
719      * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
720      *
721      * <div class="caution">
722      * <p><strong>Note:</strong>
723      * Beginning with SDK Version {@link android.os.Build.VERSION_CODES#S},
724      * apps targeting SDK Version {@link android.os.Build.VERSION_CODES#S}
725      * or higher are not allowed to start foreground services from the background.
726      * See
727      * <a href="{@docRoot}about/versions/12/behavior-changes-12">
728      * Behavior changes: Apps targeting Android 12
729      * </a>
730      * for more details.
731      * </div>
732      *
733      * <div class="caution">
734      * <p><strong>Note:</strong>
735      * Beginning with SDK Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
736      * apps targeting SDK Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}
737      * or higher are not allowed to start foreground services without specifying a valid
738      * foreground service type in the manifest attribute
739      * {@link android.R.attr#foregroundServiceType}.
740      * See
741      * <a href="{@docRoot}about/versions/14/behavior-changes-14">
742      * Behavior changes: Apps targeting Android 14
743      * </a>
744      * for more details.
745      * </div>
746      *
747      * @throws ForegroundServiceStartNotAllowedException
748      * If the app targeting API is
749      * {@link android.os.Build.VERSION_CODES#S} or later, and the service is restricted from
750      * becoming foreground service due to background restriction.
751      * @throws InvalidForegroundServiceTypeException
752      * If the app targeting API is
753      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later, and the manifest attribute
754      * {@link android.R.attr#foregroundServiceType} is set to invalid types(i.e.
755      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE}).
756      * @throws MissingForegroundServiceTypeException
757      * If the app targeting API is
758      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later, and the manifest attribute
759      * {@link android.R.attr#foregroundServiceType} is not set.
760      * @throws SecurityException If the app targeting API is
761      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later and doesn't have the
762      * permission to start the foreground service with the specified type in the manifest attribute
763      * {@link android.R.attr#foregroundServiceType}.
764      *
765      * @param id The identifier for this notification as per
766      * {@link NotificationManager#notify(int, Notification)
767      * NotificationManager.notify(int, Notification)}; must not be 0.
768      * @param notification The Notification to be displayed.
769      *
770      * @see #stopForeground(boolean)
771      */
startForeground(int id, Notification notification)772     public final void startForeground(int id, Notification notification) {
773         try {
774             final ComponentName comp = new ComponentName(this, mClassName);
775             mActivityManager.setServiceForeground(
776                     comp, mToken, id,
777                     notification, 0, FOREGROUND_SERVICE_TYPE_MANIFEST);
778             clearStartForegroundServiceStackTrace();
779             logForegroundServiceStart(comp, FOREGROUND_SERVICE_TYPE_MANIFEST);
780         } catch (RemoteException ex) {
781         }
782     }
783 
784     /**
785      * An overloaded version of {@link #startForeground(int, Notification)} with additional
786      * foregroundServiceType parameter.
787      *
788      * <p>Apps built with SDK version {@link android.os.Build.VERSION_CODES#Q} or later can specify
789      * the foreground service types using attribute {@link android.R.attr#foregroundServiceType} in
790      * service element of manifest file. The value of attribute
791      * {@link android.R.attr#foregroundServiceType} can be multiple flags ORed together.</p>
792      *
793      * <p>The foregroundServiceType parameter must be a subset flags of what is specified in
794      * manifest attribute {@link android.R.attr#foregroundServiceType}, if not, an
795      * IllegalArgumentException is thrown. Specify foregroundServiceType parameter as
796      * {@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST} to use all flags that
797      * is specified in manifest attribute foregroundServiceType.</p>
798      *
799      * <div class="caution">
800      * <p><strong>Note:</strong>
801      * Beginning with SDK Version {@link android.os.Build.VERSION_CODES#S},
802      * apps targeting SDK Version {@link android.os.Build.VERSION_CODES#S}
803      * or higher are not allowed to start foreground services from the background.
804      * See
805      * <a href="{@docRoot}about/versions/12/behavior-changes-12">
806      * Behavior changes: Apps targeting Android 12
807      * </a>
808      * for more details.
809      * </div>
810      *
811      * <div class="caution">
812      * <p><strong>Note:</strong>
813      * Beginning with SDK Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
814      * apps targeting SDK Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}
815      * or higher are not allowed to start foreground services without specifying a valid
816      * foreground service type in the manifest attribute
817      * {@link android.R.attr#foregroundServiceType}, and the parameter {@code foregroundServiceType}
818      * here must not be the {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE}.
819      * See
820      * <a href="{@docRoot}about/versions/14/behavior-changes-14">
821      * Behavior changes: Apps targeting Android 14
822      * </a>
823      * for more details.
824      * </div>
825      *
826      * @param id The identifier for this notification as per
827      * {@link NotificationManager#notify(int, Notification)
828      * NotificationManager.notify(int, Notification)}; must not be 0.
829      * @param notification The Notification to be displayed.
830      * @param foregroundServiceType must be a subset flags of manifest attribute
831      * {@link android.R.attr#foregroundServiceType} flags; must not be
832      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE}.
833      *
834      * @throws IllegalArgumentException if param foregroundServiceType is not subset of manifest
835      *     attribute {@link android.R.attr#foregroundServiceType}.
836      * @throws ForegroundServiceStartNotAllowedException
837      * If the app targeting API is
838      * {@link android.os.Build.VERSION_CODES#S} or later, and the service is restricted from
839      * becoming foreground service due to background restriction.
840      * @throws InvalidForegroundServiceTypeException
841      * If the app targeting API is
842      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later, and the manifest attribute
843      * {@link android.R.attr#foregroundServiceType} or the param {@code foregroundServiceType}
844      * is set to invalid types(i.e.{@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE}).
845      * @throws MissingForegroundServiceTypeException
846      * If the app targeting API is
847      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later, and the manifest attribute
848      * {@link android.R.attr#foregroundServiceType} is not set and the param
849      * {@code foregroundServiceType} is set to {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST}.
850      * @throws SecurityException If the app targeting API is
851      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or later and doesn't have the
852      * permission to start the foreground service with the specified type in
853      * {@code foregroundServiceType}.
854      * {@link android.R.attr#foregroundServiceType}.
855      *
856      * @see android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MANIFEST
857      */
startForeground(int id, @NonNull Notification notification, @RequiresPermission @ForegroundServiceType int foregroundServiceType)858     public final void startForeground(int id, @NonNull Notification notification,
859             @RequiresPermission @ForegroundServiceType int foregroundServiceType) {
860         try {
861             final ComponentName comp = new ComponentName(this, mClassName);
862             mActivityManager.setServiceForeground(
863                     comp, mToken, id,
864                     notification, 0, foregroundServiceType);
865             clearStartForegroundServiceStackTrace();
866             logForegroundServiceStart(comp, foregroundServiceType);
867         } catch (RemoteException ex) {
868         }
869     }
870 
871     /**
872      * Legacy version of {@link #stopForeground(int)}.
873      * @param removeNotification If true, the {@link #STOP_FOREGROUND_REMOVE}
874      * selector will be passed to {@link #stopForeground(int)}; otherwise
875      * {@link #STOP_FOREGROUND_LEGACY} will be passed.
876      * @see #stopForeground(int)
877      * @see #startForeground(int, Notification)
878      *
879      * @deprecated call {@link #stopForeground(int)} and pass either
880      * {@link #STOP_FOREGROUND_REMOVE} or {@link #STOP_FOREGROUND_DETACH}
881      * explicitly instead.
882      */
883     @Deprecated
stopForeground(boolean removeNotification)884     public final void stopForeground(boolean removeNotification) {
885         stopForeground(removeNotification ? STOP_FOREGROUND_REMOVE : STOP_FOREGROUND_LEGACY);
886     }
887 
888     /**
889      * Remove this service from foreground state, allowing it to be killed if
890      * more memory is needed.  This does not stop the service from running (for that
891      * you use {@link #stopSelf()} or related methods), just takes it out of the
892      * foreground state.
893      *
894      * <p>If {@link #STOP_FOREGROUND_REMOVE} is supplied, the service's associated
895      * notification will be cancelled immediately.</p>
896      * <p>If {@link #STOP_FOREGROUND_DETACH} is supplied, the service's association
897      * with the notification will be severed.  If the notification had not yet been
898      * shown, due to foreground-service notification deferral policy, it is
899      * immediately posted when {@code stopForeground(STOP_FOREGROUND_DETACH)}
900      * is called.  In all cases, the notification remains shown
901      * even after this service is stopped fully and destroyed.</p>
902      * <p>If {@code zero} is passed as the argument, the result will be the legacy
903      * behavior as defined prior to Android L: the notification will remain posted until
904      * the service is fully stopped, at which time it will automatically be cancelled.</p>
905      *
906      * @param notificationBehavior the intended behavior for the service's associated
907      * notification
908      * @see #startForeground(int, Notification)
909      * @see #STOP_FOREGROUND_DETACH
910      * @see #STOP_FOREGROUND_REMOVE
911      */
stopForeground(@topForegroundSelector int notificationBehavior)912     public final void stopForeground(@StopForegroundSelector int notificationBehavior) {
913         try {
914             mActivityManager.setServiceForeground(
915                     new ComponentName(this, mClassName), mToken, 0, null,
916                     notificationBehavior, 0);
917             logForegroundServiceStopIfNecessary();
918         } catch (RemoteException ex) {
919         }
920     }
921 
922     /**
923      * If the service has become a foreground service by calling
924      * {@link #startForeground(int, Notification)}
925      * or {@link #startForeground(int, Notification, int)}, {@link #getForegroundServiceType()}
926      * returns the current foreground service type.
927      *
928      * <p>If there is no foregroundServiceType specified
929      * in manifest, {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned. </p>
930      *
931      * <p>If the service is not a foreground service,
932      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE} is returned.</p>
933      *
934      * @return current foreground service type flags.
935      */
getForegroundServiceType()936     public final @ForegroundServiceType int getForegroundServiceType() {
937         int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
938         try {
939             ret = mActivityManager.getForegroundServiceType(
940                     new ComponentName(this, mClassName), mToken);
941         } catch (RemoteException ex) {
942         }
943         return ret;
944     }
945 
946     /**
947      * Print the Service's state into the given stream.  This gets invoked if
948      * you run "adb shell dumpsys activity service &lt;yourservicename&gt;"
949      * (note that for this command to work, the service must be running, and
950      * you must specify a fully-qualified service name).
951      * This is distinct from "dumpsys &lt;servicename&gt;", which only works for
952      * named system services and which invokes the {@link IBinder#dump} method
953      * on the {@link IBinder} interface registered with ServiceManager.
954      *
955      * @param fd The raw file descriptor that the dump is being sent to.
956      * @param writer The PrintWriter to which you should dump your state.  This will be
957      * closed for you after you return.
958      * @param args additional arguments to the dump request.
959      */
dump(FileDescriptor fd, PrintWriter writer, String[] args)960     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
961         writer.println("nothing to dump");
962     }
963 
964     @Override
attachBaseContext(Context newBase)965     protected void attachBaseContext(Context newBase) {
966         super.attachBaseContext(newBase);
967         if (newBase != null) {
968             newBase.setContentCaptureOptions(getContentCaptureOptions());
969         }
970     }
971 
972     // ------------------ Internal API ------------------
973 
974     /**
975      * @hide
976      */
977     @UnsupportedAppUsage
attach( Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager)978     public final void attach(
979             Context context,
980             ActivityThread thread, String className, IBinder token,
981             Application application, Object activityManager) {
982         attachBaseContext(context);
983         mThread = thread;           // NOTE:  unused - remove?
984         mClassName = className;
985         mToken = token;
986         mApplication = application;
987         mActivityManager = (IActivityManager)activityManager;
988         mStartCompatibility = getApplicationInfo().targetSdkVersion
989                 < Build.VERSION_CODES.ECLAIR;
990 
991         setContentCaptureOptions(application.getContentCaptureOptions());
992     }
993 
994     /**
995      * Creates the base {@link Context} of this {@link Service}.
996      * Users may override this API to create customized base context.
997      *
998      * @see android.window.WindowProviderService WindowProviderService class for example
999      * @see ContextWrapper#attachBaseContext(Context)
1000      *
1001      * @hide
1002      */
1003     public Context createServiceBaseContext(ActivityThread mainThread, LoadedApk packageInfo) {
1004         return ContextImpl.createAppContext(mainThread, packageInfo);
1005     }
1006 
1007     /**
1008      * @hide
1009      * Clean up any references to avoid leaks.
1010      */
1011     public final void detachAndCleanUp() {
1012         mToken = null;
1013         logForegroundServiceStopIfNecessary();
1014     }
1015 
1016     final String getClassName() {
1017         return mClassName;
1018     }
1019 
1020     /** @hide */
1021     @Override
1022     public final ContentCaptureManager.ContentCaptureClient getContentCaptureClient() {
1023         return this;
1024     }
1025 
1026     /** @hide */
1027     @Override
1028     public final ComponentName contentCaptureClientGetComponentName() {
1029         return new ComponentName(this, mClassName);
1030     }
1031 
1032     // set by the thread after the constructor and before onCreate(Bundle icicle) is called.
1033     @UnsupportedAppUsage
1034     private ActivityThread mThread = null;
1035     @UnsupportedAppUsage
1036     private String mClassName = null;
1037     @UnsupportedAppUsage
1038     private IBinder mToken = null;
1039     @UnsupportedAppUsage
1040     private Application mApplication = null;
1041     @UnsupportedAppUsage
1042     private IActivityManager mActivityManager = null;
1043     @UnsupportedAppUsage
1044     private boolean mStartCompatibility = false;
1045 
1046     /**
1047      * This will be set to the title of the system trace when this service is started as
1048      * a foreground service, and will be set to null when it's no longer in foreground
1049      * service state.
1050      */
1051     @GuardedBy("mForegroundServiceTraceTitleLock")
1052     private @Nullable String mForegroundServiceTraceTitle = null;
1053 
1054     private final Object mForegroundServiceTraceTitleLock = new Object();
1055 
1056     private static final String TRACE_TRACK_NAME_FOREGROUND_SERVICE = "FGS";
1057 
1058     private void logForegroundServiceStart(ComponentName comp,
1059             @ForegroundServiceType int foregroundServiceType) {
1060         synchronized (mForegroundServiceTraceTitleLock) {
1061             if (mForegroundServiceTraceTitle == null) {
1062                 mForegroundServiceTraceTitle = formatSimple("comp=%s type=%s",
1063                         comp.toShortString(), Integer.toHexString(foregroundServiceType));
1064                 // The service is not in foreground state, emit a start event.
1065                 Trace.asyncTraceForTrackBegin(TRACE_TAG_ACTIVITY_MANAGER,
1066                         TRACE_TRACK_NAME_FOREGROUND_SERVICE,
1067                         mForegroundServiceTraceTitle,
1068                         System.identityHashCode(this));
1069             } else {
1070                 // The service is already in foreground state, emit an one-off event.
1071                 Trace.instantForTrack(TRACE_TAG_ACTIVITY_MANAGER,
1072                         TRACE_TRACK_NAME_FOREGROUND_SERVICE,
1073                         mForegroundServiceTraceTitle);
1074             }
1075         }
1076     }
1077 
1078     private void logForegroundServiceStopIfNecessary() {
1079         synchronized (mForegroundServiceTraceTitleLock) {
1080             if (mForegroundServiceTraceTitle != null) {
1081                 Trace.asyncTraceForTrackEnd(TRACE_TAG_ACTIVITY_MANAGER,
1082                         TRACE_TRACK_NAME_FOREGROUND_SERVICE,
1083                         System.identityHashCode(this));
1084                 mForegroundServiceTraceTitle = null;
1085             }
1086         }
1087     }
1088 
1089     /**
1090      * This keeps track of the stacktrace where Context.startForegroundService() was called
1091      * for each service class. We use that when we crash the app for not calling
1092      * {@link #startForeground} in time, in {@link ActivityThread#throwRemoteServiceException}.
1093      */
1094     @GuardedBy("sStartForegroundServiceStackTraces")
1095     private static final ArrayMap<String, StackTrace> sStartForegroundServiceStackTraces =
1096             new ArrayMap<>();
1097 
1098     /** @hide */
1099     public static void setStartForegroundServiceStackTrace(
1100             @NonNull String className, @NonNull StackTrace stacktrace) {
1101         synchronized (sStartForegroundServiceStackTraces) {
1102             sStartForegroundServiceStackTraces.put(className, stacktrace);
1103         }
1104     }
1105 
1106     private void clearStartForegroundServiceStackTrace() {
1107         synchronized (sStartForegroundServiceStackTraces) {
1108             sStartForegroundServiceStackTraces.remove(this.getClassName());
1109         }
1110     }
1111 
1112     /** @hide */
1113     public static StackTrace getStartForegroundServiceStackTrace(@NonNull String className) {
1114         synchronized (sStartForegroundServiceStackTraces) {
1115             return sStartForegroundServiceStackTraces.get(className);
1116         }
1117     }
1118 
1119     /** @hide */
1120     public final void callOnTimeout(int startId) {
1121         // Note, because all the service callbacks (and other similar callbacks, e.g. activity
1122         // callbacks) are delivered using the main handler, it's possible the service is already
1123         // stopped when before this method is called, so we do a double check here.
1124         if (mToken == null) {
1125             Log.w(TAG, "Service already destroyed, skipping onTimeout()");
1126             return;
1127         }
1128         try {
1129             if (!mActivityManager.shouldServiceTimeOut(
1130                     new ComponentName(this, mClassName), mToken)) {
1131                 Log.w(TAG, "Service no longer relevant, skipping onTimeout()");
1132                 return;
1133             }
1134         } catch (RemoteException ex) {
1135         }
1136         onTimeout(startId);
1137     }
1138 
1139     /**
1140      * Callback called on timeout for {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_SHORT_SERVICE}.
1141      * See {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_SHORT_SERVICE} for more details.
1142      *
1143      * <p>If the foreground service of type
1144      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_SHORT_SERVICE}
1145      * doesn't finish even after it's timed out,
1146      * the app will be declared an ANR after a short grace period of several seconds.
1147      *
1148      * <p>Note, even though
1149      * {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_SHORT_SERVICE}
1150      * was added
1151      * on Android version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
1152      * it can be also used on
1153      * on prior android versions (just like other new foreground service types can be used).
1154      * However, because {@link android.app.Service#onTimeout(int)} did not exist on prior versions,
1155      * it will never called on such versions.
1156      * Because of this, developers must make sure to stop the foreground service even if
1157      * {@link android.app.Service#onTimeout(int)} is not called on such versions.
1158      *
1159      * @param startId the startId passed to {@link #onStartCommand(Intent, int, int)} when
1160      * the service started.
1161      */
1162     public void onTimeout(int startId) {
1163     }
1164 }
1165