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