• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.ComponentCallbacks;
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 that runs in the background, not
35  * interacting with the user, for an indefinite period of time.  Each service
36  * class must have a corresponding
37  * {@link android.R.styleable#AndroidManifestService <service>}
38  * declaration in its package's <code>AndroidManifest.xml</code>.  Services
39  * can be started with
40  * {@link android.content.Context#startService Context.startService()} and
41  * {@link android.content.Context#bindService Context.bindService()}.
42  *
43  * <p>Note that services, like other application objects, run in the main
44  * thread of their hosting process.  This means that, if your service is going
45  * to do any CPU intensive (such as MP3 playback) or blocking (such as
46  * networking) operations, it should spawn its own thread in which to do that
47  * work.  More information on this can be found in
48  * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
49  * Processes and Threads</a>.</p>
50  *
51  * <p>The Service class is an important part of an
52  * <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">application's overall lifecycle</a>.</p>
53  *
54  * <p>Topics covered here:
55  * <ol>
56  * <li><a href="#ServiceLifecycle">Service Lifecycle</a>
57  * <li><a href="#Permissions">Permissions</a>
58  * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
59  * </ol>
60  *
61  * <a name="ServiceLifecycle"></a>
62  * <h3>Service Lifecycle</h3>
63  *
64  * <p>There are two reasons that a service can be run by the system.  If someone
65  * calls {@link android.content.Context#startService Context.startService()} then the system will
66  * retrieve the service (creating it and calling its {@link #onCreate} method
67  * if needed) and then call its {@link #onStartCommand} method with the
68  * arguments supplied by the client.  The service will at this point continue
69  * running until {@link android.content.Context#stopService Context.stopService()} or
70  * {@link #stopSelf()} is called.  Note that multiple calls to
71  * Context.startService() do not nest (though they do result in multiple corresponding
72  * calls to onStartCommand()), so no matter how many times it is started a service
73  * will be stopped once Context.stopService() or stopSelf() is called; however,
74  * services can use their {@link #stopSelf(int)} method to ensure the service is
75  * not stopped until started intents have been processed.
76  *
77  * <p>For started services, there are two additional major modes of operation
78  * they can decide to run in, depending on the value they return from
79  * onStartCommand(): {@link #START_STICKY} is used for services that are
80  * explicitly started and stopped as needed, while {@link #START_NOT_STICKY}
81  * or {@link #START_REDELIVER_INTENT} are used for services that should only
82  * remain running while processing any commands sent to them.  See the linked
83  * documentation for more detail on the semantics.
84  *
85  * <p>Clients can also use {@link android.content.Context#bindService Context.bindService()} to
86  * obtain a persistent connection to a service.  This likewise creates the
87  * service if it is not already running (calling {@link #onCreate} while
88  * doing so), but does not call onStartCommand().  The client will receive the
89  * {@link android.os.IBinder} object that the service returns from its
90  * {@link #onBind} method, allowing the client to then make calls back
91  * to the service.  The service will remain running as long as the connection
92  * is established (whether or not the client retains a reference on the
93  * service's IBinder).  Usually the IBinder returned is for a complex
94  * interface that has been <a href="{@docRoot}guide/developing/tools/aidl.html">written
95  * in aidl</a>.
96  *
97  * <p>A service can be both started and have connections bound to it.  In such
98  * a case, the system will keep the service running as long as either it is
99  * started <em>or</em> there are one or more connections to it with the
100  * {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE}
101  * flag.  Once neither
102  * of these situations hold, the service's {@link #onDestroy} method is called
103  * and the service is effectively terminated.  All cleanup (stopping threads,
104  * unregistering receivers) should be complete upon returning from onDestroy().
105  *
106  * <a name="Permissions"></a>
107  * <h3>Permissions</h3>
108  *
109  * <p>Global access to a service can be enforced when it is declared in its
110  * manifest's {@link android.R.styleable#AndroidManifestService &lt;service&gt;}
111  * tag.  By doing so, other applications will need to declare a corresponding
112  * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
113  * element in their own manifest to be able to start, stop, or bind to
114  * the service.
115  *
116  * <p>In addition, a service can protect individual IPC calls into it with
117  * permissions, by calling the
118  * {@link #checkCallingPermission}
119  * method before executing the implementation of that call.
120  *
121  * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
122  * document for more information on permissions and security in general.
123  *
124  * <a name="ProcessLifecycle"></a>
125  * <h3>Process Lifecycle</h3>
126  *
127  * <p>The Android system will attempt to keep the process hosting a service
128  * around as long as the service has been started or has clients bound to it.
129  * When running low on memory and needing to kill existing processes, the
130  * priority of a process hosting the service will be the higher of the
131  * following possibilities:
132  *
133  * <ul>
134  * <li><p>If the service is currently executing code in its
135  * {@link #onCreate onCreate()}, {@link #onStartCommand onStartCommand()},
136  * or {@link #onDestroy onDestroy()} methods, then the hosting process will
137  * be a foreground process to ensure this code can execute without
138  * being killed.
139  * <li><p>If the service has been started, then its hosting process is considered
140  * to be less important than any processes that are currently visible to the
141  * user on-screen, but more important than any process not visible.  Because
142  * only a few processes are generally visible to the user, this means that
143  * the service should not be killed except in extreme low memory conditions.
144  * <li><p>If there are clients bound to the service, then the service's hosting
145  * process is never less important than the most important client.  That is,
146  * if one of its clients is visible to the user, then the service itself is
147  * considered to be visible.
148  * <li><p>A started service can use the {@link #startForeground(int, Notification)}
149  * API to put the service in a foreground state, where the system considers
150  * it to be something the user is actively aware of and thus not a candidate
151  * for killing when low on memory.  (It is still theoretically possible for
152  * the service to be killed under extreme memory pressure from the current
153  * foreground application, but in practice this should not be a concern.)
154  * </ul>
155  *
156  * <p>Note this means that most of the time your service is running, it may
157  * be killed by the system if it is under heavy memory pressure.  If this
158  * happens, the system will later try to restart the service.  An important
159  * consequence of this is that if you implement {@link #onStartCommand onStartCommand()}
160  * to schedule work to be done asynchronously or in another thread, then you
161  * may want to use {@link #START_FLAG_REDELIVERY} to have the system
162  * re-deliver an Intent for you so that it does not get lost if your service
163  * is killed while processing it.
164  *
165  * <p>Other application components running in the same process as the service
166  * (such as an {@link android.app.Activity}) can, of course, increase the
167  * importance of the overall
168  * process beyond just the importance of the service itself.
169  */
170 public abstract class Service extends ContextWrapper implements ComponentCallbacks {
171     private static final String TAG = "Service";
172 
Service()173     public Service() {
174         super(null);
175     }
176 
177     /** Return the application that owns this service. */
getApplication()178     public final Application getApplication() {
179         return mApplication;
180     }
181 
182     /**
183      * Called by the system when the service is first created.  Do not call this method directly.
184      */
onCreate()185     public void onCreate() {
186     }
187 
188     /**
189      * @deprecated Implement {@link #onStartCommand(Intent, int, int)} instead.
190      */
191     @Deprecated
onStart(Intent intent, int startId)192     public void onStart(Intent intent, int startId) {
193     }
194 
195     /**
196      * Bits returned by {@link #onStartCommand} describing how to continue
197      * the service if it is killed.  May be {@link #START_STICKY},
198      * {@link #START_NOT_STICKY}, {@link #START_REDELIVER_INTENT},
199      * or {@link #START_STICKY_COMPATIBILITY}.
200      */
201     public static final int START_CONTINUATION_MASK = 0xf;
202 
203     /**
204      * Constant to return from {@link #onStartCommand}: compatibility
205      * version of {@link #START_STICKY} that does not guarantee that
206      * {@link #onStartCommand} will be called again after being killed.
207      */
208     public static final int START_STICKY_COMPATIBILITY = 0;
209 
210     /**
211      * Constant to return from {@link #onStartCommand}: if this service's
212      * process is killed while it is started (after returning from
213      * {@link #onStartCommand}), then leave it in the started state but
214      * don't retain this delivered intent.  Later the system will try to
215      * re-create the service.  Because it is in the started state, it will
216      * guarantee to call {@link #onStartCommand} after creating the new
217      * service instance; if there are not any pending start commands to be
218      * delivered to the service, it will be called with a null intent
219      * object, so you must take care to check for this.
220      *
221      * <p>This mode makes sense for things that will be explicitly started
222      * and stopped to run for arbitrary periods of time, such as a service
223      * performing background music playback.
224      */
225     public static final int START_STICKY = 1;
226 
227     /**
228      * Constant to return from {@link #onStartCommand}: if this service's
229      * process is killed while it is started (after returning from
230      * {@link #onStartCommand}), and there are no new start intents to
231      * deliver to it, then take the service out of the started state and
232      * don't recreate until a future explicit call to
233      * {@link Context#startService Context.startService(Intent)}.  The
234      * service will not receive a {@link #onStartCommand(Intent, int, int)}
235      * call with a null Intent because it will not be re-started if there
236      * are no pending Intents to deliver.
237      *
238      * <p>This mode makes sense for things that want to do some work as a
239      * result of being started, but can be stopped when under memory pressure
240      * and will explicit start themselves again later to do more work.  An
241      * example of such a service would be one that polls for data from
242      * a server: it could schedule an alarm to poll every N minutes by having
243      * the alarm start its service.  When its {@link #onStartCommand} is
244      * called from the alarm, it schedules a new alarm for N minutes later,
245      * and spawns a thread to do its networking.  If its process is killed
246      * while doing that check, the service will not be restarted until the
247      * alarm goes off.
248      */
249     public static final int START_NOT_STICKY = 2;
250 
251     /**
252      * Constant to return from {@link #onStartCommand}: if this service's
253      * process is killed while it is started (after returning from
254      * {@link #onStartCommand}), then it will be scheduled for a restart
255      * and the last delivered Intent re-delivered to it again via
256      * {@link #onStartCommand}.  This Intent will remain scheduled for
257      * redelivery until the service calls {@link #stopSelf(int)} with the
258      * start ID provided to {@link #onStartCommand}.  The
259      * service will not receive a {@link #onStartCommand(Intent, int, int)}
260      * call with a null Intent because it will will only be re-started if
261      * it is not finished processing all Intents sent to it (and any such
262      * pending events will be delivered at the point of restart).
263      */
264     public static final int START_REDELIVER_INTENT = 3;
265 
266     /**
267      * This flag is set in {@link #onStartCommand} if the Intent is a
268      * re-delivery of a previously delivered intent, because the service
269      * had previously returned {@link #START_REDELIVER_INTENT} but had been
270      * killed before calling {@link #stopSelf(int)} for that Intent.
271      */
272     public static final int START_FLAG_REDELIVERY = 0x0001;
273 
274     /**
275      * This flag is set in {@link #onStartCommand} if the Intent is a
276      * a retry because the original attempt never got to or returned from
277      * {@link #onStartCommand(Intent, int, int)}.
278      */
279     public static final int START_FLAG_RETRY = 0x0002;
280 
281     /**
282      * Called by the system every time a client explicitly starts the service by calling
283      * {@link android.content.Context#startService}, providing the arguments it supplied and a
284      * unique integer token representing the start request.  Do not call this method directly.
285      *
286      * <p>For backwards compatibility, the default implementation calls
287      * {@link #onStart} and returns either {@link #START_STICKY}
288      * or {@link #START_STICKY_COMPATIBILITY}.
289      *
290      * @param intent The Intent supplied to {@link android.content.Context#startService},
291      * as given.  This may be null if the service is being restarted after
292      * its process has gone away, and it had previously returned anything
293      * except {@link #START_STICKY_COMPATIBILITY}.
294      * @param flags Additional data about this start request.  Currently either
295      * 0, {@link #START_FLAG_REDELIVERY}, or {@link #START_FLAG_RETRY}.
296      * @param startId A unique integer representing this specific request to
297      * start.  Use with {@link #stopSelfResult(int)}.
298      *
299      * @return The return value indicates what semantics the system should
300      * use for the service's current started state.  It may be one of the
301      * constants associated with the {@link #START_CONTINUATION_MASK} bits.
302      *
303      * @see #stopSelfResult(int)
304      */
onStartCommand(Intent intent, int flags, int startId)305     public int onStartCommand(Intent intent, int flags, int startId) {
306         onStart(intent, startId);
307         return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
308     }
309 
310     /**
311      * Called by the system to notify a Service that it is no longer used and is being removed.  The
312      * service should clean up an resources it holds (threads, registered
313      * receivers, etc) at this point.  Upon return, there will be no more calls
314      * in to this Service object and it is effectively dead.  Do not call this method directly.
315      */
onDestroy()316     public void onDestroy() {
317     }
318 
onConfigurationChanged(Configuration newConfig)319     public void onConfigurationChanged(Configuration newConfig) {
320     }
321 
onLowMemory()322     public void onLowMemory() {
323     }
324 
325     /**
326      * Return the communication channel to the service.  May return null if
327      * clients can not bind to the service.  The returned
328      * {@link android.os.IBinder} is usually for a complex interface
329      * that has been <a href="{@docRoot}guide/developing/tools/aidl.html">described using
330      * aidl</a>.
331      *
332      * <p><em>Note that unlike other application components, calls on to the
333      * IBinder interface returned here may not happen on the main thread
334      * of the process</em>.  More information about this can be found
335      * in <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
336      * Processes and Threads</a>.</p>
337      *
338      * @param intent The Intent that was used to bind to this service,
339      * as given to {@link android.content.Context#bindService
340      * Context.bindService}.  Note that any extras that were included with
341      * the Intent at that point will <em>not</em> be seen here.
342      *
343      * @return Return an IBinder through which clients can call on to the
344      *         service.
345      */
onBind(Intent intent)346     public abstract IBinder onBind(Intent intent);
347 
348     /**
349      * Called when all clients have disconnected from a particular interface
350      * published by the service.  The default implementation does nothing and
351      * returns false.
352      *
353      * @param intent The Intent that was used to bind to this service,
354      * as given to {@link android.content.Context#bindService
355      * Context.bindService}.  Note that any extras that were included with
356      * the Intent at that point will <em>not</em> be seen here.
357      *
358      * @return Return true if you would like to have the service's
359      * {@link #onRebind} method later called when new clients bind to it.
360      */
onUnbind(Intent intent)361     public boolean onUnbind(Intent intent) {
362         return false;
363     }
364 
365     /**
366      * Called when new clients have connected to the service, after it had
367      * previously been notified that all had disconnected in its
368      * {@link #onUnbind}.  This will only be called if the implementation
369      * of {@link #onUnbind} was overridden to return true.
370      *
371      * @param intent The Intent that was used to bind to this service,
372      * as given to {@link android.content.Context#bindService
373      * Context.bindService}.  Note that any extras that were included with
374      * the Intent at that point will <em>not</em> be seen here.
375      */
onRebind(Intent intent)376     public void onRebind(Intent intent) {
377     }
378 
379     /**
380      * Stop the service, if it was previously started.  This is the same as
381      * calling {@link android.content.Context#stopService} for this particular service.
382      *
383      * @see #stopSelfResult(int)
384      */
stopSelf()385     public final void stopSelf() {
386         stopSelf(-1);
387     }
388 
389     /**
390      * Old version of {@link #stopSelfResult} that doesn't return a result.
391      *
392      * @see #stopSelfResult
393      */
stopSelf(int startId)394     public final void stopSelf(int startId) {
395         if (mActivityManager == null) {
396             return;
397         }
398         try {
399             mActivityManager.stopServiceToken(
400                     new ComponentName(this, mClassName), mToken, startId);
401         } catch (RemoteException ex) {
402         }
403     }
404 
405     /**
406      * Stop the service if the most recent time it was started was
407      * <var>startId</var>.  This is the same as calling {@link
408      * android.content.Context#stopService} for this particular service but allows you to
409      * safely avoid stopping if there is a start request from a client that you
410      * haven't yet seen in {@link #onStart}.
411      *
412      * <p><em>Be careful about ordering of your calls to this function.</em>.
413      * If you call this function with the most-recently received ID before
414      * you have called it for previously received IDs, the service will be
415      * immediately stopped anyway.  If you may end up processing IDs out
416      * of order (such as by dispatching them on separate threads), then you
417      * are responsible for stopping them in the same order you received them.</p>
418      *
419      * @param startId The most recent start identifier received in {@link
420      *                #onStart}.
421      * @return Returns true if the startId matches the last start request
422      * and the service will be stopped, else false.
423      *
424      * @see #stopSelf()
425      */
stopSelfResult(int startId)426     public final boolean stopSelfResult(int startId) {
427         if (mActivityManager == null) {
428             return false;
429         }
430         try {
431             return mActivityManager.stopServiceToken(
432                     new ComponentName(this, mClassName), mToken, startId);
433         } catch (RemoteException ex) {
434         }
435         return false;
436     }
437 
438     /**
439      * @deprecated This is a now a no-op, use
440      * {@link #startForeground(int, Notification)} instead.  This method
441      * has been turned into a no-op rather than simply being deprecated
442      * because analysis of numerous poorly behaving devices has shown that
443      * increasingly often the trouble is being caused in part by applications
444      * that are abusing it.  Thus, given a choice between introducing
445      * problems in existing applications using this API (by allowing them to
446      * be killed when they would like to avoid it), vs allowing the performance
447      * of the entire system to be decreased, this method was deemed less
448      * important.
449      */
450     @Deprecated
setForeground(boolean isForeground)451     public final void setForeground(boolean isForeground) {
452         Log.w(TAG, "setForeground: ignoring old API call on " + getClass().getName());
453     }
454 
455     /**
456      * Make this service run in the foreground, supplying the ongoing
457      * notification to be shown to the user while in this state.
458      * By default services are background, meaning that if the system needs to
459      * kill them to reclaim more memory (such as to display a large page in a
460      * web browser), they can be killed without too much harm.  You can set this
461      * flag if killing your service would be disruptive to the user, such as
462      * if your service is performing background music playback, so the user
463      * would notice if their music stopped playing.
464      *
465      * @param id The identifier for this notification as per
466      * {@link NotificationManager#notify(int, Notification)
467      * NotificationManager.notify(int, Notification)}.
468      * @param notification The Notification to be displayed.
469      *
470      * @see #stopForeground(boolean)
471      */
startForeground(int id, Notification notification)472     public final void startForeground(int id, Notification notification) {
473         try {
474             mActivityManager.setServiceForeground(
475                     new ComponentName(this, mClassName), mToken, id,
476                     notification, true);
477         } catch (RemoteException ex) {
478         }
479     }
480 
481     /**
482      * Remove this service from foreground state, allowing it to be killed if
483      * more memory is needed.
484      * @param removeNotification If true, the notification previously provided
485      * to {@link #startForeground} will be removed.  Otherwise it will remain
486      * until a later call removes it (or the service is destroyed).
487      * @see #startForeground(int, Notification)
488      */
stopForeground(boolean removeNotification)489     public final void stopForeground(boolean removeNotification) {
490         try {
491             mActivityManager.setServiceForeground(
492                     new ComponentName(this, mClassName), mToken, 0, null,
493                     removeNotification);
494         } catch (RemoteException ex) {
495         }
496     }
497 
498     /**
499      * Print the Service's state into the given stream.  This gets invoked if
500      * you run "adb shell dumpsys activity service <yourservicename>".
501      * This is distinct from "dumpsys <servicename>", which only works for
502      * named system services and which invokes the {@link IBinder#dump} method
503      * on the {@link IBinder} interface registered with ServiceManager.
504      *
505      * @param fd The raw file descriptor that the dump is being sent to.
506      * @param writer The PrintWriter to which you should dump your state.  This will be
507      * closed for you after you return.
508      * @param args additional arguments to the dump request.
509      */
dump(FileDescriptor fd, PrintWriter writer, String[] args)510     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
511         writer.println("nothing to dump");
512     }
513 
514     @Override
finalize()515     protected void finalize() throws Throwable {
516         super.finalize();
517         //Log.i("Service", "Finalizing Service: " + this);
518     }
519 
520     // ------------------ Internal API ------------------
521 
522     /**
523      * @hide
524      */
attach( Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager)525     public final void attach(
526             Context context,
527             ActivityThread thread, String className, IBinder token,
528             Application application, Object activityManager) {
529         attachBaseContext(context);
530         mThread = thread;           // NOTE:  unused - remove?
531         mClassName = className;
532         mToken = token;
533         mApplication = application;
534         mActivityManager = (IActivityManager)activityManager;
535         mStartCompatibility = getApplicationInfo().targetSdkVersion
536                 < Build.VERSION_CODES.ECLAIR;
537     }
538 
539     final String getClassName() {
540         return mClassName;
541     }
542 
543     // set by the thread after the constructor and before onCreate(Bundle icicle) is called.
544     private ActivityThread mThread = null;
545     private String mClassName = null;
546     private IBinder mToken = null;
547     private Application mApplication = null;
548     private IActivityManager mActivityManager = null;
549     private boolean mStartCompatibility = false;
550 }
551