BroadcastReceiver.java revision a34df8a2ba450b2c2ad83ccbbac30b80e2706bb2
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.content;
18
19import android.app.ActivityManagerNative;
20import android.app.IActivityManager;
21import android.os.Bundle;
22import android.os.IBinder;
23import android.os.RemoteException;
24import android.util.Log;
25
26/**
27 * Base class for code that will receive intents sent by sendBroadcast().
28 * You can either dynamically register an instance of this class with
29 * {@link Context#registerReceiver Context.registerReceiver()}
30 * or statically publish an implementation through the
31 * {@link android.R.styleable#AndroidManifestReceiver <receiver>}
32 * tag in your <code>AndroidManifest.xml</code>. <em><strong>Note:</strong></em>
33 * &nbsp;&nbsp;&nbsp;If registering a receiver in your
34 * {@link android.app.Activity#onResume() Activity.onResume()}
35 * implementation, you should unregister it in
36 * {@link android.app.Activity#onPause() Activity.onPause()}.
37 * (You won't receive intents when paused,
38 * and this will cut down on unnecessary system overhead). Do not unregister in
39 * {@link android.app.Activity#onSaveInstanceState(android.os.Bundle) Activity.onSaveInstanceState()},
40 * because this won't be called if the user moves back in the history
41 * stack.
42 *
43 * <p>There are two major classes of broadcasts that can be received:</p>
44 * <ul>
45 * <li> <b>Normal broadcasts</b> (sent with {@link Context#sendBroadcast(Intent)
46 * Context.sendBroadcast}) are completely asynchronous.  All receivers of the
47 * broadcast are run in an undefined order, often at the same time.  This is
48 * more efficient, but means that receivers cannot use the result or abort
49 * APIs included here.
50 * <li> <b>Ordered broadcasts</b> (sent with {@link Context#sendOrderedBroadcast(Intent, String)
51 * Context.sendOrderedBroadcast}) are delivered to one receiver at a time.
52 * As each receiver executes in turn, it can propagate a result to the next
53 * receiver, or it can completely abort the broadcast so that it won't be passed
54 * to other receivers.  The order receivers run in can be controlled with the
55 * {@link android.R.styleable#AndroidManifestIntentFilter_priority
56 * android:priority} attribute of the matching intent-filter; receivers with
57 * the same priority will be run in an arbitrary order.
58 * </ul>
59 *
60 * <p>Even in the case of normal broadcasts, the system may in some
61 * situations revert to delivering the broadcast one receiver at a time.  In
62 * particular, for receivers that may require the creation of a process, only
63 * one will be run at a time to avoid overloading the system with new processes.
64 * In this situation, however, the non-ordered semantics hold: these receivers still
65 * cannot return results or abort their broadcast.</p>
66 *
67 * <p>Note that, although the Intent class is used for sending and receiving
68 * these broadcasts, the Intent broadcast mechanism here is completely separate
69 * from Intents that are used to start Activities with
70 * {@link Context#startActivity Context.startActivity()}.
71 * There is no way for a BroadcastReceiver
72 * to see or capture Intents used with startActivity(); likewise, when
73 * you broadcast an Intent, you will never find or start an Activity.
74 * These two operations are semantically very different: starting an
75 * Activity with an Intent is a foreground operation that modifies what the
76 * user is currently interacting with; broadcasting an Intent is a background
77 * operation that the user is not normally aware of.
78 *
79 * <p>The BroadcastReceiver class (when launched as a component through
80 * a manifest's {@link android.R.styleable#AndroidManifestReceiver &lt;receiver&gt;}
81 * tag) is an important part of an
82 * <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">application's overall lifecycle</a>.</p>
83 *
84 * <p>Topics covered here:
85 * <ol>
86 * <li><a href="#ReceiverLifecycle">Receiver Lifecycle</a>
87 * <li><a href="#Permissions">Permissions</a>
88 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
89 * </ol>
90 *
91 * <a name="ReceiverLifecycle"></a>
92 * <h3>Receiver Lifecycle</h3>
93 *
94 * <p>A BroadcastReceiver object is only valid for the duration of the call
95 * to {@link #onReceive}.  Once your code returns from this function,
96 * the system considers the object to be finished and no longer active.
97 *
98 * <p>This has important repercussions to what you can do in an
99 * {@link #onReceive} implementation: anything that requires asynchronous
100 * operation is not available, because you will need to return from the
101 * function to handle the asynchronous operation, but at that point the
102 * BroadcastReceiver is no longer active and thus the system is free to kill
103 * its process before the asynchronous operation completes.
104 *
105 * <p>In particular, you may <i>not</i> show a dialog or bind to a service from
106 * within a BroadcastReceiver.  For the former, you should instead use the
107 * {@link android.app.NotificationManager} API.  For the latter, you can
108 * use {@link android.content.Context#startService Context.startService()} to
109 * send a command to the service.
110 *
111 * <a name="Permissions"></a>
112 * <h3>Permissions</h3>
113 *
114 * <p>Access permissions can be enforced by either the sender or receiver
115 * of an Intent.
116 *
117 * <p>To enforce a permission when sending, you supply a non-null
118 * <var>permission</var> argument to
119 * {@link Context#sendBroadcast(Intent, String)} or
120 * {@link Context#sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler, int, String, Bundle)}.
121 * Only receivers who have been granted this permission
122 * (by requesting it with the
123 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
124 * tag in their <code>AndroidManifest.xml</code>) will be able to receive
125 * the broadcast.
126 *
127 * <p>To enforce a permission when receiving, you supply a non-null
128 * <var>permission</var> when registering your receiver -- either when calling
129 * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter, String, android.os.Handler)}
130 * or in the static
131 * {@link android.R.styleable#AndroidManifestReceiver &lt;receiver&gt;}
132 * tag in your <code>AndroidManifest.xml</code>.  Only broadcasters who have
133 * been granted this permission (by requesting it with the
134 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
135 * tag in their <code>AndroidManifest.xml</code>) will be able to send an
136 * Intent to the receiver.
137 *
138 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
139 * document for more information on permissions and security in general.
140 *
141 * <a name="ProcessLifecycle"></a>
142 * <h3>Process Lifecycle</h3>
143 *
144 * <p>A process that is currently executing a BroadcastReceiver (that is,
145 * currently running the code in its {@link #onReceive} method) is
146 * considered to be a foreground process and will be kept running by the
147 * system except under cases of extreme memory pressure.
148 *
149 * <p>Once you return from onReceive(), the BroadcastReceiver is no longer
150 * active, and its hosting process is only as important as any other application
151 * components that are running in it.  This is especially important because if
152 * that process was only hosting the BroadcastReceiver (a common case for
153 * applications that the user has never or not recently interacted with), then
154 * upon returning from onReceive() the system will consider its process
155 * to be empty and aggressively kill it so that resources are available for other
156 * more important processes.
157 *
158 * <p>This means that for longer-running operations you will often use
159 * a {@link android.app.Service} in conjunction with a BroadcastReceiver to keep
160 * the containing process active for the entire time of your operation.
161 */
162public abstract class BroadcastReceiver {
163    public BroadcastReceiver() {
164    }
165
166    /**
167     * This method is called when the BroadcastReceiver is receiving an Intent
168     * broadcast.  During this time you can use the other methods on
169     * BroadcastReceiver to view/modify the current result values.  The function
170     * is normally called within the main thread of its process, so you should
171     * never perform long-running operations in it (there is a timeout of
172     * 10 seconds that the system allows before considering the receiver to
173     * be blocked and a candidate to be killed). You cannot launch a popup dialog
174     * in your implementation of onReceive().
175     *
176     * <p><b>If this BroadcastReceiver was launched through a &lt;receiver&gt; tag,
177     * then the object is no longer alive after returning from this
178     * function.</b>  This means you should not perform any operations that
179     * return a result to you asynchronously -- in particular, for interacting
180     * with services, you should use
181     * {@link Context#startService(Intent)} instead of
182     * {@link Context#bindService(Intent, ServiceConnection, int)}.  If you wish
183     * to interact with a service that is already running, you can use
184     * {@link #peekService}.
185     *
186     * <p>The Intent filters used in {@link android.content.Context#registerReceiver}
187     * and in application manifests are <em>not</em> guaranteed to be exclusive. They
188     * are hints to the operating system about how to find suitable recipients. It is
189     * possible for senders to force delivery to specific recipients, bypassing filter
190     * resolution.  For this reason, {@link #onReceive(Context, Intent) onReceive()}
191     * implementations should respond only to known actions, ignoring any unexpected
192     * Intents that they may receive.
193     *
194     * @param context The Context in which the receiver is running.
195     * @param intent The Intent being received.
196     */
197    public abstract void onReceive(Context context, Intent intent);
198
199    /**
200     * Provide a binder to an already-running service.  This method is synchronous
201     * and will not start the target service if it is not present, so it is safe
202     * to call from {@link #onReceive}.
203     *
204     * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)}
205     * @param service The Intent indicating the service you wish to use.  See {@link
206     * Context#startService(Intent)} for more information.
207     */
208    public IBinder peekService(Context myContext, Intent service) {
209        IActivityManager am = ActivityManagerNative.getDefault();
210        IBinder binder = null;
211        try {
212            binder = am.peekService(service, service.resolveTypeIfNeeded(
213                    myContext.getContentResolver()));
214        } catch (RemoteException e) {
215        }
216        return binder;
217    }
218
219    /**
220     * Change the current result code of this broadcast; only works with
221     * broadcasts sent through
222     * {@link Context#sendOrderedBroadcast(Intent, String)
223     * Context.sendOrderedBroadcast}.  Often uses the
224     * Activity {@link android.app.Activity#RESULT_CANCELED} and
225     * {@link android.app.Activity#RESULT_OK} constants, though the
226     * actual meaning of this value is ultimately up to the broadcaster.
227     *
228     * <p><strong>This method does not work with non-ordered broadcasts such
229     * as those sent with {@link Context#sendBroadcast(Intent)
230     * Context.sendBroadcast}</strong></p>
231     *
232     * @param code The new result code.
233     *
234     * @see #setResult(int, String, Bundle)
235     */
236    public final void setResultCode(int code) {
237        checkSynchronousHint();
238        mResultCode = code;
239    }
240
241    /**
242     * Retrieve the current result code, as set by the previous receiver.
243     *
244     * @return int The current result code.
245     */
246    public final int getResultCode() {
247        return mResultCode;
248    }
249
250    /**
251     * Change the current result data of this broadcast; only works with
252     * broadcasts sent through
253     * {@link Context#sendOrderedBroadcast(Intent, String)
254     * Context.sendOrderedBroadcast}.  This is an arbitrary
255     * string whose interpretation is up to the broadcaster.
256     *
257     * <p><strong>This method does not work with non-ordered broadcasts such
258     * as those sent with {@link Context#sendBroadcast(Intent)
259     * Context.sendBroadcast}</strong></p>
260     *
261     * @param data The new result data; may be null.
262     *
263     * @see #setResult(int, String, Bundle)
264     */
265    public final void setResultData(String data) {
266        checkSynchronousHint();
267        mResultData = data;
268    }
269
270    /**
271     * Retrieve the current result data, as set by the previous receiver.
272     * Often this is null.
273     *
274     * @return String The current result data; may be null.
275     */
276    public final String getResultData() {
277        return mResultData;
278    }
279
280    /**
281     * Change the current result extras of this broadcast; only works with
282     * broadcasts sent through
283     * {@link Context#sendOrderedBroadcast(Intent, String)
284     * Context.sendOrderedBroadcast}.  This is a Bundle
285     * holding arbitrary data, whose interpretation is up to the
286     * broadcaster.  Can be set to null.  Calling this method completely
287     * replaces the current map (if any).
288     *
289     * <p><strong>This method does not work with non-ordered broadcasts such
290     * as those sent with {@link Context#sendBroadcast(Intent)
291     * Context.sendBroadcast}</strong></p>
292     *
293     * @param extras The new extra data map; may be null.
294     *
295     * @see #setResult(int, String, Bundle)
296     */
297    public final void setResultExtras(Bundle extras) {
298        checkSynchronousHint();
299        mResultExtras = extras;
300    }
301
302    /**
303     * Retrieve the current result extra data, as set by the previous receiver.
304     * Any changes you make to the returned Map will be propagated to the next
305     * receiver.
306     *
307     * @param makeMap If true then a new empty Map will be made for you if the
308     *                current Map is null; if false you should be prepared to
309     *                receive a null Map.
310     *
311     * @return Map The current extras map.
312     */
313    public final Bundle getResultExtras(boolean makeMap) {
314        Bundle e = mResultExtras;
315        if (!makeMap) return e;
316        if (e == null) mResultExtras = e = new Bundle();
317        return e;
318    }
319
320    /**
321     * Change all of the result data returned from this broadcasts; only works
322     * with broadcasts sent through
323     * {@link Context#sendOrderedBroadcast(Intent, String)
324     * Context.sendOrderedBroadcast}.  All current result data is replaced
325     * by the value given to this method.
326     *
327     * <p><strong>This method does not work with non-ordered broadcasts such
328     * as those sent with {@link Context#sendBroadcast(Intent)
329     * Context.sendBroadcast}</strong></p>
330     *
331     * @param code The new result code.  Often uses the
332     * Activity {@link android.app.Activity#RESULT_CANCELED} and
333     * {@link android.app.Activity#RESULT_OK} constants, though the
334     * actual meaning of this value is ultimately up to the broadcaster.
335     * @param data The new result data.  This is an arbitrary
336     * string whose interpretation is up to the broadcaster; may be null.
337     * @param extras The new extra data map.  This is a Bundle
338     * holding arbitrary data, whose interpretation is up to the
339     * broadcaster.  Can be set to null.  This completely
340     * replaces the current map (if any).
341     */
342    public final void setResult(int code, String data, Bundle extras) {
343        checkSynchronousHint();
344        mResultCode = code;
345        mResultData = data;
346        mResultExtras = extras;
347    }
348
349    /**
350     * Returns the flag indicating whether or not this receiver should
351     * abort the current broadcast.
352     *
353     * @return True if the broadcast should be aborted.
354     */
355    public final boolean getAbortBroadcast() {
356        return mAbortBroadcast;
357    }
358
359    /**
360     * Sets the flag indicating that this receiver should abort the
361     * current broadcast; only works with broadcasts sent through
362     * {@link Context#sendOrderedBroadcast(Intent, String)
363     * Context.sendOrderedBroadcast}.  This will prevent
364     * any other broadcast receivers from receiving the broadcast. It will still
365     * call {@link #onReceive} of the BroadcastReceiver that the caller of
366     * {@link Context#sendOrderedBroadcast(Intent, String)
367     * Context.sendOrderedBroadcast} passed in.
368     *
369     * <p><strong>This method does not work with non-ordered broadcasts such
370     * as those sent with {@link Context#sendBroadcast(Intent)
371     * Context.sendBroadcast}</strong></p>
372     */
373    public final void abortBroadcast() {
374        checkSynchronousHint();
375        mAbortBroadcast = true;
376    }
377
378    /**
379     * Clears the flag indicating that this receiver should abort the current
380     * broadcast.
381     */
382    public final void clearAbortBroadcast() {
383        mAbortBroadcast = false;
384    }
385
386    /**
387     * For internal use, sets the hint about whether this BroadcastReceiver is
388     * running in ordered mode.
389     */
390    public final void setOrderedHint(boolean isOrdered) {
391        mOrderedHint = isOrdered;
392    }
393
394    /**
395     * Control inclusion of debugging help for mismatched
396     * calls to {@ Context#registerReceiver(BroadcastReceiver, IntentFilter)
397     * Context.registerReceiver()}.
398     * If called with true, before given to registerReceiver(), then the
399     * callstack of the following {@link Context#unregisterReceiver(BroadcastReceiver)
400     * Context.unregisterReceiver()} call is retained, to be printed if a later
401     * incorrect unregister call is made.  Note that doing this requires retaining
402     * information about the BroadcastReceiver for the lifetime of the app,
403     * resulting in a leak -- this should only be used for debugging.
404     */
405    public final void setDebugUnregister(boolean debug) {
406        mDebugUnregister = debug;
407    }
408
409    /**
410     * Return the last value given to {@link #setDebugUnregister}.
411     */
412    public final boolean getDebugUnregister() {
413        return mDebugUnregister;
414    }
415
416    void checkSynchronousHint() {
417        if (mOrderedHint) {
418            return;
419        }
420        RuntimeException e = new RuntimeException(
421                "BroadcastReceiver trying to return result during a non-ordered broadcast");
422        e.fillInStackTrace();
423        Log.e("BroadcastReceiver", e.getMessage(), e);
424    }
425
426    private int mResultCode;
427    private String mResultData;
428    private Bundle mResultExtras;
429    private boolean mAbortBroadcast;
430    private boolean mDebugUnregister;
431    private boolean mOrderedHint;
432}
433
434