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