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