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
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;
25import android.os.RemoteException;
26import android.os.IBinder;
27
28import java.io.FileDescriptor;
29import java.io.PrintWriter;
30
31/**
32 * A Service is an application component that runs in the background, not
33 * interacting with the user, for an indefinite period of time.  Each service
34 * class must have a corresponding
35 * {@link android.R.styleable#AndroidManifestService <service>}
36 * declaration in its package's <code>AndroidManifest.xml</code>.  Services
37 * can be started with
38 * {@link android.content.Context#startService Context.startService()} and
39 * {@link android.content.Context#bindService Context.bindService()}.
40 *
41 * <p>Note that services, like other application objects, run in the main
42 * thread of their hosting process.  This means that, if your service is going
43 * to do any CPU intensive (such as MP3 playback) or blocking (such as
44 * networking) operations, it should spawn its own thread in which to do that
45 * work.  More information on this can be found in
46 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
47 * Processes and Threads</a>.</p>
48 *
49 * <p>The Service class is an important part of an
50 * <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">application's overall lifecycle</a>.</p>
51 *
52 * <p>Topics covered here:
53 * <ol>
54 * <li><a href="#ServiceLifecycle">Service Lifecycle</a>
55 * <li><a href="#Permissions">Permissions</a>
56 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
57 * </ol>
58 *
59 * <a name="ServiceLifecycle"></a>
60 * <h3>Service Lifecycle</h3>
61 *
62 * <p>There are two reasons that a service can be run by the system.  If someone
63 * calls {@link android.content.Context#startService Context.startService()} then the system will
64 * retrieve the service (creating it and calling its {@link #onCreate} method
65 * if needed) and then call its {@link #onStart} method with the
66 * arguments supplied by the client.  The service will at this point continue
67 * running until {@link android.content.Context#stopService Context.stopService()} or
68 * {@link #stopSelf()} is called.  Note that multiple calls to
69 * Context.startService() do not nest (though they do result in multiple corresponding
70 * calls to onStart()), so no matter how many times it is started a service
71 * will be stopped once Context.stopService() or stopSelf() is called.
72 *
73 * <p>Clients can also use {@link android.content.Context#bindService Context.bindService()} to
74 * obtain a persistent connection to a service.  This likewise creates the
75 * service if it is not already running (calling {@link #onCreate} while
76 * doing so), but does not call onStart().  The client will receive the
77 * {@link android.os.IBinder} object that the service returns from its
78 * {@link #onBind} method, allowing the client to then make calls back
79 * to the service.  The service will remain running as long as the connection
80 * is established (whether or not the client retains a reference on the
81 * service's IBinder).  Usually the IBinder returned is for a complex
82 * interface that has been <a href="{@docRoot}guide/developing/tools/aidl.html">written
83 * in aidl</a>.
84 *
85 * <p>A service can be both started and have connections bound to it.  In such
86 * a case, the system will keep the service running as long as either it is
87 * started <em>or</em> there are one or more connections to it with the
88 * {@link android.content.Context#BIND_AUTO_CREATE Context.BIND_AUTO_CREATE}
89 * flag.  Once neither
90 * of these situations hold, the service's {@link #onDestroy} method is called
91 * and the service is effectively terminated.  All cleanup (stopping threads,
92 * unregistering receivers) should be complete upon returning from onDestroy().
93 *
94 * <a name="Permissions"></a>
95 * <h3>Permissions</h3>
96 *
97 * <p>Global access to a service can be enforced when it is declared in its
98 * manifest's {@link android.R.styleable#AndroidManifestService &lt;service&gt;}
99 * tag.  By doing so, other applications will need to declare a corresponding
100 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
101 * element in their own manifest to be able to start, stop, or bind to
102 * the service.
103 *
104 * <p>In addition, a service can protect individual IPC calls into it with
105 * permissions, by calling the
106 * {@link #checkCallingPermission}
107 * method before executing the implementation of that call.
108 *
109 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
110 * document for more information on permissions and security in general.
111 *
112 * <a name="ProcessLifecycle"></a>
113 * <h3>Process Lifecycle</h3>
114 *
115 * <p>The Android system will attempt to keep the process hosting a service
116 * around as long as the service has been started or has clients bound to it.
117 * When running low on memory and needing to kill existing processes, the
118 * priority of a process hosting the service will be the higher of the
119 * following possibilities:
120 *
121 * <ul>
122 * <li><p>If the service is currently executing code in its
123 * {@link #onCreate onCreate()}, {@link #onStart onStart()},
124 * or {@link #onDestroy onDestroy()} methods, then the hosting process will
125 * be a foreground process to ensure this code can execute without
126 * being killed.
127 * <li><p>If the service has been started, then its hosting process is considered
128 * to be less important than any processes that are currently visible to the
129 * user on-screen, but more important than any process not visible.  Because
130 * only a few processes are generally visible to the user, this means that
131 * the service should not be killed except in extreme low memory conditions.
132 * <li><p>If there are clients bound to the service, then the service's hosting
133 * process is never less important than the most important client.  That is,
134 * if one of its clients is visible to the user, then the service itself is
135 * considered to be visible.
136 * </ul>
137 *
138 * <p>Note this means that most of the time your service is running, it may
139 * be killed by the system if it is under heavy memory pressure.  If this
140 * happens, the system will later try to restart the service.  An important
141 * consequence of this is that if you implement {@link #onStart onStart()}
142 * to schedule work to be done asynchronously or in another thread, then you
143 * may want to write information about that work into persistent storage
144 * during the onStart() call so that it does not get lost if the service later
145 * gets killed.
146 *
147 * <p>Other application components running in the same process as the service
148 * (such as an {@link android.app.Activity}) can, of course, increase the
149 * importance of the overall
150 * process beyond just the importance of the service itself.
151 */
152public abstract class Service extends ContextWrapper implements ComponentCallbacks {
153    private static final String TAG = "Service";
154
155    public Service() {
156        super(null);
157    }
158
159    /** Return the application that owns this service. */
160    public final Application getApplication() {
161        return mApplication;
162    }
163
164    /**
165     * Called by the system when the service is first created.  Do not call this method directly.
166     */
167    public void onCreate() {
168    }
169
170    /**
171     * Called by the system every time a client explicitly starts the service by calling
172     * {@link android.content.Context#startService}, providing the arguments it supplied and a
173     * unique integer token representing the start request.  Do not call this method directly.
174     *
175     * @param intent The Intent supplied to {@link android.content.Context#startService},
176     *                  as given.
177     * @param startId A unique integer representing this specific request to
178     *                start.  Use with {@link #stopSelfResult(int)}.
179     *
180     * @see #stopSelfResult(int)
181     */
182    public void onStart(Intent intent, int startId) {
183    }
184
185    /**
186     * Called by the system to notify a Service that it is no longer used and is being removed.  The
187     * service should clean up an resources it holds (threads, registered
188     * receivers, etc) at this point.  Upon return, there will be no more calls
189     * in to this Service object and it is effectively dead.  Do not call this method directly.
190     */
191    public void onDestroy() {
192    }
193
194    public void onConfigurationChanged(Configuration newConfig) {
195    }
196
197    public void onLowMemory() {
198    }
199
200    /**
201     * Return the communication channel to the service.  May return null if
202     * clients can not bind to the service.  The returned
203     * {@link android.os.IBinder} is usually for a complex interface
204     * that has been <a href="{@docRoot}guide/developing/tools/aidl.html">described using
205     * aidl</a>.
206     *
207     * <p><em>Note that unlike other application components, calls on to the
208     * IBinder interface returned here may not happen on the main thread
209     * of the process</em>.  More information about this can be found
210     * in <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
211     * Processes and Threads</a>.</p>
212     *
213     * @param intent The Intent that was used to bind to this service,
214     * as given to {@link android.content.Context#bindService
215     * Context.bindService}.  Note that any extras that were included with
216     * the Intent at that point will <em>not</em> be seen here.
217     *
218     * @return Return an IBinder through which clients can call on to the
219     *         service.
220     */
221    public abstract IBinder onBind(Intent intent);
222
223    /**
224     * Called when all clients have disconnected from a particular interface
225     * published by the service.  The default implementation does nothing and
226     * returns false.
227     *
228     * @param intent The Intent that was used to bind to this service,
229     * as given to {@link android.content.Context#bindService
230     * Context.bindService}.  Note that any extras that were included with
231     * the Intent at that point will <em>not</em> be seen here.
232     *
233     * @return Return true if you would like to have the service's
234     * {@link #onRebind} method later called when new clients bind to it.
235     */
236    public boolean onUnbind(Intent intent) {
237        return false;
238    }
239
240    /**
241     * Called when new clients have connected to the service, after it had
242     * previously been notified that all had disconnected in its
243     * {@link #onUnbind}.  This will only be called if the implementation
244     * of {@link #onUnbind} was overridden to return true.
245     *
246     * @param intent The Intent that was used to bind to this service,
247     * as given to {@link android.content.Context#bindService
248     * Context.bindService}.  Note that any extras that were included with
249     * the Intent at that point will <em>not</em> be seen here.
250     */
251    public void onRebind(Intent intent) {
252    }
253
254    /**
255     * Stop the service, if it was previously started.  This is the same as
256     * calling {@link android.content.Context#stopService} for this particular service.
257     *
258     * @see #stopSelfResult(int)
259     */
260    public final void stopSelf() {
261        stopSelf(-1);
262    }
263
264    /**
265     * Old version of {@link #stopSelfResult} that doesn't return a result.
266     *
267     * @see #stopSelfResult
268     */
269    public final void stopSelf(int startId) {
270        if (mActivityManager == null) {
271            return;
272        }
273        try {
274            mActivityManager.stopServiceToken(
275                    new ComponentName(this, mClassName), mToken, startId);
276        } catch (RemoteException ex) {
277        }
278    }
279
280    /**
281     * Stop the service if the most recent time it was started was
282     * <var>startId</var>.  This is the same as calling {@link
283     * android.content.Context#stopService} for this particular service but allows you to
284     * safely avoid stopping if there is a start request from a client that you
285     * haven't yet seen in {@link #onStart}.
286     *
287     * @param startId The most recent start identifier received in {@link
288     *                #onStart}.
289     * @return Returns true if the startId matches the last start request
290     * and the service will be stopped, else false.
291     *
292     * @see #stopSelf()
293     */
294    public final boolean stopSelfResult(int startId) {
295        if (mActivityManager == null) {
296            return false;
297        }
298        try {
299            return mActivityManager.stopServiceToken(
300                    new ComponentName(this, mClassName), mToken, startId);
301        } catch (RemoteException ex) {
302        }
303        return false;
304    }
305
306    /**
307     * Control whether this service is considered to be a foreground service.
308     * By default services are background, meaning that if the system needs to
309     * kill them to reclaim more memory (such as to display a large page in a
310     * web browser), they can be killed without too much harm.  You can set this
311     * flag if killing your service would be disruptive to the user: such as
312     * if your service is performing background music playback, so the user
313     * would notice if their music stopped playing.
314     *
315     * @param isForeground Determines whether this service is considered to
316     * be foreground (true) or background (false).
317     */
318    public final void setForeground(boolean isForeground) {
319        if (mActivityManager == null) {
320            return;
321        }
322        try {
323            mActivityManager.setServiceForeground(
324                    new ComponentName(this, mClassName), mToken, isForeground);
325        } catch (RemoteException ex) {
326        }
327    }
328
329    /**
330     * Print the Service's state into the given stream.  This gets invoked if
331     * you run "adb shell dumpsys activity service <yourservicename>".
332     * This is distinct from "dumpsys <servicename>", which only works for
333     * named system services and which invokes the {@link IBinder#dump} method
334     * on the {@link IBinder} interface registered with ServiceManager.
335     *
336     * @param fd The raw file descriptor that the dump is being sent to.
337     * @param writer The PrintWriter to which you should dump your state.  This will be
338     * closed for you after you return.
339     * @param args additional arguments to the dump request.
340     */
341    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
342        writer.println("nothing to dump");
343    }
344
345    @Override
346    protected void finalize() throws Throwable {
347        super.finalize();
348        //Log.i("Service", "Finalizing Service: " + this);
349    }
350
351    // ------------------ Internal API ------------------
352
353    /**
354     * @hide
355     */
356    public final void attach(
357            Context context,
358            ActivityThread thread, String className, IBinder token,
359            Application application, Object activityManager) {
360        attachBaseContext(context);
361        mThread = thread;           // NOTE:  unused - remove?
362        mClassName = className;
363        mToken = token;
364        mApplication = application;
365        mActivityManager = (IActivityManager)activityManager;
366    }
367
368    final String getClassName() {
369        return mClassName;
370    }
371
372    // set by the thread after the constructor and before onCreate(Bundle icicle) is called.
373    private ActivityThread mThread = null;
374    private String mClassName = null;
375    private IBinder mToken = null;
376    private Application mApplication = null;
377    private IActivityManager mActivityManager = null;
378}
379