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