BroadcastReceiver.java revision 9066cfe9886ac131c34d59ed0e2d287b0e3c0087
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 * 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 can not 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 runs 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 65 * can not 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 an 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 <receiver>} 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 an 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 <uses-permission>} 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 <receiver>} 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 <uses-permission>} 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 an 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 an 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 from 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 <receiver> 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 * @param context The Context in which the receiver is running. 187 * @param intent The Intent being received. 188 */ 189 public abstract void onReceive(Context context, Intent intent); 190 191 /** 192 * Provide a binder to an already-running service. This method is synchronous 193 * and will not start the target service if it is not present, so it is safe 194 * to call from {@link #onReceive}. 195 * 196 * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)} 197 * @param service The Intent indicating the service you wish to use. See {@link 198 * Context#startService(Intent)} for more information. 199 */ 200 public IBinder peekService(Context myContext, Intent service) { 201 IActivityManager am = ActivityManagerNative.getDefault(); 202 IBinder binder = null; 203 try { 204 binder = am.peekService(service, service.resolveTypeIfNeeded( 205 myContext.getContentResolver())); 206 } catch (RemoteException e) { 207 } 208 return binder; 209 } 210 211 /** 212 * Change the current result code of this broadcast; only works with 213 * broadcasts sent through 214 * {@link Context#sendOrderedBroadcast(Intent, String) 215 * Context.sendOrderedBroadcast}. Often uses the 216 * Activity {@link android.app.Activity#RESULT_CANCELED} and 217 * {@link android.app.Activity#RESULT_OK} constants, though the 218 * actual meaning of this value is ultimately up to the broadcaster. 219 * 220 * <p><strong>This method does not work with non-ordered broadcasts such 221 * as those sent with {@link Context#sendBroadcast(Intent) 222 * Context.sendBroadcast}</strong></p> 223 * 224 * @param code The new result code. 225 * 226 * @see #setResult(int, String, Bundle) 227 */ 228 public final void setResultCode(int code) { 229 checkSynchronousHint(); 230 mResultCode = code; 231 } 232 233 /** 234 * Retrieve the current result code, as set by the previous receiver. 235 * 236 * @return int The current result code. 237 */ 238 public final int getResultCode() { 239 return mResultCode; 240 } 241 242 /** 243 * Change the current result data of this broadcast; only works with 244 * broadcasts sent through 245 * {@link Context#sendOrderedBroadcast(Intent, String) 246 * Context.sendOrderedBroadcast}. This is an arbitrary 247 * string whose interpretation is up to the broadcaster. 248 * 249 * <p><strong>This method does not work with non-ordered broadcasts such 250 * as those sent with {@link Context#sendBroadcast(Intent) 251 * Context.sendBroadcast}</strong></p> 252 * 253 * @param data The new result data; may be null. 254 * 255 * @see #setResult(int, String, Bundle) 256 */ 257 public final void setResultData(String data) { 258 checkSynchronousHint(); 259 mResultData = data; 260 } 261 262 /** 263 * Retrieve the current result data, as set by the previous receiver. 264 * Often this is null. 265 * 266 * @return String The current result data; may be null. 267 */ 268 public final String getResultData() { 269 return mResultData; 270 } 271 272 /** 273 * Change the current result extras of this broadcast; only works with 274 * broadcasts sent through 275 * {@link Context#sendOrderedBroadcast(Intent, String) 276 * Context.sendOrderedBroadcast}. This is a Bundle 277 * holding arbitrary data, whose interpretation is up to the 278 * broadcaster. Can be set to null. Calling this method completely 279 * replaces the current map (if any). 280 * 281 * <p><strong>This method does not work with non-ordered broadcasts such 282 * as those sent with {@link Context#sendBroadcast(Intent) 283 * Context.sendBroadcast}</strong></p> 284 * 285 * @param extras The new extra data map; may be null. 286 * 287 * @see #setResult(int, String, Bundle) 288 */ 289 public final void setResultExtras(Bundle extras) { 290 checkSynchronousHint(); 291 mResultExtras = extras; 292 } 293 294 /** 295 * Retrieve the current result extra data, as set by the previous receiver. 296 * Any changes you make to the returned Map will be propagated to the next 297 * receiver. 298 * 299 * @param makeMap If true then a new empty Map will be made for you if the 300 * current Map is null; if false you should be prepared to 301 * receive a null Map. 302 * 303 * @return Map The current extras map. 304 */ 305 public final Bundle getResultExtras(boolean makeMap) { 306 Bundle e = mResultExtras; 307 if (!makeMap) return e; 308 if (e == null) mResultExtras = e = new Bundle(); 309 return e; 310 } 311 312 /** 313 * Change all of the result data returned from this broadcasts; only works 314 * with broadcasts sent through 315 * {@link Context#sendOrderedBroadcast(Intent, String) 316 * Context.sendOrderedBroadcast}. All current result data is replaced 317 * by the value given to this method. 318 * 319 * <p><strong>This method does not work with non-ordered broadcasts such 320 * as those sent with {@link Context#sendBroadcast(Intent) 321 * Context.sendBroadcast}</strong></p> 322 * 323 * @param code The new result code. Often uses the 324 * Activity {@link android.app.Activity#RESULT_CANCELED} and 325 * {@link android.app.Activity#RESULT_OK} constants, though the 326 * actual meaning of this value is ultimately up to the broadcaster. 327 * @param data The new result data. This is an arbitrary 328 * string whose interpretation is up to the broadcaster; may be null. 329 * @param extras The new extra data map. This is a Bundle 330 * holding arbitrary data, whose interpretation is up to the 331 * broadcaster. Can be set to null. This completely 332 * replaces the current map (if any). 333 */ 334 public final void setResult(int code, String data, Bundle extras) { 335 checkSynchronousHint(); 336 mResultCode = code; 337 mResultData = data; 338 mResultExtras = extras; 339 } 340 341 /** 342 * Returns the flag indicating whether or not this receiver should 343 * abort the current broadcast. 344 * 345 * @return True if the broadcast should be aborted. 346 */ 347 public final boolean getAbortBroadcast() { 348 return mAbortBroadcast; 349 } 350 351 /** 352 * Sets the flag indicating that this receiver should abort the 353 * current broadcast; only works with broadcasts sent through 354 * {@link Context#sendOrderedBroadcast(Intent, String) 355 * Context.sendOrderedBroadcast}. This will prevent 356 * any other broadcast receivers from receiving the broadcast. It will still 357 * call {@link #onReceive} of the BroadcastReceiver that the caller of 358 * {@link Context#sendOrderedBroadcast(Intent, String) 359 * Context.sendOrderedBroadcast} passed in. 360 * 361 * <p><strong>This method does not work with non-ordered broadcasts such 362 * as those sent with {@link Context#sendBroadcast(Intent) 363 * Context.sendBroadcast}</strong></p> 364 */ 365 public final void abortBroadcast() { 366 checkSynchronousHint(); 367 mAbortBroadcast = true; 368 } 369 370 /** 371 * Clears the flag indicating that this receiver should abort the current 372 * broadcast. 373 */ 374 public final void clearAbortBroadcast() { 375 mAbortBroadcast = false; 376 } 377 378 /** 379 * For internal use, sets the hint about whether this BroadcastReceiver is 380 * running in ordered mode. 381 */ 382 public final void setOrderedHint(boolean isOrdered) { 383 mOrderedHint = isOrdered; 384 } 385 386 /** 387 * Control inclusion of debugging help for mismatched 388 * calls to {@ Context#registerReceiver(BroadcastReceiver, IntentFilter) 389 * Context.registerReceiver()}. 390 * If called with true, before given to registerReceiver(), then the 391 * callstack of the following {@link Context#unregisterReceiver(BroadcastReceiver) 392 * Context.unregisterReceiver()} call is retained, to be printed if a later 393 * incorrect unregister call is made. Note that doing this requires retaining 394 * information about the BroadcastReceiver for the lifetime of the app, 395 * resulting in a leak -- this should only be used for debugging. 396 */ 397 public final void setDebugUnregister(boolean debug) { 398 mDebugUnregister = debug; 399 } 400 401 /** 402 * Return the last value given to {@link #setDebugUnregister}. 403 */ 404 public final boolean getDebugUnregister() { 405 return mDebugUnregister; 406 } 407 408 void checkSynchronousHint() { 409 if (mOrderedHint) { 410 return; 411 } 412 RuntimeException e = new RuntimeException( 413 "BroadcastReceiver trying to return result during a non-ordered broadcast"); 414 e.fillInStackTrace(); 415 Log.e("BroadcastReceiver", e.getMessage(), e); 416 } 417 418 private int mResultCode; 419 private String mResultData; 420 private Bundle mResultExtras; 421 private boolean mAbortBroadcast; 422 private boolean mDebugUnregister; 423 private boolean mOrderedHint; 424} 425 426