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