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