Activity.java revision 7aee61f5a96e94e158bf5ad3d8e192c4d4f7eff6
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 com.android.internal.app.ActionBarImpl; 20import com.android.internal.policy.PolicyManager; 21 22import android.content.ComponentCallbacks; 23import android.content.ComponentName; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.CursorLoader; 27import android.content.IIntentSender; 28import android.content.Intent; 29import android.content.IntentSender; 30import android.content.SharedPreferences; 31import android.content.pm.ActivityInfo; 32import android.content.res.Configuration; 33import android.content.res.Resources; 34import android.content.res.TypedArray; 35import android.database.Cursor; 36import android.graphics.Bitmap; 37import android.graphics.Canvas; 38import android.graphics.drawable.Drawable; 39import android.media.AudioManager; 40import android.net.Uri; 41import android.os.Build; 42import android.os.Bundle; 43import android.os.Handler; 44import android.os.IBinder; 45import android.os.Looper; 46import android.os.Parcelable; 47import android.os.RemoteException; 48import android.os.StrictMode; 49import android.text.Selection; 50import android.text.SpannableStringBuilder; 51import android.text.TextUtils; 52import android.text.method.TextKeyListener; 53import android.util.AttributeSet; 54import android.util.Config; 55import android.util.EventLog; 56import android.util.Log; 57import android.util.SparseArray; 58import android.view.ActionMode; 59import android.view.ContextMenu; 60import android.view.ContextMenu.ContextMenuInfo; 61import android.view.ContextThemeWrapper; 62import android.view.KeyEvent; 63import android.view.LayoutInflater; 64import android.view.Menu; 65import android.view.MenuInflater; 66import android.view.MenuItem; 67import android.view.MotionEvent; 68import android.view.View; 69import android.view.View.OnCreateContextMenuListener; 70import android.view.ViewGroup; 71import android.view.ViewGroup.LayoutParams; 72import android.view.ViewManager; 73import android.view.Window; 74import android.view.WindowManager; 75import android.view.accessibility.AccessibilityEvent; 76import android.widget.AdapterView; 77 78import java.io.FileDescriptor; 79import java.io.PrintWriter; 80import java.util.ArrayList; 81import java.util.HashMap; 82 83/** 84 * An activity is a single, focused thing that the user can do. Almost all 85 * activities interact with the user, so the Activity class takes care of 86 * creating a window for you in which you can place your UI with 87 * {@link #setContentView}. While activities are often presented to the user 88 * as full-screen windows, they can also be used in other ways: as floating 89 * windows (via a theme with {@link android.R.attr#windowIsFloating} set) 90 * or embedded inside of another activity (using {@link ActivityGroup}). 91 * 92 * There are two methods almost all subclasses of Activity will implement: 93 * 94 * <ul> 95 * <li> {@link #onCreate} is where you initialize your activity. Most 96 * importantly, here you will usually call {@link #setContentView(int)} 97 * with a layout resource defining your UI, and using {@link #findViewById} 98 * to retrieve the widgets in that UI that you need to interact with 99 * programmatically. 100 * 101 * <li> {@link #onPause} is where you deal with the user leaving your 102 * activity. Most importantly, any changes made by the user should at this 103 * point be committed (usually to the 104 * {@link android.content.ContentProvider} holding the data). 105 * </ul> 106 * 107 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all 108 * activity classes must have a corresponding 109 * {@link android.R.styleable#AndroidManifestActivity <activity>} 110 * declaration in their package's <code>AndroidManifest.xml</code>.</p> 111 * 112 * <p>The Activity class is an important part of an application's overall lifecycle, 113 * and the way activities are launched and put together is a fundamental 114 * part of the platform's application model. For a detailed perspective on the structure of an 115 * Android application and how activities behave, please read the 116 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and 117 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a> 118 * documents.</p> 119 * 120 * <p>You can also find a detailed discussion about how to create activities in the 121 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> 122 * document.</p> 123 * 124 * <p>Topics covered here: 125 * <ol> 126 * <li><a href="#Fragments">Fragments</a> 127 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a> 128 * <li><a href="#ConfigurationChanges">Configuration Changes</a> 129 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a> 130 * <li><a href="#SavingPersistentState">Saving Persistent State</a> 131 * <li><a href="#Permissions">Permissions</a> 132 * <li><a href="#ProcessLifecycle">Process Lifecycle</a> 133 * </ol> 134 * 135 * <a name="Fragments"></a> 136 * <h3>Fragments</h3> 137 * 138 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity 139 * implementations can make use of the {@link Fragment} class to better 140 * modularize their code, build more sophisticated user interfaces for larger 141 * screens, and help scale their application between small and large screens. 142 * 143 * <a name="ActivityLifecycle"></a> 144 * <h3>Activity Lifecycle</h3> 145 * 146 * <p>Activities in the system are managed as an <em>activity stack</em>. 147 * When a new activity is started, it is placed on the top of the stack 148 * and becomes the running activity -- the previous activity always remains 149 * below it in the stack, and will not come to the foreground again until 150 * the new activity exits.</p> 151 * 152 * <p>An activity has essentially four states:</p> 153 * <ul> 154 * <li> If an activity in the foreground of the screen (at the top of 155 * the stack), 156 * it is <em>active</em> or <em>running</em>. </li> 157 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized 158 * or transparent activity has focus on top of your activity), it 159 * is <em>paused</em>. A paused activity is completely alive (it 160 * maintains all state and member information and remains attached to 161 * the window manager), but can be killed by the system in extreme 162 * low memory situations. 163 * <li>If an activity is completely obscured by another activity, 164 * it is <em>stopped</em>. It still retains all state and member information, 165 * however, it is no longer visible to the user so its window is hidden 166 * and it will often be killed by the system when memory is needed 167 * elsewhere.</li> 168 * <li>If an activity is paused or stopped, the system can drop the activity 169 * from memory by either asking it to finish, or simply killing its 170 * process. When it is displayed again to the user, it must be 171 * completely restarted and restored to its previous state.</li> 172 * </ul> 173 * 174 * <p>The following diagram shows the important state paths of an Activity. 175 * The square rectangles represent callback methods you can implement to 176 * perform operations when the Activity moves between states. The colored 177 * ovals are major states the Activity can be in.</p> 178 * 179 * <p><img src="../../../images/activity_lifecycle.png" 180 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p> 181 * 182 * <p>There are three key loops you may be interested in monitoring within your 183 * activity: 184 * 185 * <ul> 186 * <li>The <b>entire lifetime</b> of an activity happens between the first call 187 * to {@link android.app.Activity#onCreate} through to a single final call 188 * to {@link android.app.Activity#onDestroy}. An activity will do all setup 189 * of "global" state in onCreate(), and release all remaining resources in 190 * onDestroy(). For example, if it has a thread running in the background 191 * to download data from the network, it may create that thread in onCreate() 192 * and then stop the thread in onDestroy(). 193 * 194 * <li>The <b>visible lifetime</b> of an activity happens between a call to 195 * {@link android.app.Activity#onStart} until a corresponding call to 196 * {@link android.app.Activity#onStop}. During this time the user can see the 197 * activity on-screen, though it may not be in the foreground and interacting 198 * with the user. Between these two methods you can maintain resources that 199 * are needed to show the activity to the user. For example, you can register 200 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes 201 * that impact your UI, and unregister it in onStop() when the user an no 202 * longer see what you are displaying. The onStart() and onStop() methods 203 * can be called multiple times, as the activity becomes visible and hidden 204 * to the user. 205 * 206 * <li>The <b>foreground lifetime</b> of an activity happens between a call to 207 * {@link android.app.Activity#onResume} until a corresponding call to 208 * {@link android.app.Activity#onPause}. During this time the activity is 209 * in front of all other activities and interacting with the user. An activity 210 * can frequently go between the resumed and paused states -- for example when 211 * the device goes to sleep, when an activity result is delivered, when a new 212 * intent is delivered -- so the code in these methods should be fairly 213 * lightweight. 214 * </ul> 215 * 216 * <p>The entire lifecycle of an activity is defined by the following 217 * Activity methods. All of these are hooks that you can override 218 * to do appropriate work when the activity changes state. All 219 * activities will implement {@link android.app.Activity#onCreate} 220 * to do their initial setup; many will also implement 221 * {@link android.app.Activity#onPause} to commit changes to data and 222 * otherwise prepare to stop interacting with the user. You should always 223 * call up to your superclass when implementing these methods.</p> 224 * 225 * </p> 226 * <pre class="prettyprint"> 227 * public class Activity extends ApplicationContext { 228 * protected void onCreate(Bundle savedInstanceState); 229 * 230 * protected void onStart(); 231 * 232 * protected void onRestart(); 233 * 234 * protected void onResume(); 235 * 236 * protected void onPause(); 237 * 238 * protected void onStop(); 239 * 240 * protected void onDestroy(); 241 * } 242 * </pre> 243 * 244 * <p>In general the movement through an activity's lifecycle looks like 245 * this:</p> 246 * 247 * <table border="2" width="85%" align="center" frame="hsides" rules="rows"> 248 * <colgroup align="left" span="3" /> 249 * <colgroup align="left" /> 250 * <colgroup align="center" /> 251 * <colgroup align="center" /> 252 * 253 * <thead> 254 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr> 255 * </thead> 256 * 257 * <tbody> 258 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th> 259 * <td>Called when the activity is first created. 260 * This is where you should do all of your normal static set up: 261 * create views, bind data to lists, etc. This method also 262 * provides you with a Bundle containing the activity's previously 263 * frozen state, if there was one. 264 * <p>Always followed by <code>onStart()</code>.</td> 265 * <td align="center">No</td> 266 * <td align="center"><code>onStart()</code></td> 267 * </tr> 268 * 269 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td> 270 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th> 271 * <td>Called after your activity has been stopped, prior to it being 272 * started again. 273 * <p>Always followed by <code>onStart()</code></td> 274 * <td align="center">No</td> 275 * <td align="center"><code>onStart()</code></td> 276 * </tr> 277 * 278 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th> 279 * <td>Called when the activity is becoming visible to the user. 280 * <p>Followed by <code>onResume()</code> if the activity comes 281 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td> 282 * <td align="center">No</td> 283 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td> 284 * </tr> 285 * 286 * <tr><td rowspan="2" style="border-left: none;"> </td> 287 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th> 288 * <td>Called when the activity will start 289 * interacting with the user. At this point your activity is at 290 * the top of the activity stack, with user input going to it. 291 * <p>Always followed by <code>onPause()</code>.</td> 292 * <td align="center">No</td> 293 * <td align="center"><code>onPause()</code></td> 294 * </tr> 295 * 296 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th> 297 * <td>Called when the system is about to start resuming a previous 298 * activity. This is typically used to commit unsaved changes to 299 * persistent data, stop animations and other things that may be consuming 300 * CPU, etc. Implementations of this method must be very quick because 301 * the next activity will not be resumed until this method returns. 302 * <p>Followed by either <code>onResume()</code> if the activity 303 * returns back to the front, or <code>onStop()</code> if it becomes 304 * invisible to the user.</td> 305 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td> 306 * <td align="center"><code>onResume()</code> or<br> 307 * <code>onStop()</code></td> 308 * </tr> 309 * 310 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th> 311 * <td>Called when the activity is no longer visible to the user, because 312 * another activity has been resumed and is covering this one. This 313 * may happen either because a new activity is being started, an existing 314 * one is being brought in front of this one, or this one is being 315 * destroyed. 316 * <p>Followed by either <code>onRestart()</code> if 317 * this activity is coming back to interact with the user, or 318 * <code>onDestroy()</code> if this activity is going away.</td> 319 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td> 320 * <td align="center"><code>onRestart()</code> or<br> 321 * <code>onDestroy()</code></td> 322 * </tr> 323 * 324 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th> 325 * <td>The final call you receive before your 326 * activity is destroyed. This can happen either because the 327 * activity is finishing (someone called {@link Activity#finish} on 328 * it, or because the system is temporarily destroying this 329 * instance of the activity to save space. You can distinguish 330 * between these two scenarios with the {@link 331 * Activity#isFinishing} method.</td> 332 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td> 333 * <td align="center"><em>nothing</em></td> 334 * </tr> 335 * </tbody> 336 * </table> 337 * 338 * <p>Note the "Killable" column in the above table -- for those methods that 339 * are marked as being killable, after that method returns the process hosting the 340 * activity may killed by the system <em>at any time</em> without another line 341 * of its code being executed. Because of this, you should use the 342 * {@link #onPause} method to write any persistent data (such as user edits) 343 * to storage. In addition, the method 344 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity 345 * in such a background state, allowing you to save away any dynamic instance 346 * state in your activity into the given Bundle, to be later received in 347 * {@link #onCreate} if the activity needs to be re-created. 348 * See the <a href="#ProcessLifecycle">Process Lifecycle</a> 349 * section for more information on how the lifecycle of a process is tied 350 * to the activities it is hosting. Note that it is important to save 351 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState} 352 * because the later is not part of the lifecycle callbacks, so will not 353 * be called in every situation as described in its documentation.</p> 354 * 355 * <p class="note">Be aware that these semantics will change slightly between 356 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB} 357 * vs. those targeting prior platforms. Starting with Honeycomb, an application 358 * is not in the killable state until its {@link #onStop} has returned. This 359 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be 360 * safely called after {@link #onPause()} and allows and application to safely 361 * wait until {@link #onStop()} to save persistent state.</p> 362 * 363 * <p>For those methods that are not marked as being killable, the activity's 364 * process will not be killed by the system starting from the time the method 365 * is called and continuing after it returns. Thus an activity is in the killable 366 * state, for example, between after <code>onPause()</code> to the start of 367 * <code>onResume()</code>.</p> 368 * 369 * <a name="ConfigurationChanges"></a> 370 * <h3>Configuration Changes</h3> 371 * 372 * <p>If the configuration of the device (as defined by the 373 * {@link Configuration Resources.Configuration} class) changes, 374 * then anything displaying a user interface will need to update to match that 375 * configuration. Because Activity is the primary mechanism for interacting 376 * with the user, it includes special support for handling configuration 377 * changes.</p> 378 * 379 * <p>Unless you specify otherwise, a configuration change (such as a change 380 * in screen orientation, language, input devices, etc) will cause your 381 * current activity to be <em>destroyed</em>, going through the normal activity 382 * lifecycle process of {@link #onPause}, 383 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity 384 * had been in the foreground or visible to the user, once {@link #onDestroy} is 385 * called in that instance then a new instance of the activity will be 386 * created, with whatever savedInstanceState the previous instance had generated 387 * from {@link #onSaveInstanceState}.</p> 388 * 389 * <p>This is done because any application resource, 390 * including layout files, can change based on any configuration value. Thus 391 * the only safe way to handle a configuration change is to re-retrieve all 392 * resources, including layouts, drawables, and strings. Because activities 393 * must already know how to save their state and re-create themselves from 394 * that state, this is a convenient way to have an activity restart itself 395 * with a new configuration.</p> 396 * 397 * <p>In some special cases, you may want to bypass restarting of your 398 * activity based on one or more types of configuration changes. This is 399 * done with the {@link android.R.attr#configChanges android:configChanges} 400 * attribute in its manifest. For any types of configuration changes you say 401 * that you handle there, you will receive a call to your current activity's 402 * {@link #onConfigurationChanged} method instead of being restarted. If 403 * a configuration change involves any that you do not handle, however, the 404 * activity will still be restarted and {@link #onConfigurationChanged} 405 * will not be called.</p> 406 * 407 * <a name="StartingActivities"></a> 408 * <h3>Starting Activities and Getting Results</h3> 409 * 410 * <p>The {@link android.app.Activity#startActivity} 411 * method is used to start a 412 * new activity, which will be placed at the top of the activity stack. It 413 * takes a single argument, an {@link android.content.Intent Intent}, 414 * which describes the activity 415 * to be executed.</p> 416 * 417 * <p>Sometimes you want to get a result back from an activity when it 418 * ends. For example, you may start an activity that lets the user pick 419 * a person in a list of contacts; when it ends, it returns the person 420 * that was selected. To do this, you call the 421 * {@link android.app.Activity#startActivityForResult(Intent, int)} 422 * version with a second integer parameter identifying the call. The result 423 * will come back through your {@link android.app.Activity#onActivityResult} 424 * method.</p> 425 * 426 * <p>When an activity exits, it can call 427 * {@link android.app.Activity#setResult(int)} 428 * to return data back to its parent. It must always supply a result code, 429 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any 430 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally 431 * return back an Intent containing any additional data it wants. All of this 432 * information appears back on the 433 * parent's <code>Activity.onActivityResult()</code>, along with the integer 434 * identifier it originally supplied.</p> 435 * 436 * <p>If a child activity fails for any reason (such as crashing), the parent 437 * activity will receive a result with the code RESULT_CANCELED.</p> 438 * 439 * <pre class="prettyprint"> 440 * public class MyActivity extends Activity { 441 * ... 442 * 443 * static final int PICK_CONTACT_REQUEST = 0; 444 * 445 * protected boolean onKeyDown(int keyCode, KeyEvent event) { 446 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 447 * // When the user center presses, let them pick a contact. 448 * startActivityForResult( 449 * new Intent(Intent.ACTION_PICK, 450 * new Uri("content://contacts")), 451 * PICK_CONTACT_REQUEST); 452 * return true; 453 * } 454 * return false; 455 * } 456 * 457 * protected void onActivityResult(int requestCode, int resultCode, 458 * Intent data) { 459 * if (requestCode == PICK_CONTACT_REQUEST) { 460 * if (resultCode == RESULT_OK) { 461 * // A contact was picked. Here we will just display it 462 * // to the user. 463 * startActivity(new Intent(Intent.ACTION_VIEW, data)); 464 * } 465 * } 466 * } 467 * } 468 * </pre> 469 * 470 * <a name="SavingPersistentState"></a> 471 * <h3>Saving Persistent State</h3> 472 * 473 * <p>There are generally two kinds of persistent state than an activity 474 * will deal with: shared document-like data (typically stored in a SQLite 475 * database using a {@linkplain android.content.ContentProvider content provider}) 476 * and internal state such as user preferences.</p> 477 * 478 * <p>For content provider data, we suggest that activities use a 479 * "edit in place" user model. That is, any edits a user makes are effectively 480 * made immediately without requiring an additional confirmation step. 481 * Supporting this model is generally a simple matter of following two rules:</p> 482 * 483 * <ul> 484 * <li> <p>When creating a new document, the backing database entry or file for 485 * it is created immediately. For example, if the user chooses to write 486 * a new e-mail, a new entry for that e-mail is created as soon as they 487 * start entering data, so that if they go to any other activity after 488 * that point this e-mail will now appear in the list of drafts.</p> 489 * <li> <p>When an activity's <code>onPause()</code> method is called, it should 490 * commit to the backing content provider or file any changes the user 491 * has made. This ensures that those changes will be seen by any other 492 * activity that is about to run. You will probably want to commit 493 * your data even more aggressively at key times during your 494 * activity's lifecycle: for example before starting a new 495 * activity, before finishing your own activity, when the user 496 * switches between input fields, etc.</p> 497 * </ul> 498 * 499 * <p>This model is designed to prevent data loss when a user is navigating 500 * between activities, and allows the system to safely kill an activity (because 501 * system resources are needed somewhere else) at any time after it has been 502 * paused. Note this implies 503 * that the user pressing BACK from your activity does <em>not</em> 504 * mean "cancel" -- it means to leave the activity with its current contents 505 * saved away. Canceling edits in an activity must be provided through 506 * some other mechanism, such as an explicit "revert" or "undo" option.</p> 507 * 508 * <p>See the {@linkplain android.content.ContentProvider content package} for 509 * more information about content providers. These are a key aspect of how 510 * different activities invoke and propagate data between themselves.</p> 511 * 512 * <p>The Activity class also provides an API for managing internal persistent state 513 * associated with an activity. This can be used, for example, to remember 514 * the user's preferred initial display in a calendar (day view or week view) 515 * or the user's default home page in a web browser.</p> 516 * 517 * <p>Activity persistent state is managed 518 * with the method {@link #getPreferences}, 519 * allowing you to retrieve and 520 * modify a set of name/value pairs associated with the activity. To use 521 * preferences that are shared across multiple application components 522 * (activities, receivers, services, providers), you can use the underlying 523 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method 524 * to retrieve a preferences 525 * object stored under a specific name. 526 * (Note that it is not possible to share settings data across application 527 * packages -- for that you will need a content provider.)</p> 528 * 529 * <p>Here is an excerpt from a calendar activity that stores the user's 530 * preferred view mode in its persistent settings:</p> 531 * 532 * <pre class="prettyprint"> 533 * public class CalendarActivity extends Activity { 534 * ... 535 * 536 * static final int DAY_VIEW_MODE = 0; 537 * static final int WEEK_VIEW_MODE = 1; 538 * 539 * private SharedPreferences mPrefs; 540 * private int mCurViewMode; 541 * 542 * protected void onCreate(Bundle savedInstanceState) { 543 * super.onCreate(savedInstanceState); 544 * 545 * SharedPreferences mPrefs = getSharedPreferences(); 546 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE); 547 * } 548 * 549 * protected void onPause() { 550 * super.onPause(); 551 * 552 * SharedPreferences.Editor ed = mPrefs.edit(); 553 * ed.putInt("view_mode", mCurViewMode); 554 * ed.commit(); 555 * } 556 * } 557 * </pre> 558 * 559 * <a name="Permissions"></a> 560 * <h3>Permissions</h3> 561 * 562 * <p>The ability to start a particular Activity can be enforced when it is 563 * declared in its 564 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>} 565 * tag. By doing so, other applications will need to declare a corresponding 566 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} 567 * element in their own manifest to be able to start that activity. 568 * 569 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> 570 * document for more information on permissions and security in general. 571 * 572 * <a name="ProcessLifecycle"></a> 573 * <h3>Process Lifecycle</h3> 574 * 575 * <p>The Android system attempts to keep application process around for as 576 * long as possible, but eventually will need to remove old processes when 577 * memory runs low. As described in <a href="#ActivityLifecycle">Activity 578 * Lifecycle</a>, the decision about which process to remove is intimately 579 * tied to the state of the user's interaction with it. In general, there 580 * are four states a process can be in based on the activities running in it, 581 * listed here in order of importance. The system will kill less important 582 * processes (the last ones) before it resorts to killing more important 583 * processes (the first ones). 584 * 585 * <ol> 586 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen 587 * that the user is currently interacting with) is considered the most important. 588 * Its process will only be killed as a last resort, if it uses more memory 589 * than is available on the device. Generally at this point the device has 590 * reached a memory paging state, so this is required in order to keep the user 591 * interface responsive. 592 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user 593 * but not in the foreground, such as one sitting behind a foreground dialog) 594 * is considered extremely important and will not be killed unless that is 595 * required to keep the foreground activity running. 596 * <li> <p>A <b>background activity</b> (an activity that is not visible to 597 * the user and has been paused) is no longer critical, so the system may 598 * safely kill its process to reclaim memory for other foreground or 599 * visible processes. If its process needs to be killed, when the user navigates 600 * back to the activity (making it visible on the screen again), its 601 * {@link #onCreate} method will be called with the savedInstanceState it had previously 602 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same 603 * state as the user last left it. 604 * <li> <p>An <b>empty process</b> is one hosting no activities or other 605 * application components (such as {@link Service} or 606 * {@link android.content.BroadcastReceiver} classes). These are killed very 607 * quickly by the system as memory becomes low. For this reason, any 608 * background operation you do outside of an activity must be executed in the 609 * context of an activity BroadcastReceiver or Service to ensure that the system 610 * knows it needs to keep your process around. 611 * </ol> 612 * 613 * <p>Sometimes an Activity may need to do a long-running operation that exists 614 * independently of the activity lifecycle itself. An example may be a camera 615 * application that allows you to upload a picture to a web site. The upload 616 * may take a long time, and the application should allow the user to leave 617 * the application will it is executing. To accomplish this, your Activity 618 * should start a {@link Service} in which the upload takes place. This allows 619 * the system to properly prioritize your process (considering it to be more 620 * important than other non-visible applications) for the duration of the 621 * upload, independent of whether the original activity is paused, stopped, 622 * or finished. 623 */ 624public class Activity extends ContextThemeWrapper 625 implements LayoutInflater.Factory2, 626 Window.Callback, KeyEvent.Callback, 627 OnCreateContextMenuListener, ComponentCallbacks { 628 private static final String TAG = "Activity"; 629 630 /** Standard activity result: operation canceled. */ 631 public static final int RESULT_CANCELED = 0; 632 /** Standard activity result: operation succeeded. */ 633 public static final int RESULT_OK = -1; 634 /** Start of user-defined activity results. */ 635 public static final int RESULT_FIRST_USER = 1; 636 637 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState"; 638 private static final String FRAGMENTS_TAG = "android:fragments"; 639 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds"; 640 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs"; 641 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_"; 642 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_"; 643 644 private static class ManagedDialog { 645 Dialog mDialog; 646 Bundle mArgs; 647 } 648 private SparseArray<ManagedDialog> mManagedDialogs; 649 650 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called. 651 private Instrumentation mInstrumentation; 652 private IBinder mToken; 653 private int mIdent; 654 /*package*/ String mEmbeddedID; 655 private Application mApplication; 656 /*package*/ Intent mIntent; 657 private ComponentName mComponent; 658 /*package*/ ActivityInfo mActivityInfo; 659 /*package*/ ActivityThread mMainThread; 660 Activity mParent; 661 boolean mCalled; 662 boolean mCheckedForLoaderManager; 663 boolean mLoadersStarted; 664 /*package*/ boolean mResumed; 665 private boolean mStopped; 666 boolean mFinished; 667 boolean mStartedActivity; 668 /** true if the activity is going through a transient pause */ 669 /*package*/ boolean mTemporaryPause = false; 670 /** true if the activity is being destroyed in order to recreate it with a new configuration */ 671 /*package*/ boolean mChangingConfigurations = false; 672 /*package*/ int mConfigChangeFlags; 673 /*package*/ Configuration mCurrentConfig; 674 private SearchManager mSearchManager; 675 676 static final class NonConfigurationInstances { 677 Object activity; 678 HashMap<String, Object> children; 679 ArrayList<Fragment> fragments; 680 SparseArray<LoaderManagerImpl> loaders; 681 } 682 /* package */ NonConfigurationInstances mLastNonConfigurationInstances; 683 684 private Window mWindow; 685 686 private WindowManager mWindowManager; 687 /*package*/ View mDecor = null; 688 /*package*/ boolean mWindowAdded = false; 689 /*package*/ boolean mVisibleFromServer = false; 690 /*package*/ boolean mVisibleFromClient = true; 691 /*package*/ ActionBarImpl mActionBar = null; 692 693 private CharSequence mTitle; 694 private int mTitleColor = 0; 695 696 final FragmentManagerImpl mFragments = new FragmentManagerImpl(); 697 698 SparseArray<LoaderManagerImpl> mAllLoaderManagers; 699 LoaderManagerImpl mLoaderManager; 700 701 private static final class ManagedCursor { 702 ManagedCursor(Cursor cursor) { 703 mCursor = cursor; 704 mReleased = false; 705 mUpdated = false; 706 } 707 708 private final Cursor mCursor; 709 private boolean mReleased; 710 private boolean mUpdated; 711 } 712 private final ArrayList<ManagedCursor> mManagedCursors = 713 new ArrayList<ManagedCursor>(); 714 715 // protected by synchronized (this) 716 int mResultCode = RESULT_CANCELED; 717 Intent mResultData = null; 718 719 private boolean mTitleReady = false; 720 721 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE; 722 private SpannableStringBuilder mDefaultKeySsb = null; 723 724 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused}; 725 726 private Thread mUiThread; 727 final Handler mHandler = new Handler(); 728 729 /** Return the intent that started this activity. */ 730 public Intent getIntent() { 731 return mIntent; 732 } 733 734 /** 735 * Change the intent returned by {@link #getIntent}. This holds a 736 * reference to the given intent; it does not copy it. Often used in 737 * conjunction with {@link #onNewIntent}. 738 * 739 * @param newIntent The new Intent object to return from getIntent 740 * 741 * @see #getIntent 742 * @see #onNewIntent 743 */ 744 public void setIntent(Intent newIntent) { 745 mIntent = newIntent; 746 } 747 748 /** Return the application that owns this activity. */ 749 public final Application getApplication() { 750 return mApplication; 751 } 752 753 /** Is this activity embedded inside of another activity? */ 754 public final boolean isChild() { 755 return mParent != null; 756 } 757 758 /** Return the parent activity if this view is an embedded child. */ 759 public final Activity getParent() { 760 return mParent; 761 } 762 763 /** Retrieve the window manager for showing custom windows. */ 764 public WindowManager getWindowManager() { 765 return mWindowManager; 766 } 767 768 /** 769 * Retrieve the current {@link android.view.Window} for the activity. 770 * This can be used to directly access parts of the Window API that 771 * are not available through Activity/Screen. 772 * 773 * @return Window The current window, or null if the activity is not 774 * visual. 775 */ 776 public Window getWindow() { 777 return mWindow; 778 } 779 780 /** 781 * Return the LoaderManager for this fragment, creating it if needed. 782 */ 783 public LoaderManager getLoaderManager() { 784 if (mLoaderManager != null) { 785 return mLoaderManager; 786 } 787 mCheckedForLoaderManager = true; 788 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true); 789 return mLoaderManager; 790 } 791 792 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) { 793 if (mAllLoaderManagers == null) { 794 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>(); 795 } 796 LoaderManagerImpl lm = mAllLoaderManagers.get(index); 797 if (lm == null) { 798 if (create) { 799 lm = new LoaderManagerImpl(this, started); 800 mAllLoaderManagers.put(index, lm); 801 } 802 } else { 803 lm.updateActivity(this); 804 } 805 return lm; 806 } 807 808 /** 809 * Calls {@link android.view.Window#getCurrentFocus} on the 810 * Window of this Activity to return the currently focused view. 811 * 812 * @return View The current View with focus or null. 813 * 814 * @see #getWindow 815 * @see android.view.Window#getCurrentFocus 816 */ 817 public View getCurrentFocus() { 818 return mWindow != null ? mWindow.getCurrentFocus() : null; 819 } 820 821 @Override 822 public int getWallpaperDesiredMinimumWidth() { 823 int width = super.getWallpaperDesiredMinimumWidth(); 824 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width; 825 } 826 827 @Override 828 public int getWallpaperDesiredMinimumHeight() { 829 int height = super.getWallpaperDesiredMinimumHeight(); 830 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height; 831 } 832 833 /** 834 * Called when the activity is starting. This is where most initialization 835 * should go: calling {@link #setContentView(int)} to inflate the 836 * activity's UI, using {@link #findViewById} to programmatically interact 837 * with widgets in the UI, calling 838 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve 839 * cursors for data being displayed, etc. 840 * 841 * <p>You can call {@link #finish} from within this function, in 842 * which case onDestroy() will be immediately called without any of the rest 843 * of the activity lifecycle ({@link #onStart}, {@link #onResume}, 844 * {@link #onPause}, etc) executing. 845 * 846 * <p><em>Derived classes must call through to the super class's 847 * implementation of this method. If they do not, an exception will be 848 * thrown.</em></p> 849 * 850 * @param savedInstanceState If the activity is being re-initialized after 851 * previously being shut down then this Bundle contains the data it most 852 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> 853 * 854 * @see #onStart 855 * @see #onSaveInstanceState 856 * @see #onRestoreInstanceState 857 * @see #onPostCreate 858 */ 859 protected void onCreate(Bundle savedInstanceState) { 860 if (mLastNonConfigurationInstances != null) { 861 mAllLoaderManagers = mLastNonConfigurationInstances.loaders; 862 } 863 if (savedInstanceState != null) { 864 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); 865 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null 866 ? mLastNonConfigurationInstances.fragments : null); 867 } 868 mFragments.dispatchCreate(); 869 mCalled = true; 870 } 871 872 /** 873 * The hook for {@link ActivityThread} to restore the state of this activity. 874 * 875 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and 876 * {@link #restoreManagedDialogs(android.os.Bundle)}. 877 * 878 * @param savedInstanceState contains the saved state 879 */ 880 final void performRestoreInstanceState(Bundle savedInstanceState) { 881 onRestoreInstanceState(savedInstanceState); 882 restoreManagedDialogs(savedInstanceState); 883 } 884 885 /** 886 * This method is called after {@link #onStart} when the activity is 887 * being re-initialized from a previously saved state, given here in 888 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate} 889 * to restore their state, but it is sometimes convenient to do it here 890 * after all of the initialization has been done or to allow subclasses to 891 * decide whether to use your default implementation. The default 892 * implementation of this method performs a restore of any view state that 893 * had previously been frozen by {@link #onSaveInstanceState}. 894 * 895 * <p>This method is called between {@link #onStart} and 896 * {@link #onPostCreate}. 897 * 898 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}. 899 * 900 * @see #onCreate 901 * @see #onPostCreate 902 * @see #onResume 903 * @see #onSaveInstanceState 904 */ 905 protected void onRestoreInstanceState(Bundle savedInstanceState) { 906 if (mWindow != null) { 907 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG); 908 if (windowState != null) { 909 mWindow.restoreHierarchyState(windowState); 910 } 911 } 912 } 913 914 /** 915 * Restore the state of any saved managed dialogs. 916 * 917 * @param savedInstanceState The bundle to restore from. 918 */ 919 private void restoreManagedDialogs(Bundle savedInstanceState) { 920 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG); 921 if (b == null) { 922 return; 923 } 924 925 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY); 926 final int numDialogs = ids.length; 927 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs); 928 for (int i = 0; i < numDialogs; i++) { 929 final Integer dialogId = ids[i]; 930 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId)); 931 if (dialogState != null) { 932 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate 933 // so tell createDialog() not to do it, otherwise we get an exception 934 final ManagedDialog md = new ManagedDialog(); 935 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId)); 936 md.mDialog = createDialog(dialogId, dialogState, md.mArgs); 937 if (md.mDialog != null) { 938 mManagedDialogs.put(dialogId, md); 939 onPrepareDialog(dialogId, md.mDialog, md.mArgs); 940 md.mDialog.onRestoreInstanceState(dialogState); 941 } 942 } 943 } 944 } 945 946 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) { 947 final Dialog dialog = onCreateDialog(dialogId, args); 948 if (dialog == null) { 949 return null; 950 } 951 dialog.dispatchOnCreate(state); 952 return dialog; 953 } 954 955 private static String savedDialogKeyFor(int key) { 956 return SAVED_DIALOG_KEY_PREFIX + key; 957 } 958 959 private static String savedDialogArgsKeyFor(int key) { 960 return SAVED_DIALOG_ARGS_KEY_PREFIX + key; 961 } 962 963 /** 964 * Called when activity start-up is complete (after {@link #onStart} 965 * and {@link #onRestoreInstanceState} have been called). Applications will 966 * generally not implement this method; it is intended for system 967 * classes to do final initialization after application code has run. 968 * 969 * <p><em>Derived classes must call through to the super class's 970 * implementation of this method. If they do not, an exception will be 971 * thrown.</em></p> 972 * 973 * @param savedInstanceState If the activity is being re-initialized after 974 * previously being shut down then this Bundle contains the data it most 975 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> 976 * @see #onCreate 977 */ 978 protected void onPostCreate(Bundle savedInstanceState) { 979 if (!isChild()) { 980 mTitleReady = true; 981 onTitleChanged(getTitle(), getTitleColor()); 982 } 983 mCalled = true; 984 } 985 986 /** 987 * Called after {@link #onCreate} — or after {@link #onRestart} when 988 * the activity had been stopped, but is now again being displayed to the 989 * user. It will be followed by {@link #onResume}. 990 * 991 * <p><em>Derived classes must call through to the super class's 992 * implementation of this method. If they do not, an exception will be 993 * thrown.</em></p> 994 * 995 * @see #onCreate 996 * @see #onStop 997 * @see #onResume 998 */ 999 protected void onStart() { 1000 mCalled = true; 1001 1002 if (!mLoadersStarted) { 1003 mLoadersStarted = true; 1004 if (mLoaderManager != null) { 1005 mLoaderManager.doStart(); 1006 } else if (!mCheckedForLoaderManager) { 1007 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false); 1008 } 1009 mCheckedForLoaderManager = true; 1010 } 1011 } 1012 1013 /** 1014 * Called after {@link #onStop} when the current activity is being 1015 * re-displayed to the user (the user has navigated back to it). It will 1016 * be followed by {@link #onStart} and then {@link #onResume}. 1017 * 1018 * <p>For activities that are using raw {@link Cursor} objects (instead of 1019 * creating them through 1020 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)}, 1021 * this is usually the place 1022 * where the cursor should be requeried (because you had deactivated it in 1023 * {@link #onStop}. 1024 * 1025 * <p><em>Derived classes must call through to the super class's 1026 * implementation of this method. If they do not, an exception will be 1027 * thrown.</em></p> 1028 * 1029 * @see #onStop 1030 * @see #onStart 1031 * @see #onResume 1032 */ 1033 protected void onRestart() { 1034 mCalled = true; 1035 } 1036 1037 /** 1038 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or 1039 * {@link #onPause}, for your activity to start interacting with the user. 1040 * This is a good place to begin animations, open exclusive-access devices 1041 * (such as the camera), etc. 1042 * 1043 * <p>Keep in mind that onResume is not the best indicator that your activity 1044 * is visible to the user; a system window such as the keyguard may be in 1045 * front. Use {@link #onWindowFocusChanged} to know for certain that your 1046 * activity is visible to the user (for example, to resume a game). 1047 * 1048 * <p><em>Derived classes must call through to the super class's 1049 * implementation of this method. If they do not, an exception will be 1050 * thrown.</em></p> 1051 * 1052 * @see #onRestoreInstanceState 1053 * @see #onRestart 1054 * @see #onPostResume 1055 * @see #onPause 1056 */ 1057 protected void onResume() { 1058 mCalled = true; 1059 } 1060 1061 /** 1062 * Called when activity resume is complete (after {@link #onResume} has 1063 * been called). Applications will generally not implement this method; 1064 * it is intended for system classes to do final setup after application 1065 * resume code has run. 1066 * 1067 * <p><em>Derived classes must call through to the super class's 1068 * implementation of this method. If they do not, an exception will be 1069 * thrown.</em></p> 1070 * 1071 * @see #onResume 1072 */ 1073 protected void onPostResume() { 1074 final Window win = getWindow(); 1075 if (win != null) win.makeActive(); 1076 mCalled = true; 1077 } 1078 1079 /** 1080 * This is called for activities that set launchMode to "singleTop" in 1081 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} 1082 * flag when calling {@link #startActivity}. In either case, when the 1083 * activity is re-launched while at the top of the activity stack instead 1084 * of a new instance of the activity being started, onNewIntent() will be 1085 * called on the existing instance with the Intent that was used to 1086 * re-launch it. 1087 * 1088 * <p>An activity will always be paused before receiving a new intent, so 1089 * you can count on {@link #onResume} being called after this method. 1090 * 1091 * <p>Note that {@link #getIntent} still returns the original Intent. You 1092 * can use {@link #setIntent} to update it to this new Intent. 1093 * 1094 * @param intent The new intent that was started for the activity. 1095 * 1096 * @see #getIntent 1097 * @see #setIntent 1098 * @see #onResume 1099 */ 1100 protected void onNewIntent(Intent intent) { 1101 } 1102 1103 /** 1104 * The hook for {@link ActivityThread} to save the state of this activity. 1105 * 1106 * Calls {@link #onSaveInstanceState(android.os.Bundle)} 1107 * and {@link #saveManagedDialogs(android.os.Bundle)}. 1108 * 1109 * @param outState The bundle to save the state to. 1110 */ 1111 final void performSaveInstanceState(Bundle outState) { 1112 onSaveInstanceState(outState); 1113 saveManagedDialogs(outState); 1114 } 1115 1116 /** 1117 * Called to retrieve per-instance state from an activity before being killed 1118 * so that the state can be restored in {@link #onCreate} or 1119 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method 1120 * will be passed to both). 1121 * 1122 * <p>This method is called before an activity may be killed so that when it 1123 * comes back some time in the future it can restore its state. For example, 1124 * if activity B is launched in front of activity A, and at some point activity 1125 * A is killed to reclaim resources, activity A will have a chance to save the 1126 * current state of its user interface via this method so that when the user 1127 * returns to activity A, the state of the user interface can be restored 1128 * via {@link #onCreate} or {@link #onRestoreInstanceState}. 1129 * 1130 * <p>Do not confuse this method with activity lifecycle callbacks such as 1131 * {@link #onPause}, which is always called when an activity is being placed 1132 * in the background or on its way to destruction, or {@link #onStop} which 1133 * is called before destruction. One example of when {@link #onPause} and 1134 * {@link #onStop} is called and not this method is when a user navigates back 1135 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState} 1136 * on B because that particular instance will never be restored, so the 1137 * system avoids calling it. An example when {@link #onPause} is called and 1138 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A: 1139 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't 1140 * killed during the lifetime of B since the state of the user interface of 1141 * A will stay intact. 1142 * 1143 * <p>The default implementation takes care of most of the UI per-instance 1144 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each 1145 * view in the hierarchy that has an id, and by saving the id of the currently 1146 * focused view (all of which is restored by the default implementation of 1147 * {@link #onRestoreInstanceState}). If you override this method to save additional 1148 * information not captured by each individual view, you will likely want to 1149 * call through to the default implementation, otherwise be prepared to save 1150 * all of the state of each view yourself. 1151 * 1152 * <p>If called, this method will occur before {@link #onStop}. There are 1153 * no guarantees about whether it will occur before or after {@link #onPause}. 1154 * 1155 * @param outState Bundle in which to place your saved state. 1156 * 1157 * @see #onCreate 1158 * @see #onRestoreInstanceState 1159 * @see #onPause 1160 */ 1161 protected void onSaveInstanceState(Bundle outState) { 1162 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState()); 1163 Parcelable p = mFragments.saveAllState(); 1164 if (p != null) { 1165 outState.putParcelable(FRAGMENTS_TAG, p); 1166 } 1167 } 1168 1169 /** 1170 * Save the state of any managed dialogs. 1171 * 1172 * @param outState place to store the saved state. 1173 */ 1174 private void saveManagedDialogs(Bundle outState) { 1175 if (mManagedDialogs == null) { 1176 return; 1177 } 1178 1179 final int numDialogs = mManagedDialogs.size(); 1180 if (numDialogs == 0) { 1181 return; 1182 } 1183 1184 Bundle dialogState = new Bundle(); 1185 1186 int[] ids = new int[mManagedDialogs.size()]; 1187 1188 // save each dialog's bundle, gather the ids 1189 for (int i = 0; i < numDialogs; i++) { 1190 final int key = mManagedDialogs.keyAt(i); 1191 ids[i] = key; 1192 final ManagedDialog md = mManagedDialogs.valueAt(i); 1193 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState()); 1194 if (md.mArgs != null) { 1195 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs); 1196 } 1197 } 1198 1199 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids); 1200 outState.putBundle(SAVED_DIALOGS_TAG, dialogState); 1201 } 1202 1203 1204 /** 1205 * Called as part of the activity lifecycle when an activity is going into 1206 * the background, but has not (yet) been killed. The counterpart to 1207 * {@link #onResume}. 1208 * 1209 * <p>When activity B is launched in front of activity A, this callback will 1210 * be invoked on A. B will not be created until A's {@link #onPause} returns, 1211 * so be sure to not do anything lengthy here. 1212 * 1213 * <p>This callback is mostly used for saving any persistent state the 1214 * activity is editing, to present a "edit in place" model to the user and 1215 * making sure nothing is lost if there are not enough resources to start 1216 * the new activity without first killing this one. This is also a good 1217 * place to do things like stop animations and other things that consume a 1218 * noticeable mount of CPU in order to make the switch to the next activity 1219 * as fast as possible, or to close resources that are exclusive access 1220 * such as the camera. 1221 * 1222 * <p>In situations where the system needs more memory it may kill paused 1223 * processes to reclaim resources. Because of this, you should be sure 1224 * that all of your state is saved by the time you return from 1225 * this function. In general {@link #onSaveInstanceState} is used to save 1226 * per-instance state in the activity and this method is used to store 1227 * global persistent data (in content providers, files, etc.) 1228 * 1229 * <p>After receiving this call you will usually receive a following call 1230 * to {@link #onStop} (after the next activity has been resumed and 1231 * displayed), however in some cases there will be a direct call back to 1232 * {@link #onResume} without going through the stopped state. 1233 * 1234 * <p><em>Derived classes must call through to the super class's 1235 * implementation of this method. If they do not, an exception will be 1236 * thrown.</em></p> 1237 * 1238 * @see #onResume 1239 * @see #onSaveInstanceState 1240 * @see #onStop 1241 */ 1242 protected void onPause() { 1243 mCalled = true; 1244 } 1245 1246 /** 1247 * Called as part of the activity lifecycle when an activity is about to go 1248 * into the background as the result of user choice. For example, when the 1249 * user presses the Home key, {@link #onUserLeaveHint} will be called, but 1250 * when an incoming phone call causes the in-call Activity to be automatically 1251 * brought to the foreground, {@link #onUserLeaveHint} will not be called on 1252 * the activity being interrupted. In cases when it is invoked, this method 1253 * is called right before the activity's {@link #onPause} callback. 1254 * 1255 * <p>This callback and {@link #onUserInteraction} are intended to help 1256 * activities manage status bar notifications intelligently; specifically, 1257 * for helping activities determine the proper time to cancel a notfication. 1258 * 1259 * @see #onUserInteraction() 1260 */ 1261 protected void onUserLeaveHint() { 1262 } 1263 1264 /** 1265 * Generate a new thumbnail for this activity. This method is called before 1266 * pausing the activity, and should draw into <var>outBitmap</var> the 1267 * imagery for the desired thumbnail in the dimensions of that bitmap. It 1268 * can use the given <var>canvas</var>, which is configured to draw into the 1269 * bitmap, for rendering if desired. 1270 * 1271 * <p>The default implementation returns fails and does not draw a thumbnail; 1272 * this will result in the platform creating its own thumbnail if needed. 1273 * 1274 * @param outBitmap The bitmap to contain the thumbnail. 1275 * @param canvas Can be used to render into the bitmap. 1276 * 1277 * @return Return true if you have drawn into the bitmap; otherwise after 1278 * you return it will be filled with a default thumbnail. 1279 * 1280 * @see #onCreateDescription 1281 * @see #onSaveInstanceState 1282 * @see #onPause 1283 */ 1284 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) { 1285 return false; 1286 } 1287 1288 /** 1289 * Generate a new description for this activity. This method is called 1290 * before pausing the activity and can, if desired, return some textual 1291 * description of its current state to be displayed to the user. 1292 * 1293 * <p>The default implementation returns null, which will cause you to 1294 * inherit the description from the previous activity. If all activities 1295 * return null, generally the label of the top activity will be used as the 1296 * description. 1297 * 1298 * @return A description of what the user is doing. It should be short and 1299 * sweet (only a few words). 1300 * 1301 * @see #onCreateThumbnail 1302 * @see #onSaveInstanceState 1303 * @see #onPause 1304 */ 1305 public CharSequence onCreateDescription() { 1306 return null; 1307 } 1308 1309 /** 1310 * Called when you are no longer visible to the user. You will next 1311 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing, 1312 * depending on later user activity. 1313 * 1314 * <p>Note that this method may never be called, in low memory situations 1315 * where the system does not have enough memory to keep your activity's 1316 * process running after its {@link #onPause} method is called. 1317 * 1318 * <p><em>Derived classes must call through to the super class's 1319 * implementation of this method. If they do not, an exception will be 1320 * thrown.</em></p> 1321 * 1322 * @see #onRestart 1323 * @see #onResume 1324 * @see #onSaveInstanceState 1325 * @see #onDestroy 1326 */ 1327 protected void onStop() { 1328 mCalled = true; 1329 } 1330 1331 /** 1332 * Perform any final cleanup before an activity is destroyed. This can 1333 * happen either because the activity is finishing (someone called 1334 * {@link #finish} on it, or because the system is temporarily destroying 1335 * this instance of the activity to save space. You can distinguish 1336 * between these two scenarios with the {@link #isFinishing} method. 1337 * 1338 * <p><em>Note: do not count on this method being called as a place for 1339 * saving data! For example, if an activity is editing data in a content 1340 * provider, those edits should be committed in either {@link #onPause} or 1341 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to 1342 * free resources like threads that are associated with an activity, so 1343 * that a destroyed activity does not leave such things around while the 1344 * rest of its application is still running. There are situations where 1345 * the system will simply kill the activity's hosting process without 1346 * calling this method (or any others) in it, so it should not be used to 1347 * do things that are intended to remain around after the process goes 1348 * away. 1349 * 1350 * <p><em>Derived classes must call through to the super class's 1351 * implementation of this method. If they do not, an exception will be 1352 * thrown.</em></p> 1353 * 1354 * @see #onPause 1355 * @see #onStop 1356 * @see #finish 1357 * @see #isFinishing 1358 */ 1359 protected void onDestroy() { 1360 mCalled = true; 1361 1362 // dismiss any dialogs we are managing. 1363 if (mManagedDialogs != null) { 1364 final int numDialogs = mManagedDialogs.size(); 1365 for (int i = 0; i < numDialogs; i++) { 1366 final ManagedDialog md = mManagedDialogs.valueAt(i); 1367 if (md.mDialog.isShowing()) { 1368 md.mDialog.dismiss(); 1369 } 1370 } 1371 mManagedDialogs = null; 1372 } 1373 1374 // close any cursors we are managing. 1375 synchronized (mManagedCursors) { 1376 int numCursors = mManagedCursors.size(); 1377 for (int i = 0; i < numCursors; i++) { 1378 ManagedCursor c = mManagedCursors.get(i); 1379 if (c != null) { 1380 c.mCursor.close(); 1381 } 1382 } 1383 mManagedCursors.clear(); 1384 } 1385 1386 // Close any open search dialog 1387 if (mSearchManager != null) { 1388 mSearchManager.stopSearch(); 1389 } 1390 } 1391 1392 /** 1393 * Called by the system when the device configuration changes while your 1394 * activity is running. Note that this will <em>only</em> be called if 1395 * you have selected configurations you would like to handle with the 1396 * {@link android.R.attr#configChanges} attribute in your manifest. If 1397 * any configuration change occurs that is not selected to be reported 1398 * by that attribute, then instead of reporting it the system will stop 1399 * and restart the activity (to have it launched with the new 1400 * configuration). 1401 * 1402 * <p>At the time that this function has been called, your Resources 1403 * object will have been updated to return resource values matching the 1404 * new configuration. 1405 * 1406 * @param newConfig The new device configuration. 1407 */ 1408 public void onConfigurationChanged(Configuration newConfig) { 1409 mCalled = true; 1410 1411 mFragments.dispatchConfigurationChanged(newConfig); 1412 1413 if (mWindow != null) { 1414 // Pass the configuration changed event to the window 1415 mWindow.onConfigurationChanged(newConfig); 1416 } 1417 } 1418 1419 /** 1420 * If this activity is being destroyed because it can not handle a 1421 * configuration parameter being changed (and thus its 1422 * {@link #onConfigurationChanged(Configuration)} method is 1423 * <em>not</em> being called), then you can use this method to discover 1424 * the set of changes that have occurred while in the process of being 1425 * destroyed. Note that there is no guarantee that these will be 1426 * accurate (other changes could have happened at any time), so you should 1427 * only use this as an optimization hint. 1428 * 1429 * @return Returns a bit field of the configuration parameters that are 1430 * changing, as defined by the {@link android.content.res.Configuration} 1431 * class. 1432 */ 1433 public int getChangingConfigurations() { 1434 return mConfigChangeFlags; 1435 } 1436 1437 /** 1438 * Retrieve the non-configuration instance data that was previously 1439 * returned by {@link #onRetainNonConfigurationInstance()}. This will 1440 * be available from the initial {@link #onCreate} and 1441 * {@link #onStart} calls to the new instance, allowing you to extract 1442 * any useful dynamic state from the previous instance. 1443 * 1444 * <p>Note that the data you retrieve here should <em>only</em> be used 1445 * as an optimization for handling configuration changes. You should always 1446 * be able to handle getting a null pointer back, and an activity must 1447 * still be able to restore itself to its previous state (through the 1448 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this 1449 * function returns null. 1450 * 1451 * @return Returns the object previously returned by 1452 * {@link #onRetainNonConfigurationInstance()}. 1453 */ 1454 public Object getLastNonConfigurationInstance() { 1455 return mLastNonConfigurationInstances != null 1456 ? mLastNonConfigurationInstances.activity : null; 1457 } 1458 1459 /** 1460 * Called by the system, as part of destroying an 1461 * activity due to a configuration change, when it is known that a new 1462 * instance will immediately be created for the new configuration. You 1463 * can return any object you like here, including the activity instance 1464 * itself, which can later be retrieved by calling 1465 * {@link #getLastNonConfigurationInstance()} in the new activity 1466 * instance. 1467 * 1468 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 1469 * or later, consider instead using a {@link Fragment} with 1470 * {@link Fragment#setRetainInstance(boolean) 1471 * Fragment.setRetainInstance(boolean}.</em> 1472 * 1473 * <p>This function is called purely as an optimization, and you must 1474 * not rely on it being called. When it is called, a number of guarantees 1475 * will be made to help optimize configuration switching: 1476 * <ul> 1477 * <li> The function will be called between {@link #onStop} and 1478 * {@link #onDestroy}. 1479 * <li> A new instance of the activity will <em>always</em> be immediately 1480 * created after this one's {@link #onDestroy()} is called. In particular, 1481 * <em>no</em> messages will be dispatched during this time (when the returned 1482 * object does not have an activity to be associated with). 1483 * <li> The object you return here will <em>always</em> be available from 1484 * the {@link #getLastNonConfigurationInstance()} method of the following 1485 * activity instance as described there. 1486 * </ul> 1487 * 1488 * <p>These guarantees are designed so that an activity can use this API 1489 * to propagate extensive state from the old to new activity instance, from 1490 * loaded bitmaps, to network connections, to evenly actively running 1491 * threads. Note that you should <em>not</em> propagate any data that 1492 * may change based on the configuration, including any data loaded from 1493 * resources such as strings, layouts, or drawables. 1494 * 1495 * <p>The guarantee of no message handling during the switch to the next 1496 * activity simplifies use with active objects. For example if your retained 1497 * state is an {@link android.os.AsyncTask} you are guaranteed that its 1498 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will 1499 * not be called from the call here until you execute the next instance's 1500 * {@link #onCreate(Bundle)}. (Note however that there is of course no such 1501 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is 1502 * running in a separate thread.) 1503 * 1504 * @return Return any Object holding the desired state to propagate to the 1505 * next activity instance. 1506 */ 1507 public Object onRetainNonConfigurationInstance() { 1508 return null; 1509 } 1510 1511 /** 1512 * Retrieve the non-configuration instance data that was previously 1513 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will 1514 * be available from the initial {@link #onCreate} and 1515 * {@link #onStart} calls to the new instance, allowing you to extract 1516 * any useful dynamic state from the previous instance. 1517 * 1518 * <p>Note that the data you retrieve here should <em>only</em> be used 1519 * as an optimization for handling configuration changes. You should always 1520 * be able to handle getting a null pointer back, and an activity must 1521 * still be able to restore itself to its previous state (through the 1522 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this 1523 * function returns null. 1524 * 1525 * @return Returns the object previously returned by 1526 * {@link #onRetainNonConfigurationChildInstances()} 1527 */ 1528 HashMap<String, Object> getLastNonConfigurationChildInstances() { 1529 return mLastNonConfigurationInstances != null 1530 ? mLastNonConfigurationInstances.children : null; 1531 } 1532 1533 /** 1534 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that 1535 * it should return either a mapping from child activity id strings to arbitrary objects, 1536 * or null. This method is intended to be used by Activity framework subclasses that control a 1537 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply 1538 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null. 1539 */ 1540 HashMap<String,Object> onRetainNonConfigurationChildInstances() { 1541 return null; 1542 } 1543 1544 NonConfigurationInstances retainNonConfigurationInstances() { 1545 Object activity = onRetainNonConfigurationInstance(); 1546 HashMap<String, Object> children = onRetainNonConfigurationChildInstances(); 1547 ArrayList<Fragment> fragments = mFragments.retainNonConfig(); 1548 boolean retainLoaders = false; 1549 if (mAllLoaderManagers != null) { 1550 // prune out any loader managers that were already stopped and so 1551 // have nothing useful to retain. 1552 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) { 1553 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i); 1554 if (lm.mRetaining) { 1555 retainLoaders = true; 1556 } else { 1557 lm.doDestroy(); 1558 mAllLoaderManagers.removeAt(i); 1559 } 1560 } 1561 } 1562 if (activity == null && children == null && fragments == null && !retainLoaders) { 1563 return null; 1564 } 1565 1566 NonConfigurationInstances nci = new NonConfigurationInstances(); 1567 nci.activity = activity; 1568 nci.children = children; 1569 nci.fragments = fragments; 1570 nci.loaders = mAllLoaderManagers; 1571 return nci; 1572 } 1573 1574 public void onLowMemory() { 1575 mCalled = true; 1576 mFragments.dispatchLowMemory(); 1577 } 1578 1579 /** 1580 * Return the FragmentManager for interacting with fragments associated 1581 * with this activity. 1582 */ 1583 public FragmentManager getFragmentManager() { 1584 return mFragments; 1585 } 1586 1587 void invalidateFragmentIndex(int index) { 1588 //Log.v(TAG, "invalidateFragmentIndex: index=" + index); 1589 if (mAllLoaderManagers != null) { 1590 LoaderManagerImpl lm = mAllLoaderManagers.get(index); 1591 if (lm != null) { 1592 lm.doDestroy(); 1593 } 1594 mAllLoaderManagers.remove(index); 1595 } 1596 } 1597 1598 /** 1599 * Called when a Fragment is being attached to this activity, immediately 1600 * after the call to its {@link Fragment#onAttach Fragment.onAttach()} 1601 * method and before {@link Fragment#onCreate Fragment.onCreate()}. 1602 */ 1603 public void onAttachFragment(Fragment fragment) { 1604 } 1605 1606 /** 1607 * Wrapper around 1608 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)} 1609 * that gives the resulting {@link Cursor} to call 1610 * {@link #startManagingCursor} so that the activity will manage its 1611 * lifecycle for you. 1612 * 1613 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 1614 * or later, consider instead using {@link LoaderManager} instead, available 1615 * via {@link #getLoaderManager()}.</em> 1616 * 1617 * @param uri The URI of the content provider to query. 1618 * @param projection List of columns to return. 1619 * @param selection SQL WHERE clause. 1620 * @param sortOrder SQL ORDER BY clause. 1621 * 1622 * @return The Cursor that was returned by query(). 1623 * 1624 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) 1625 * @see #startManagingCursor 1626 * @hide 1627 * 1628 * @deprecated Use {@link CursorLoader} instead. 1629 */ 1630 @Deprecated 1631 public final Cursor managedQuery(Uri uri, String[] projection, String selection, 1632 String sortOrder) { 1633 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder); 1634 if (c != null) { 1635 startManagingCursor(c); 1636 } 1637 return c; 1638 } 1639 1640 /** 1641 * Wrapper around 1642 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)} 1643 * that gives the resulting {@link Cursor} to call 1644 * {@link #startManagingCursor} so that the activity will manage its 1645 * lifecycle for you. 1646 * 1647 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 1648 * or later, consider instead using {@link LoaderManager} instead, available 1649 * via {@link #getLoaderManager()}.</em> 1650 * 1651 * @param uri The URI of the content provider to query. 1652 * @param projection List of columns to return. 1653 * @param selection SQL WHERE clause. 1654 * @param selectionArgs The arguments to selection, if any ?s are pesent 1655 * @param sortOrder SQL ORDER BY clause. 1656 * 1657 * @return The Cursor that was returned by query(). 1658 * 1659 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) 1660 * @see #startManagingCursor 1661 * 1662 * @deprecated Use {@link CursorLoader} instead. 1663 */ 1664 @Deprecated 1665 public final Cursor managedQuery(Uri uri, String[] projection, String selection, 1666 String[] selectionArgs, String sortOrder) { 1667 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); 1668 if (c != null) { 1669 startManagingCursor(c); 1670 } 1671 return c; 1672 } 1673 1674 /** 1675 * This method allows the activity to take care of managing the given 1676 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle. 1677 * That is, when the activity is stopped it will automatically call 1678 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 1679 * it will call {@link Cursor#requery} for you. When the activity is 1680 * destroyed, all managed Cursors will be closed automatically. 1681 * 1682 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 1683 * or later, consider instead using {@link LoaderManager} instead, available 1684 * via {@link #getLoaderManager()}.</em> 1685 * 1686 * @param c The Cursor to be managed. 1687 * 1688 * @see #managedQuery(android.net.Uri , String[], String, String[], String) 1689 * @see #stopManagingCursor 1690 * 1691 * @deprecated Use {@link CursorLoader} instead. 1692 */ 1693 @Deprecated 1694 public void startManagingCursor(Cursor c) { 1695 synchronized (mManagedCursors) { 1696 mManagedCursors.add(new ManagedCursor(c)); 1697 } 1698 } 1699 1700 /** 1701 * Given a Cursor that was previously given to 1702 * {@link #startManagingCursor}, stop the activity's management of that 1703 * cursor. 1704 * 1705 * @param c The Cursor that was being managed. 1706 * 1707 * @see #startManagingCursor 1708 * 1709 * @deprecated Use {@link CursorLoader} instead. 1710 */ 1711 @Deprecated 1712 public void stopManagingCursor(Cursor c) { 1713 synchronized (mManagedCursors) { 1714 final int N = mManagedCursors.size(); 1715 for (int i=0; i<N; i++) { 1716 ManagedCursor mc = mManagedCursors.get(i); 1717 if (mc.mCursor == c) { 1718 mManagedCursors.remove(i); 1719 break; 1720 } 1721 } 1722 } 1723 } 1724 1725 /** 1726 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD} 1727 * this is a no-op. 1728 * @hide 1729 */ 1730 @Deprecated 1731 public void setPersistent(boolean isPersistent) { 1732 } 1733 1734 /** 1735 * Finds a view that was identified by the id attribute from the XML that 1736 * was processed in {@link #onCreate}. 1737 * 1738 * @return The view if found or null otherwise. 1739 */ 1740 public View findViewById(int id) { 1741 return getWindow().findViewById(id); 1742 } 1743 1744 /** 1745 * Retrieve a reference to this activity's ActionBar. 1746 * 1747 * @return The Activity's ActionBar, or null if it does not have one. 1748 */ 1749 public ActionBar getActionBar() { 1750 initActionBar(); 1751 return mActionBar; 1752 } 1753 1754 /** 1755 * Creates a new ActionBar, locates the inflated ActionBarView, 1756 * initializes the ActionBar with the view, and sets mActionBar. 1757 */ 1758 private void initActionBar() { 1759 Window window = getWindow(); 1760 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) { 1761 return; 1762 } 1763 1764 mActionBar = new ActionBarImpl(this); 1765 } 1766 1767 /** 1768 * Set the activity content from a layout resource. The resource will be 1769 * inflated, adding all top-level views to the activity. 1770 * 1771 * @param layoutResID Resource ID to be inflated. 1772 * 1773 * @see #setContentView(android.view.View) 1774 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 1775 */ 1776 public void setContentView(int layoutResID) { 1777 getWindow().setContentView(layoutResID); 1778 initActionBar(); 1779 } 1780 1781 /** 1782 * Set the activity content to an explicit view. This view is placed 1783 * directly into the activity's view hierarchy. It can itself be a complex 1784 * view hierarchy. When calling this method, the layout parameters of the 1785 * specified view are ignored. Both the width and the height of the view are 1786 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use 1787 * your own layout parameters, invoke 1788 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} 1789 * instead. 1790 * 1791 * @param view The desired content to display. 1792 * 1793 * @see #setContentView(int) 1794 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 1795 */ 1796 public void setContentView(View view) { 1797 getWindow().setContentView(view); 1798 initActionBar(); 1799 } 1800 1801 /** 1802 * Set the activity content to an explicit view. This view is placed 1803 * directly into the activity's view hierarchy. It can itself be a complex 1804 * view hierarchy. 1805 * 1806 * @param view The desired content to display. 1807 * @param params Layout parameters for the view. 1808 * 1809 * @see #setContentView(android.view.View) 1810 * @see #setContentView(int) 1811 */ 1812 public void setContentView(View view, ViewGroup.LayoutParams params) { 1813 getWindow().setContentView(view, params); 1814 initActionBar(); 1815 } 1816 1817 /** 1818 * Add an additional content view to the activity. Added after any existing 1819 * ones in the activity -- existing views are NOT removed. 1820 * 1821 * @param view The desired content to display. 1822 * @param params Layout parameters for the view. 1823 */ 1824 public void addContentView(View view, ViewGroup.LayoutParams params) { 1825 getWindow().addContentView(view, params); 1826 initActionBar(); 1827 } 1828 1829 /** 1830 * Sets whether this activity is finished when touched outside its window's 1831 * bounds. 1832 */ 1833 public void setFinishOnTouchOutside(boolean finish) { 1834 mWindow.setCloseOnTouchOutside(finish); 1835 } 1836 1837 /** 1838 * Use with {@link #setDefaultKeyMode} to turn off default handling of 1839 * keys. 1840 * 1841 * @see #setDefaultKeyMode 1842 */ 1843 static public final int DEFAULT_KEYS_DISABLE = 0; 1844 /** 1845 * Use with {@link #setDefaultKeyMode} to launch the dialer during default 1846 * key handling. 1847 * 1848 * @see #setDefaultKeyMode 1849 */ 1850 static public final int DEFAULT_KEYS_DIALER = 1; 1851 /** 1852 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in 1853 * default key handling. 1854 * 1855 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts. 1856 * 1857 * @see #setDefaultKeyMode 1858 */ 1859 static public final int DEFAULT_KEYS_SHORTCUT = 2; 1860 /** 1861 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes 1862 * will start an application-defined search. (If the application or activity does not 1863 * actually define a search, the the keys will be ignored.) 1864 * 1865 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details. 1866 * 1867 * @see #setDefaultKeyMode 1868 */ 1869 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3; 1870 1871 /** 1872 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes 1873 * will start a global search (typically web search, but some platforms may define alternate 1874 * methods for global search) 1875 * 1876 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details. 1877 * 1878 * @see #setDefaultKeyMode 1879 */ 1880 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4; 1881 1882 /** 1883 * Select the default key handling for this activity. This controls what 1884 * will happen to key events that are not otherwise handled. The default 1885 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the 1886 * floor. Other modes allow you to launch the dialer 1887 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options 1888 * menu without requiring the menu key be held down 1889 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL} 1890 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}). 1891 * 1892 * <p>Note that the mode selected here does not impact the default 1893 * handling of system keys, such as the "back" and "menu" keys, and your 1894 * activity and its views always get a first chance to receive and handle 1895 * all application keys. 1896 * 1897 * @param mode The desired default key mode constant. 1898 * 1899 * @see #DEFAULT_KEYS_DISABLE 1900 * @see #DEFAULT_KEYS_DIALER 1901 * @see #DEFAULT_KEYS_SHORTCUT 1902 * @see #DEFAULT_KEYS_SEARCH_LOCAL 1903 * @see #DEFAULT_KEYS_SEARCH_GLOBAL 1904 * @see #onKeyDown 1905 */ 1906 public final void setDefaultKeyMode(int mode) { 1907 mDefaultKeyMode = mode; 1908 1909 // Some modes use a SpannableStringBuilder to track & dispatch input events 1910 // This list must remain in sync with the switch in onKeyDown() 1911 switch (mode) { 1912 case DEFAULT_KEYS_DISABLE: 1913 case DEFAULT_KEYS_SHORTCUT: 1914 mDefaultKeySsb = null; // not used in these modes 1915 break; 1916 case DEFAULT_KEYS_DIALER: 1917 case DEFAULT_KEYS_SEARCH_LOCAL: 1918 case DEFAULT_KEYS_SEARCH_GLOBAL: 1919 mDefaultKeySsb = new SpannableStringBuilder(); 1920 Selection.setSelection(mDefaultKeySsb,0); 1921 break; 1922 default: 1923 throw new IllegalArgumentException(); 1924 } 1925 } 1926 1927 /** 1928 * Called when a key was pressed down and not handled by any of the views 1929 * inside of the activity. So, for example, key presses while the cursor 1930 * is inside a TextView will not trigger the event (unless it is a navigation 1931 * to another object) because TextView handles its own key presses. 1932 * 1933 * <p>If the focused view didn't want this event, this method is called. 1934 * 1935 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK} 1936 * by calling {@link #onBackPressed()}, though the behavior varies based 1937 * on the application compatibility mode: for 1938 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications, 1939 * it will set up the dispatch to call {@link #onKeyUp} where the action 1940 * will be performed; for earlier applications, it will perform the 1941 * action immediately in on-down, as those versions of the platform 1942 * behaved. 1943 * 1944 * <p>Other additional default key handling may be performed 1945 * if configured with {@link #setDefaultKeyMode}. 1946 * 1947 * @return Return <code>true</code> to prevent this event from being propagated 1948 * further, or <code>false</code> to indicate that you have not handled 1949 * this event and it should continue to be propagated. 1950 * @see #onKeyUp 1951 * @see android.view.KeyEvent 1952 */ 1953 public boolean onKeyDown(int keyCode, KeyEvent event) { 1954 if (keyCode == KeyEvent.KEYCODE_BACK) { 1955 if (getApplicationInfo().targetSdkVersion 1956 >= Build.VERSION_CODES.ECLAIR) { 1957 event.startTracking(); 1958 } else { 1959 onBackPressed(); 1960 } 1961 return true; 1962 } 1963 1964 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) { 1965 return false; 1966 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) { 1967 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, 1968 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) { 1969 return true; 1970 } 1971 return false; 1972 } else { 1973 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_* 1974 boolean clearSpannable = false; 1975 boolean handled; 1976 if ((event.getRepeatCount() != 0) || event.isSystem()) { 1977 clearSpannable = true; 1978 handled = false; 1979 } else { 1980 handled = TextKeyListener.getInstance().onKeyDown( 1981 null, mDefaultKeySsb, keyCode, event); 1982 if (handled && mDefaultKeySsb.length() > 0) { 1983 // something useable has been typed - dispatch it now. 1984 1985 final String str = mDefaultKeySsb.toString(); 1986 clearSpannable = true; 1987 1988 switch (mDefaultKeyMode) { 1989 case DEFAULT_KEYS_DIALER: 1990 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str)); 1991 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1992 startActivity(intent); 1993 break; 1994 case DEFAULT_KEYS_SEARCH_LOCAL: 1995 startSearch(str, false, null, false); 1996 break; 1997 case DEFAULT_KEYS_SEARCH_GLOBAL: 1998 startSearch(str, false, null, true); 1999 break; 2000 } 2001 } 2002 } 2003 if (clearSpannable) { 2004 mDefaultKeySsb.clear(); 2005 mDefaultKeySsb.clearSpans(); 2006 Selection.setSelection(mDefaultKeySsb,0); 2007 } 2008 return handled; 2009 } 2010 } 2011 2012 /** 2013 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 2014 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 2015 * the event). 2016 */ 2017 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 2018 return false; 2019 } 2020 2021 /** 2022 * Called when a key was released and not handled by any of the views 2023 * inside of the activity. So, for example, key presses while the cursor 2024 * is inside a TextView will not trigger the event (unless it is a navigation 2025 * to another object) because TextView handles its own key presses. 2026 * 2027 * <p>The default implementation handles KEYCODE_BACK to stop the activity 2028 * and go back. 2029 * 2030 * @return Return <code>true</code> to prevent this event from being propagated 2031 * further, or <code>false</code> to indicate that you have not handled 2032 * this event and it should continue to be propagated. 2033 * @see #onKeyDown 2034 * @see KeyEvent 2035 */ 2036 public boolean onKeyUp(int keyCode, KeyEvent event) { 2037 if (getApplicationInfo().targetSdkVersion 2038 >= Build.VERSION_CODES.ECLAIR) { 2039 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() 2040 && !event.isCanceled()) { 2041 onBackPressed(); 2042 return true; 2043 } 2044 } 2045 return false; 2046 } 2047 2048 /** 2049 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 2050 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 2051 * the event). 2052 */ 2053 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 2054 return false; 2055 } 2056 2057 /** 2058 * Called when the activity has detected the user's press of the back 2059 * key. The default implementation simply finishes the current activity, 2060 * but you can override this to do whatever you want. 2061 */ 2062 public void onBackPressed() { 2063 if (!mFragments.popBackStackImmediate()) { 2064 finish(); 2065 } 2066 } 2067 2068 /** 2069 * Called when a key shortcut event is not handled by any of the views in the Activity. 2070 * Override this method to implement global key shortcuts for the Activity. 2071 * Key shortcuts can also be implemented by setting the 2072 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 2073 * 2074 * @param keyCode The value in event.getKeyCode(). 2075 * @param event Description of the key event. 2076 * @return True if the key shortcut was handled. 2077 */ 2078 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 2079 return false; 2080 } 2081 2082 /** 2083 * Called when a touch screen event was not handled by any of the views 2084 * under it. This is most useful to process touch events that happen 2085 * outside of your window bounds, where there is no view to receive it. 2086 * 2087 * @param event The touch screen event being processed. 2088 * 2089 * @return Return true if you have consumed the event, false if you haven't. 2090 * The default implementation always returns false. 2091 */ 2092 public boolean onTouchEvent(MotionEvent event) { 2093 if (mWindow.shouldCloseOnTouch(this, event)) { 2094 finish(); 2095 return true; 2096 } 2097 2098 return false; 2099 } 2100 2101 /** 2102 * Called when the trackball was moved and not handled by any of the 2103 * views inside of the activity. So, for example, if the trackball moves 2104 * while focus is on a button, you will receive a call here because 2105 * buttons do not normally do anything with trackball events. The call 2106 * here happens <em>before</em> trackball movements are converted to 2107 * DPAD key events, which then get sent back to the view hierarchy, and 2108 * will be processed at the point for things like focus navigation. 2109 * 2110 * @param event The trackball event being processed. 2111 * 2112 * @return Return true if you have consumed the event, false if you haven't. 2113 * The default implementation always returns false. 2114 */ 2115 public boolean onTrackballEvent(MotionEvent event) { 2116 return false; 2117 } 2118 2119 /** 2120 * Called whenever a key, touch, or trackball event is dispatched to the 2121 * activity. Implement this method if you wish to know that the user has 2122 * interacted with the device in some way while your activity is running. 2123 * This callback and {@link #onUserLeaveHint} are intended to help 2124 * activities manage status bar notifications intelligently; specifically, 2125 * for helping activities determine the proper time to cancel a notfication. 2126 * 2127 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will 2128 * be accompanied by calls to {@link #onUserInteraction}. This 2129 * ensures that your activity will be told of relevant user activity such 2130 * as pulling down the notification pane and touching an item there. 2131 * 2132 * <p>Note that this callback will be invoked for the touch down action 2133 * that begins a touch gesture, but may not be invoked for the touch-moved 2134 * and touch-up actions that follow. 2135 * 2136 * @see #onUserLeaveHint() 2137 */ 2138 public void onUserInteraction() { 2139 } 2140 2141 public void onWindowAttributesChanged(WindowManager.LayoutParams params) { 2142 // Update window manager if: we have a view, that view is 2143 // attached to its parent (which will be a RootView), and 2144 // this activity is not embedded. 2145 if (mParent == null) { 2146 View decor = mDecor; 2147 if (decor != null && decor.getParent() != null) { 2148 getWindowManager().updateViewLayout(decor, params); 2149 } 2150 } 2151 } 2152 2153 public void onContentChanged() { 2154 } 2155 2156 /** 2157 * Called when the current {@link Window} of the activity gains or loses 2158 * focus. This is the best indicator of whether this activity is visible 2159 * to the user. The default implementation clears the key tracking 2160 * state, so should always be called. 2161 * 2162 * <p>Note that this provides information about global focus state, which 2163 * is managed independently of activity lifecycles. As such, while focus 2164 * changes will generally have some relation to lifecycle changes (an 2165 * activity that is stopped will not generally get window focus), you 2166 * should not rely on any particular order between the callbacks here and 2167 * those in the other lifecycle methods such as {@link #onResume}. 2168 * 2169 * <p>As a general rule, however, a resumed activity will have window 2170 * focus... unless it has displayed other dialogs or popups that take 2171 * input focus, in which case the activity itself will not have focus 2172 * when the other windows have it. Likewise, the system may display 2173 * system-level windows (such as the status bar notification panel or 2174 * a system alert) which will temporarily take window input focus without 2175 * pausing the foreground activity. 2176 * 2177 * @param hasFocus Whether the window of this activity has focus. 2178 * 2179 * @see #hasWindowFocus() 2180 * @see #onResume 2181 * @see View#onWindowFocusChanged(boolean) 2182 */ 2183 public void onWindowFocusChanged(boolean hasFocus) { 2184 } 2185 2186 /** 2187 * Called when the main window associated with the activity has been 2188 * attached to the window manager. 2189 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()} 2190 * for more information. 2191 * @see View#onAttachedToWindow 2192 */ 2193 public void onAttachedToWindow() { 2194 } 2195 2196 /** 2197 * Called when the main window associated with the activity has been 2198 * detached from the window manager. 2199 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()} 2200 * for more information. 2201 * @see View#onDetachedFromWindow 2202 */ 2203 public void onDetachedFromWindow() { 2204 } 2205 2206 /** 2207 * Returns true if this activity's <em>main</em> window currently has window focus. 2208 * Note that this is not the same as the view itself having focus. 2209 * 2210 * @return True if this activity's main window currently has window focus. 2211 * 2212 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams) 2213 */ 2214 public boolean hasWindowFocus() { 2215 Window w = getWindow(); 2216 if (w != null) { 2217 View d = w.getDecorView(); 2218 if (d != null) { 2219 return d.hasWindowFocus(); 2220 } 2221 } 2222 return false; 2223 } 2224 2225 /** 2226 * Called to process key events. You can override this to intercept all 2227 * key events before they are dispatched to the window. Be sure to call 2228 * this implementation for key events that should be handled normally. 2229 * 2230 * @param event The key event. 2231 * 2232 * @return boolean Return true if this event was consumed. 2233 */ 2234 public boolean dispatchKeyEvent(KeyEvent event) { 2235 onUserInteraction(); 2236 Window win = getWindow(); 2237 if (win.superDispatchKeyEvent(event)) { 2238 return true; 2239 } 2240 View decor = mDecor; 2241 if (decor == null) decor = win.getDecorView(); 2242 return event.dispatch(this, decor != null 2243 ? decor.getKeyDispatcherState() : null, this); 2244 } 2245 2246 /** 2247 * Called to process a key shortcut event. 2248 * You can override this to intercept all key shortcut events before they are 2249 * dispatched to the window. Be sure to call this implementation for key shortcut 2250 * events that should be handled normally. 2251 * 2252 * @param event The key shortcut event. 2253 * @return True if this event was consumed. 2254 */ 2255 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 2256 onUserInteraction(); 2257 if (getWindow().superDispatchKeyShortcutEvent(event)) { 2258 return true; 2259 } 2260 return onKeyShortcut(event.getKeyCode(), event); 2261 } 2262 2263 /** 2264 * Called to process touch screen events. You can override this to 2265 * intercept all touch screen events before they are dispatched to the 2266 * window. Be sure to call this implementation for touch screen events 2267 * that should be handled normally. 2268 * 2269 * @param ev The touch screen event. 2270 * 2271 * @return boolean Return true if this event was consumed. 2272 */ 2273 public boolean dispatchTouchEvent(MotionEvent ev) { 2274 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 2275 onUserInteraction(); 2276 } 2277 if (getWindow().superDispatchTouchEvent(ev)) { 2278 return true; 2279 } 2280 return onTouchEvent(ev); 2281 } 2282 2283 /** 2284 * Called to process trackball events. You can override this to 2285 * intercept all trackball events before they are dispatched to the 2286 * window. Be sure to call this implementation for trackball events 2287 * that should be handled normally. 2288 * 2289 * @param ev The trackball event. 2290 * 2291 * @return boolean Return true if this event was consumed. 2292 */ 2293 public boolean dispatchTrackballEvent(MotionEvent ev) { 2294 onUserInteraction(); 2295 if (getWindow().superDispatchTrackballEvent(ev)) { 2296 return true; 2297 } 2298 return onTrackballEvent(ev); 2299 } 2300 2301 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 2302 event.setClassName(getClass().getName()); 2303 event.setPackageName(getPackageName()); 2304 2305 LayoutParams params = getWindow().getAttributes(); 2306 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) && 2307 (params.height == LayoutParams.MATCH_PARENT); 2308 event.setFullScreen(isFullScreen); 2309 2310 CharSequence title = getTitle(); 2311 if (!TextUtils.isEmpty(title)) { 2312 event.getText().add(title); 2313 } 2314 2315 return true; 2316 } 2317 2318 /** 2319 * Default implementation of 2320 * {@link android.view.Window.Callback#onCreatePanelView} 2321 * for activities. This 2322 * simply returns null so that all panel sub-windows will have the default 2323 * menu behavior. 2324 */ 2325 public View onCreatePanelView(int featureId) { 2326 return null; 2327 } 2328 2329 /** 2330 * Default implementation of 2331 * {@link android.view.Window.Callback#onCreatePanelMenu} 2332 * for activities. This calls through to the new 2333 * {@link #onCreateOptionsMenu} method for the 2334 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel, 2335 * so that subclasses of Activity don't need to deal with feature codes. 2336 */ 2337 public boolean onCreatePanelMenu(int featureId, Menu menu) { 2338 if (featureId == Window.FEATURE_OPTIONS_PANEL) { 2339 boolean show = onCreateOptionsMenu(menu); 2340 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater()); 2341 return show; 2342 } 2343 return false; 2344 } 2345 2346 /** 2347 * Default implementation of 2348 * {@link android.view.Window.Callback#onPreparePanel} 2349 * for activities. This 2350 * calls through to the new {@link #onPrepareOptionsMenu} method for the 2351 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} 2352 * panel, so that subclasses of 2353 * Activity don't need to deal with feature codes. 2354 */ 2355 public boolean onPreparePanel(int featureId, View view, Menu menu) { 2356 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) { 2357 boolean goforit = onPrepareOptionsMenu(menu); 2358 goforit |= mFragments.dispatchPrepareOptionsMenu(menu); 2359 return goforit && menu.hasVisibleItems(); 2360 } 2361 return true; 2362 } 2363 2364 /** 2365 * {@inheritDoc} 2366 * 2367 * @return The default implementation returns true. 2368 */ 2369 public boolean onMenuOpened(int featureId, Menu menu) { 2370 if (featureId == Window.FEATURE_ACTION_BAR) { 2371 if (mActionBar != null) { 2372 mActionBar.dispatchMenuVisibilityChanged(true); 2373 } else { 2374 Log.e(TAG, "Tried to open action bar menu with no action bar"); 2375 } 2376 } 2377 return true; 2378 } 2379 2380 /** 2381 * Default implementation of 2382 * {@link android.view.Window.Callback#onMenuItemSelected} 2383 * for activities. This calls through to the new 2384 * {@link #onOptionsItemSelected} method for the 2385 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} 2386 * panel, so that subclasses of 2387 * Activity don't need to deal with feature codes. 2388 */ 2389 public boolean onMenuItemSelected(int featureId, MenuItem item) { 2390 switch (featureId) { 2391 case Window.FEATURE_OPTIONS_PANEL: 2392 // Put event logging here so it gets called even if subclass 2393 // doesn't call through to superclass's implmeentation of each 2394 // of these methods below 2395 EventLog.writeEvent(50000, 0, item.getTitleCondensed()); 2396 if (onOptionsItemSelected(item)) { 2397 return true; 2398 } 2399 return mFragments.dispatchOptionsItemSelected(item); 2400 2401 case Window.FEATURE_CONTEXT_MENU: 2402 EventLog.writeEvent(50000, 1, item.getTitleCondensed()); 2403 if (onContextItemSelected(item)) { 2404 return true; 2405 } 2406 return mFragments.dispatchContextItemSelected(item); 2407 2408 default: 2409 return false; 2410 } 2411 } 2412 2413 /** 2414 * Default implementation of 2415 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for 2416 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)} 2417 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel, 2418 * so that subclasses of Activity don't need to deal with feature codes. 2419 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the 2420 * {@link #onContextMenuClosed(Menu)} will be called. 2421 */ 2422 public void onPanelClosed(int featureId, Menu menu) { 2423 switch (featureId) { 2424 case Window.FEATURE_OPTIONS_PANEL: 2425 mFragments.dispatchOptionsMenuClosed(menu); 2426 onOptionsMenuClosed(menu); 2427 break; 2428 2429 case Window.FEATURE_CONTEXT_MENU: 2430 onContextMenuClosed(menu); 2431 break; 2432 2433 case Window.FEATURE_ACTION_BAR: 2434 mActionBar.dispatchMenuVisibilityChanged(false); 2435 break; 2436 } 2437 } 2438 2439 /** 2440 * Declare that the options menu has changed, so should be recreated. 2441 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next 2442 * time it needs to be displayed. 2443 */ 2444 public void invalidateOptionsMenu() { 2445 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); 2446 } 2447 2448 /** 2449 * Initialize the contents of the Activity's standard options menu. You 2450 * should place your menu items in to <var>menu</var>. 2451 * 2452 * <p>This is only called once, the first time the options menu is 2453 * displayed. To update the menu every time it is displayed, see 2454 * {@link #onPrepareOptionsMenu}. 2455 * 2456 * <p>The default implementation populates the menu with standard system 2457 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that 2458 * they will be correctly ordered with application-defined menu items. 2459 * Deriving classes should always call through to the base implementation. 2460 * 2461 * <p>You can safely hold on to <var>menu</var> (and any items created 2462 * from it), making modifications to it as desired, until the next 2463 * time onCreateOptionsMenu() is called. 2464 * 2465 * <p>When you add items to the menu, you can implement the Activity's 2466 * {@link #onOptionsItemSelected} method to handle them there. 2467 * 2468 * @param menu The options menu in which you place your items. 2469 * 2470 * @return You must return true for the menu to be displayed; 2471 * if you return false it will not be shown. 2472 * 2473 * @see #onPrepareOptionsMenu 2474 * @see #onOptionsItemSelected 2475 */ 2476 public boolean onCreateOptionsMenu(Menu menu) { 2477 if (mParent != null) { 2478 return mParent.onCreateOptionsMenu(menu); 2479 } 2480 return true; 2481 } 2482 2483 /** 2484 * Prepare the Screen's standard options menu to be displayed. This is 2485 * called right before the menu is shown, every time it is shown. You can 2486 * use this method to efficiently enable/disable items or otherwise 2487 * dynamically modify the contents. 2488 * 2489 * <p>The default implementation updates the system menu items based on the 2490 * activity's state. Deriving classes should always call through to the 2491 * base class implementation. 2492 * 2493 * @param menu The options menu as last shown or first initialized by 2494 * onCreateOptionsMenu(). 2495 * 2496 * @return You must return true for the menu to be displayed; 2497 * if you return false it will not be shown. 2498 * 2499 * @see #onCreateOptionsMenu 2500 */ 2501 public boolean onPrepareOptionsMenu(Menu menu) { 2502 if (mParent != null) { 2503 return mParent.onPrepareOptionsMenu(menu); 2504 } 2505 return true; 2506 } 2507 2508 /** 2509 * This hook is called whenever an item in your options menu is selected. 2510 * The default implementation simply returns false to have the normal 2511 * processing happen (calling the item's Runnable or sending a message to 2512 * its Handler as appropriate). You can use this method for any items 2513 * for which you would like to do processing without those other 2514 * facilities. 2515 * 2516 * <p>Derived classes should call through to the base class for it to 2517 * perform the default menu handling. 2518 * 2519 * @param item The menu item that was selected. 2520 * 2521 * @return boolean Return false to allow normal menu processing to 2522 * proceed, true to consume it here. 2523 * 2524 * @see #onCreateOptionsMenu 2525 */ 2526 public boolean onOptionsItemSelected(MenuItem item) { 2527 if (mParent != null) { 2528 return mParent.onOptionsItemSelected(item); 2529 } 2530 return false; 2531 } 2532 2533 /** 2534 * This hook is called whenever the options menu is being closed (either by the user canceling 2535 * the menu with the back/menu button, or when an item is selected). 2536 * 2537 * @param menu The options menu as last shown or first initialized by 2538 * onCreateOptionsMenu(). 2539 */ 2540 public void onOptionsMenuClosed(Menu menu) { 2541 if (mParent != null) { 2542 mParent.onOptionsMenuClosed(menu); 2543 } 2544 } 2545 2546 /** 2547 * Programmatically opens the options menu. If the options menu is already 2548 * open, this method does nothing. 2549 */ 2550 public void openOptionsMenu() { 2551 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null); 2552 } 2553 2554 /** 2555 * Progammatically closes the options menu. If the options menu is already 2556 * closed, this method does nothing. 2557 */ 2558 public void closeOptionsMenu() { 2559 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL); 2560 } 2561 2562 /** 2563 * Called when a context menu for the {@code view} is about to be shown. 2564 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every 2565 * time the context menu is about to be shown and should be populated for 2566 * the view (or item inside the view for {@link AdapterView} subclasses, 2567 * this can be found in the {@code menuInfo})). 2568 * <p> 2569 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an 2570 * item has been selected. 2571 * <p> 2572 * It is not safe to hold onto the context menu after this method returns. 2573 * {@inheritDoc} 2574 */ 2575 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 2576 } 2577 2578 /** 2579 * Registers a context menu to be shown for the given view (multiple views 2580 * can show the context menu). This method will set the 2581 * {@link OnCreateContextMenuListener} on the view to this activity, so 2582 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 2583 * called when it is time to show the context menu. 2584 * 2585 * @see #unregisterForContextMenu(View) 2586 * @param view The view that should show a context menu. 2587 */ 2588 public void registerForContextMenu(View view) { 2589 view.setOnCreateContextMenuListener(this); 2590 } 2591 2592 /** 2593 * Prevents a context menu to be shown for the given view. This method will remove the 2594 * {@link OnCreateContextMenuListener} on the view. 2595 * 2596 * @see #registerForContextMenu(View) 2597 * @param view The view that should stop showing a context menu. 2598 */ 2599 public void unregisterForContextMenu(View view) { 2600 view.setOnCreateContextMenuListener(null); 2601 } 2602 2603 /** 2604 * Programmatically opens the context menu for a particular {@code view}. 2605 * The {@code view} should have been added via 2606 * {@link #registerForContextMenu(View)}. 2607 * 2608 * @param view The view to show the context menu for. 2609 */ 2610 public void openContextMenu(View view) { 2611 view.showContextMenu(); 2612 } 2613 2614 /** 2615 * Programmatically closes the most recently opened context menu, if showing. 2616 */ 2617 public void closeContextMenu() { 2618 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU); 2619 } 2620 2621 /** 2622 * This hook is called whenever an item in a context menu is selected. The 2623 * default implementation simply returns false to have the normal processing 2624 * happen (calling the item's Runnable or sending a message to its Handler 2625 * as appropriate). You can use this method for any items for which you 2626 * would like to do processing without those other facilities. 2627 * <p> 2628 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the 2629 * View that added this menu item. 2630 * <p> 2631 * Derived classes should call through to the base class for it to perform 2632 * the default menu handling. 2633 * 2634 * @param item The context menu item that was selected. 2635 * @return boolean Return false to allow normal context menu processing to 2636 * proceed, true to consume it here. 2637 */ 2638 public boolean onContextItemSelected(MenuItem item) { 2639 if (mParent != null) { 2640 return mParent.onContextItemSelected(item); 2641 } 2642 return false; 2643 } 2644 2645 /** 2646 * This hook is called whenever the context menu is being closed (either by 2647 * the user canceling the menu with the back/menu button, or when an item is 2648 * selected). 2649 * 2650 * @param menu The context menu that is being closed. 2651 */ 2652 public void onContextMenuClosed(Menu menu) { 2653 if (mParent != null) { 2654 mParent.onContextMenuClosed(menu); 2655 } 2656 } 2657 2658 /** 2659 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}. 2660 */ 2661 @Deprecated 2662 protected Dialog onCreateDialog(int id) { 2663 return null; 2664 } 2665 2666 /** 2667 * Callback for creating dialogs that are managed (saved and restored) for you 2668 * by the activity. The default implementation calls through to 2669 * {@link #onCreateDialog(int)} for compatibility. 2670 * 2671 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2672 * or later, consider instead using a {@link DialogFragment} instead.</em> 2673 * 2674 * <p>If you use {@link #showDialog(int)}, the activity will call through to 2675 * this method the first time, and hang onto it thereafter. Any dialog 2676 * that is created by this method will automatically be saved and restored 2677 * for you, including whether it is showing. 2678 * 2679 * <p>If you would like the activity to manage saving and restoring dialogs 2680 * for you, you should override this method and handle any ids that are 2681 * passed to {@link #showDialog}. 2682 * 2683 * <p>If you would like an opportunity to prepare your dialog before it is shown, 2684 * override {@link #onPrepareDialog(int, Dialog, Bundle)}. 2685 * 2686 * @param id The id of the dialog. 2687 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}. 2688 * @return The dialog. If you return null, the dialog will not be created. 2689 * 2690 * @see #onPrepareDialog(int, Dialog, Bundle) 2691 * @see #showDialog(int, Bundle) 2692 * @see #dismissDialog(int) 2693 * @see #removeDialog(int) 2694 */ 2695 protected Dialog onCreateDialog(int id, Bundle args) { 2696 return onCreateDialog(id); 2697 } 2698 2699 /** 2700 * @deprecated Old no-arguments version of 2701 * {@link #onPrepareDialog(int, Dialog, Bundle)}. 2702 */ 2703 @Deprecated 2704 protected void onPrepareDialog(int id, Dialog dialog) { 2705 dialog.setOwnerActivity(this); 2706 } 2707 2708 /** 2709 * Provides an opportunity to prepare a managed dialog before it is being 2710 * shown. The default implementation calls through to 2711 * {@link #onPrepareDialog(int, Dialog)} for compatibility. 2712 * 2713 * <p> 2714 * Override this if you need to update a managed dialog based on the state 2715 * of the application each time it is shown. For example, a time picker 2716 * dialog might want to be updated with the current time. You should call 2717 * through to the superclass's implementation. The default implementation 2718 * will set this Activity as the owner activity on the Dialog. 2719 * 2720 * @param id The id of the managed dialog. 2721 * @param dialog The dialog. 2722 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}. 2723 * @see #onCreateDialog(int, Bundle) 2724 * @see #showDialog(int) 2725 * @see #dismissDialog(int) 2726 * @see #removeDialog(int) 2727 */ 2728 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { 2729 onPrepareDialog(id, dialog); 2730 } 2731 2732 /** 2733 * Simple version of {@link #showDialog(int, Bundle)} that does not 2734 * take any arguments. Simply calls {@link #showDialog(int, Bundle)} 2735 * with null arguments. 2736 */ 2737 public final void showDialog(int id) { 2738 showDialog(id, null); 2739 } 2740 2741 /** 2742 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)} 2743 * will be made with the same id the first time this is called for a given 2744 * id. From thereafter, the dialog will be automatically saved and restored. 2745 * 2746 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2747 * or later, consider instead using a {@link DialogFragment} instead.</em> 2748 * 2749 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will 2750 * be made to provide an opportunity to do any timely preparation. 2751 * 2752 * @param id The id of the managed dialog. 2753 * @param args Arguments to pass through to the dialog. These will be saved 2754 * and restored for you. Note that if the dialog is already created, 2755 * {@link #onCreateDialog(int, Bundle)} will not be called with the new 2756 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be. 2757 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first. 2758 * @return Returns true if the Dialog was created; false is returned if 2759 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false. 2760 * 2761 * @see Dialog 2762 * @see #onCreateDialog(int, Bundle) 2763 * @see #onPrepareDialog(int, Dialog, Bundle) 2764 * @see #dismissDialog(int) 2765 * @see #removeDialog(int) 2766 */ 2767 public final boolean showDialog(int id, Bundle args) { 2768 if (mManagedDialogs == null) { 2769 mManagedDialogs = new SparseArray<ManagedDialog>(); 2770 } 2771 ManagedDialog md = mManagedDialogs.get(id); 2772 if (md == null) { 2773 md = new ManagedDialog(); 2774 md.mDialog = createDialog(id, null, args); 2775 if (md.mDialog == null) { 2776 return false; 2777 } 2778 mManagedDialogs.put(id, md); 2779 } 2780 2781 md.mArgs = args; 2782 onPrepareDialog(id, md.mDialog, args); 2783 md.mDialog.show(); 2784 return true; 2785 } 2786 2787 /** 2788 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}. 2789 * 2790 * @param id The id of the managed dialog. 2791 * 2792 * @throws IllegalArgumentException if the id was not previously shown via 2793 * {@link #showDialog(int)}. 2794 * 2795 * @see #onCreateDialog(int, Bundle) 2796 * @see #onPrepareDialog(int, Dialog, Bundle) 2797 * @see #showDialog(int) 2798 * @see #removeDialog(int) 2799 */ 2800 public final void dismissDialog(int id) { 2801 if (mManagedDialogs == null) { 2802 throw missingDialog(id); 2803 } 2804 2805 final ManagedDialog md = mManagedDialogs.get(id); 2806 if (md == null) { 2807 throw missingDialog(id); 2808 } 2809 md.mDialog.dismiss(); 2810 } 2811 2812 /** 2813 * Creates an exception to throw if a user passed in a dialog id that is 2814 * unexpected. 2815 */ 2816 private IllegalArgumentException missingDialog(int id) { 2817 return new IllegalArgumentException("no dialog with id " + id + " was ever " 2818 + "shown via Activity#showDialog"); 2819 } 2820 2821 /** 2822 * Removes any internal references to a dialog managed by this Activity. 2823 * If the dialog is showing, it will dismiss it as part of the clean up. 2824 * 2825 * <p>This can be useful if you know that you will never show a dialog again and 2826 * want to avoid the overhead of saving and restoring it in the future. 2827 * 2828 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function 2829 * will not throw an exception if you try to remove an ID that does not 2830 * currently have an associated dialog.</p> 2831 * 2832 * @param id The id of the managed dialog. 2833 * 2834 * @see #onCreateDialog(int, Bundle) 2835 * @see #onPrepareDialog(int, Dialog, Bundle) 2836 * @see #showDialog(int) 2837 * @see #dismissDialog(int) 2838 */ 2839 public final void removeDialog(int id) { 2840 if (mManagedDialogs != null) { 2841 final ManagedDialog md = mManagedDialogs.get(id); 2842 if (md != null) { 2843 md.mDialog.dismiss(); 2844 mManagedDialogs.remove(id); 2845 } 2846 } 2847 } 2848 2849 /** 2850 * This hook is called when the user signals the desire to start a search. 2851 * 2852 * <p>You can use this function as a simple way to launch the search UI, in response to a 2853 * menu item, search button, or other widgets within your activity. Unless overidden, 2854 * calling this function is the same as calling 2855 * {@link #startSearch startSearch(null, false, null, false)}, which launches 2856 * search for the current activity as specified in its manifest, see {@link SearchManager}. 2857 * 2858 * <p>You can override this function to force global search, e.g. in response to a dedicated 2859 * search key, or to block search entirely (by simply returning false). 2860 * 2861 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it. 2862 * The default implementation always returns {@code true}. 2863 * 2864 * @see android.app.SearchManager 2865 */ 2866 public boolean onSearchRequested() { 2867 startSearch(null, false, null, false); 2868 return true; 2869 } 2870 2871 /** 2872 * This hook is called to launch the search UI. 2873 * 2874 * <p>It is typically called from onSearchRequested(), either directly from 2875 * Activity.onSearchRequested() or from an overridden version in any given 2876 * Activity. If your goal is simply to activate search, it is preferred to call 2877 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal 2878 * is to inject specific data such as context data, it is preferred to <i>override</i> 2879 * onSearchRequested(), so that any callers to it will benefit from the override. 2880 * 2881 * @param initialQuery Any non-null non-empty string will be inserted as 2882 * pre-entered text in the search query box. 2883 * @param selectInitialQuery If true, the intial query will be preselected, which means that 2884 * any further typing will replace it. This is useful for cases where an entire pre-formed 2885 * query is being inserted. If false, the selection point will be placed at the end of the 2886 * inserted query. This is useful when the inserted query is text that the user entered, 2887 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful 2888 * if initialQuery is a non-empty string.</i> 2889 * @param appSearchData An application can insert application-specific 2890 * context here, in order to improve quality or specificity of its own 2891 * searches. This data will be returned with SEARCH intent(s). Null if 2892 * no extra data is required. 2893 * @param globalSearch If false, this will only launch the search that has been specifically 2894 * defined by the application (which is usually defined as a local search). If no default 2895 * search is defined in the current application or activity, global search will be launched. 2896 * If true, this will always launch a platform-global (e.g. web-based) search instead. 2897 * 2898 * @see android.app.SearchManager 2899 * @see #onSearchRequested 2900 */ 2901 public void startSearch(String initialQuery, boolean selectInitialQuery, 2902 Bundle appSearchData, boolean globalSearch) { 2903 ensureSearchManager(); 2904 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), 2905 appSearchData, globalSearch); 2906 } 2907 2908 /** 2909 * Similar to {@link #startSearch}, but actually fires off the search query after invoking 2910 * the search dialog. Made available for testing purposes. 2911 * 2912 * @param query The query to trigger. If empty, the request will be ignored. 2913 * @param appSearchData An application can insert application-specific 2914 * context here, in order to improve quality or specificity of its own 2915 * searches. This data will be returned with SEARCH intent(s). Null if 2916 * no extra data is required. 2917 */ 2918 public void triggerSearch(String query, Bundle appSearchData) { 2919 ensureSearchManager(); 2920 mSearchManager.triggerSearch(query, getComponentName(), appSearchData); 2921 } 2922 2923 /** 2924 * Request that key events come to this activity. Use this if your 2925 * activity has no views with focus, but the activity still wants 2926 * a chance to process key events. 2927 * 2928 * @see android.view.Window#takeKeyEvents 2929 */ 2930 public void takeKeyEvents(boolean get) { 2931 getWindow().takeKeyEvents(get); 2932 } 2933 2934 /** 2935 * Enable extended window features. This is a convenience for calling 2936 * {@link android.view.Window#requestFeature getWindow().requestFeature()}. 2937 * 2938 * @param featureId The desired feature as defined in 2939 * {@link android.view.Window}. 2940 * @return Returns true if the requested feature is supported and now 2941 * enabled. 2942 * 2943 * @see android.view.Window#requestFeature 2944 */ 2945 public final boolean requestWindowFeature(int featureId) { 2946 return getWindow().requestFeature(featureId); 2947 } 2948 2949 /** 2950 * Convenience for calling 2951 * {@link android.view.Window#setFeatureDrawableResource}. 2952 */ 2953 public final void setFeatureDrawableResource(int featureId, int resId) { 2954 getWindow().setFeatureDrawableResource(featureId, resId); 2955 } 2956 2957 /** 2958 * Convenience for calling 2959 * {@link android.view.Window#setFeatureDrawableUri}. 2960 */ 2961 public final void setFeatureDrawableUri(int featureId, Uri uri) { 2962 getWindow().setFeatureDrawableUri(featureId, uri); 2963 } 2964 2965 /** 2966 * Convenience for calling 2967 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}. 2968 */ 2969 public final void setFeatureDrawable(int featureId, Drawable drawable) { 2970 getWindow().setFeatureDrawable(featureId, drawable); 2971 } 2972 2973 /** 2974 * Convenience for calling 2975 * {@link android.view.Window#setFeatureDrawableAlpha}. 2976 */ 2977 public final void setFeatureDrawableAlpha(int featureId, int alpha) { 2978 getWindow().setFeatureDrawableAlpha(featureId, alpha); 2979 } 2980 2981 /** 2982 * Convenience for calling 2983 * {@link android.view.Window#getLayoutInflater}. 2984 */ 2985 public LayoutInflater getLayoutInflater() { 2986 return getWindow().getLayoutInflater(); 2987 } 2988 2989 /** 2990 * Returns a {@link MenuInflater} with this context. 2991 */ 2992 public MenuInflater getMenuInflater() { 2993 return new MenuInflater(this); 2994 } 2995 2996 @Override 2997 protected void onApplyThemeResource(Resources.Theme theme, int resid, 2998 boolean first) { 2999 if (mParent == null) { 3000 super.onApplyThemeResource(theme, resid, first); 3001 } else { 3002 try { 3003 theme.setTo(mParent.getTheme()); 3004 } catch (Exception e) { 3005 // Empty 3006 } 3007 theme.applyStyle(resid, false); 3008 } 3009 } 3010 3011 /** 3012 * Launch an activity for which you would like a result when it finished. 3013 * When this activity exits, your 3014 * onActivityResult() method will be called with the given requestCode. 3015 * Using a negative requestCode is the same as calling 3016 * {@link #startActivity} (the activity is not launched as a sub-activity). 3017 * 3018 * <p>Note that this method should only be used with Intent protocols 3019 * that are defined to return a result. In other protocols (such as 3020 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may 3021 * not get the result when you expect. For example, if the activity you 3022 * are launching uses the singleTask launch mode, it will not run in your 3023 * task and thus you will immediately receive a cancel result. 3024 * 3025 * <p>As a special case, if you call startActivityForResult() with a requestCode 3026 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your 3027 * activity, then your window will not be displayed until a result is 3028 * returned back from the started activity. This is to avoid visible 3029 * flickering when redirecting to another activity. 3030 * 3031 * <p>This method throws {@link android.content.ActivityNotFoundException} 3032 * if there was no Activity found to run the given Intent. 3033 * 3034 * @param intent The intent to start. 3035 * @param requestCode If >= 0, this code will be returned in 3036 * onActivityResult() when the activity exits. 3037 * 3038 * @throws android.content.ActivityNotFoundException 3039 * 3040 * @see #startActivity 3041 */ 3042 public void startActivityForResult(Intent intent, int requestCode) { 3043 if (mParent == null) { 3044 Instrumentation.ActivityResult ar = 3045 mInstrumentation.execStartActivity( 3046 this, mMainThread.getApplicationThread(), mToken, this, 3047 intent, requestCode); 3048 if (ar != null) { 3049 mMainThread.sendActivityResult( 3050 mToken, mEmbeddedID, requestCode, ar.getResultCode(), 3051 ar.getResultData()); 3052 } 3053 if (requestCode >= 0) { 3054 // If this start is requesting a result, we can avoid making 3055 // the activity visible until the result is received. Setting 3056 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 3057 // activity hidden during this time, to avoid flickering. 3058 // This can only be done when a result is requested because 3059 // that guarantees we will get information back when the 3060 // activity is finished, no matter what happens to it. 3061 mStartedActivity = true; 3062 } 3063 } else { 3064 mParent.startActivityFromChild(this, intent, requestCode); 3065 } 3066 } 3067 3068 /** 3069 * Like {@link #startActivityForResult(Intent, int)}, but allowing you 3070 * to use a IntentSender to describe the activity to be started. If 3071 * the IntentSender is for an activity, that activity will be started 3072 * as if you had called the regular {@link #startActivityForResult(Intent, int)} 3073 * here; otherwise, its associated action will be executed (such as 3074 * sending a broadcast) as if you had called 3075 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it. 3076 * 3077 * @param intent The IntentSender to launch. 3078 * @param requestCode If >= 0, this code will be returned in 3079 * onActivityResult() when the activity exits. 3080 * @param fillInIntent If non-null, this will be provided as the 3081 * intent parameter to {@link IntentSender#sendIntent}. 3082 * @param flagsMask Intent flags in the original IntentSender that you 3083 * would like to change. 3084 * @param flagsValues Desired values for any bits set in 3085 * <var>flagsMask</var> 3086 * @param extraFlags Always set to 0. 3087 */ 3088 public void startIntentSenderForResult(IntentSender intent, int requestCode, 3089 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 3090 throws IntentSender.SendIntentException { 3091 if (mParent == null) { 3092 startIntentSenderForResultInner(intent, requestCode, fillInIntent, 3093 flagsMask, flagsValues, this); 3094 } else { 3095 mParent.startIntentSenderFromChild(this, intent, requestCode, 3096 fillInIntent, flagsMask, flagsValues, extraFlags); 3097 } 3098 } 3099 3100 private void startIntentSenderForResultInner(IntentSender intent, int requestCode, 3101 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity) 3102 throws IntentSender.SendIntentException { 3103 try { 3104 String resolvedType = null; 3105 if (fillInIntent != null) { 3106 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 3107 } 3108 int result = ActivityManagerNative.getDefault() 3109 .startActivityIntentSender(mMainThread.getApplicationThread(), intent, 3110 fillInIntent, resolvedType, mToken, activity.mEmbeddedID, 3111 requestCode, flagsMask, flagsValues); 3112 if (result == IActivityManager.START_CANCELED) { 3113 throw new IntentSender.SendIntentException(); 3114 } 3115 Instrumentation.checkStartActivityResult(result, null); 3116 } catch (RemoteException e) { 3117 } 3118 if (requestCode >= 0) { 3119 // If this start is requesting a result, we can avoid making 3120 // the activity visible until the result is received. Setting 3121 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 3122 // activity hidden during this time, to avoid flickering. 3123 // This can only be done when a result is requested because 3124 // that guarantees we will get information back when the 3125 // activity is finished, no matter what happens to it. 3126 mStartedActivity = true; 3127 } 3128 } 3129 3130 /** 3131 * Launch a new activity. You will not receive any information about when 3132 * the activity exits. This implementation overrides the base version, 3133 * providing information about 3134 * the activity performing the launch. Because of this additional 3135 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not 3136 * required; if not specified, the new activity will be added to the 3137 * task of the caller. 3138 * 3139 * <p>This method throws {@link android.content.ActivityNotFoundException} 3140 * if there was no Activity found to run the given Intent. 3141 * 3142 * @param intent The intent to start. 3143 * 3144 * @throws android.content.ActivityNotFoundException 3145 * 3146 * @see #startActivityForResult 3147 */ 3148 @Override 3149 public void startActivity(Intent intent) { 3150 startActivityForResult(intent, -1); 3151 } 3152 3153 /** 3154 * Launch a new activity. You will not receive any information about when 3155 * the activity exits. This implementation overrides the base version, 3156 * providing information about 3157 * the activity performing the launch. Because of this additional 3158 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not 3159 * required; if not specified, the new activity will be added to the 3160 * task of the caller. 3161 * 3162 * <p>This method throws {@link android.content.ActivityNotFoundException} 3163 * if there was no Activity found to run the given Intent. 3164 * 3165 * @param intents The intents to start. 3166 * 3167 * @throws android.content.ActivityNotFoundException 3168 * 3169 * @see #startActivityForResult 3170 */ 3171 @Override 3172 public void startActivities(Intent[] intents) { 3173 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(), 3174 mToken, this, intents); 3175 } 3176 3177 /** 3178 * Like {@link #startActivity(Intent)}, but taking a IntentSender 3179 * to start; see 3180 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)} 3181 * for more information. 3182 * 3183 * @param intent The IntentSender to launch. 3184 * @param fillInIntent If non-null, this will be provided as the 3185 * intent parameter to {@link IntentSender#sendIntent}. 3186 * @param flagsMask Intent flags in the original IntentSender that you 3187 * would like to change. 3188 * @param flagsValues Desired values for any bits set in 3189 * <var>flagsMask</var> 3190 * @param extraFlags Always set to 0. 3191 */ 3192 public void startIntentSender(IntentSender intent, 3193 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 3194 throws IntentSender.SendIntentException { 3195 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask, 3196 flagsValues, extraFlags); 3197 } 3198 3199 /** 3200 * A special variation to launch an activity only if a new activity 3201 * instance is needed to handle the given Intent. In other words, this is 3202 * just like {@link #startActivityForResult(Intent, int)} except: if you are 3203 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or 3204 * singleTask or singleTop 3205 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode}, 3206 * and the activity 3207 * that handles <var>intent</var> is the same as your currently running 3208 * activity, then a new instance is not needed. In this case, instead of 3209 * the normal behavior of calling {@link #onNewIntent} this function will 3210 * return and you can handle the Intent yourself. 3211 * 3212 * <p>This function can only be called from a top-level activity; if it is 3213 * called from a child activity, a runtime exception will be thrown. 3214 * 3215 * @param intent The intent to start. 3216 * @param requestCode If >= 0, this code will be returned in 3217 * onActivityResult() when the activity exits, as described in 3218 * {@link #startActivityForResult}. 3219 * 3220 * @return If a new activity was launched then true is returned; otherwise 3221 * false is returned and you must handle the Intent yourself. 3222 * 3223 * @see #startActivity 3224 * @see #startActivityForResult 3225 */ 3226 public boolean startActivityIfNeeded(Intent intent, int requestCode) { 3227 if (mParent == null) { 3228 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER; 3229 try { 3230 result = ActivityManagerNative.getDefault() 3231 .startActivity(mMainThread.getApplicationThread(), 3232 intent, intent.resolveTypeIfNeeded( 3233 getContentResolver()), 3234 null, 0, 3235 mToken, mEmbeddedID, requestCode, true, false); 3236 } catch (RemoteException e) { 3237 // Empty 3238 } 3239 3240 Instrumentation.checkStartActivityResult(result, intent); 3241 3242 if (requestCode >= 0) { 3243 // If this start is requesting a result, we can avoid making 3244 // the activity visible until the result is received. Setting 3245 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 3246 // activity hidden during this time, to avoid flickering. 3247 // This can only be done when a result is requested because 3248 // that guarantees we will get information back when the 3249 // activity is finished, no matter what happens to it. 3250 mStartedActivity = true; 3251 } 3252 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER; 3253 } 3254 3255 throw new UnsupportedOperationException( 3256 "startActivityIfNeeded can only be called from a top-level activity"); 3257 } 3258 3259 /** 3260 * Special version of starting an activity, for use when you are replacing 3261 * other activity components. You can use this to hand the Intent off 3262 * to the next Activity that can handle it. You typically call this in 3263 * {@link #onCreate} with the Intent returned by {@link #getIntent}. 3264 * 3265 * @param intent The intent to dispatch to the next activity. For 3266 * correct behavior, this must be the same as the Intent that started 3267 * your own activity; the only changes you can make are to the extras 3268 * inside of it. 3269 * 3270 * @return Returns a boolean indicating whether there was another Activity 3271 * to start: true if there was a next activity to start, false if there 3272 * wasn't. In general, if true is returned you will then want to call 3273 * finish() on yourself. 3274 */ 3275 public boolean startNextMatchingActivity(Intent intent) { 3276 if (mParent == null) { 3277 try { 3278 return ActivityManagerNative.getDefault() 3279 .startNextMatchingActivity(mToken, intent); 3280 } catch (RemoteException e) { 3281 // Empty 3282 } 3283 return false; 3284 } 3285 3286 throw new UnsupportedOperationException( 3287 "startNextMatchingActivity can only be called from a top-level activity"); 3288 } 3289 3290 /** 3291 * This is called when a child activity of this one calls its 3292 * {@link #startActivity} or {@link #startActivityForResult} method. 3293 * 3294 * <p>This method throws {@link android.content.ActivityNotFoundException} 3295 * if there was no Activity found to run the given Intent. 3296 * 3297 * @param child The activity making the call. 3298 * @param intent The intent to start. 3299 * @param requestCode Reply request code. < 0 if reply is not requested. 3300 * 3301 * @throws android.content.ActivityNotFoundException 3302 * 3303 * @see #startActivity 3304 * @see #startActivityForResult 3305 */ 3306 public void startActivityFromChild(Activity child, Intent intent, 3307 int requestCode) { 3308 Instrumentation.ActivityResult ar = 3309 mInstrumentation.execStartActivity( 3310 this, mMainThread.getApplicationThread(), mToken, child, 3311 intent, requestCode); 3312 if (ar != null) { 3313 mMainThread.sendActivityResult( 3314 mToken, child.mEmbeddedID, requestCode, 3315 ar.getResultCode(), ar.getResultData()); 3316 } 3317 } 3318 3319 /** 3320 * This is called when a Fragment in this activity calls its 3321 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult} 3322 * method. 3323 * 3324 * <p>This method throws {@link android.content.ActivityNotFoundException} 3325 * if there was no Activity found to run the given Intent. 3326 * 3327 * @param fragment The fragment making the call. 3328 * @param intent The intent to start. 3329 * @param requestCode Reply request code. < 0 if reply is not requested. 3330 * 3331 * @throws android.content.ActivityNotFoundException 3332 * 3333 * @see Fragment#startActivity 3334 * @see Fragment#startActivityForResult 3335 */ 3336 public void startActivityFromFragment(Fragment fragment, Intent intent, 3337 int requestCode) { 3338 Instrumentation.ActivityResult ar = 3339 mInstrumentation.execStartActivity( 3340 this, mMainThread.getApplicationThread(), mToken, fragment, 3341 intent, requestCode); 3342 if (ar != null) { 3343 mMainThread.sendActivityResult( 3344 mToken, fragment.mWho, requestCode, 3345 ar.getResultCode(), ar.getResultData()); 3346 } 3347 } 3348 3349 /** 3350 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but 3351 * taking a IntentSender; see 3352 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)} 3353 * for more information. 3354 */ 3355 public void startIntentSenderFromChild(Activity child, IntentSender intent, 3356 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, 3357 int extraFlags) 3358 throws IntentSender.SendIntentException { 3359 startIntentSenderForResultInner(intent, requestCode, fillInIntent, 3360 flagsMask, flagsValues, child); 3361 } 3362 3363 /** 3364 * Call immediately after one of the flavors of {@link #startActivity(Intent)} 3365 * or {@link #finish} to specify an explicit transition animation to 3366 * perform next. 3367 * @param enterAnim A resource ID of the animation resource to use for 3368 * the incoming activity. Use 0 for no animation. 3369 * @param exitAnim A resource ID of the animation resource to use for 3370 * the outgoing activity. Use 0 for no animation. 3371 */ 3372 public void overridePendingTransition(int enterAnim, int exitAnim) { 3373 try { 3374 ActivityManagerNative.getDefault().overridePendingTransition( 3375 mToken, getPackageName(), enterAnim, exitAnim); 3376 } catch (RemoteException e) { 3377 } 3378 } 3379 3380 /** 3381 * Call this to set the result that your activity will return to its 3382 * caller. 3383 * 3384 * @param resultCode The result code to propagate back to the originating 3385 * activity, often RESULT_CANCELED or RESULT_OK 3386 * 3387 * @see #RESULT_CANCELED 3388 * @see #RESULT_OK 3389 * @see #RESULT_FIRST_USER 3390 * @see #setResult(int, Intent) 3391 */ 3392 public final void setResult(int resultCode) { 3393 synchronized (this) { 3394 mResultCode = resultCode; 3395 mResultData = null; 3396 } 3397 } 3398 3399 /** 3400 * Call this to set the result that your activity will return to its 3401 * caller. 3402 * 3403 * @param resultCode The result code to propagate back to the originating 3404 * activity, often RESULT_CANCELED or RESULT_OK 3405 * @param data The data to propagate back to the originating activity. 3406 * 3407 * @see #RESULT_CANCELED 3408 * @see #RESULT_OK 3409 * @see #RESULT_FIRST_USER 3410 * @see #setResult(int) 3411 */ 3412 public final void setResult(int resultCode, Intent data) { 3413 synchronized (this) { 3414 mResultCode = resultCode; 3415 mResultData = data; 3416 } 3417 } 3418 3419 /** 3420 * Return the name of the package that invoked this activity. This is who 3421 * the data in {@link #setResult setResult()} will be sent to. You can 3422 * use this information to validate that the recipient is allowed to 3423 * receive the data. 3424 * 3425 * <p>Note: if the calling activity is not expecting a result (that is it 3426 * did not use the {@link #startActivityForResult} 3427 * form that includes a request code), then the calling package will be 3428 * null. 3429 * 3430 * @return The package of the activity that will receive your 3431 * reply, or null if none. 3432 */ 3433 public String getCallingPackage() { 3434 try { 3435 return ActivityManagerNative.getDefault().getCallingPackage(mToken); 3436 } catch (RemoteException e) { 3437 return null; 3438 } 3439 } 3440 3441 /** 3442 * Return the name of the activity that invoked this activity. This is 3443 * who the data in {@link #setResult setResult()} will be sent to. You 3444 * can use this information to validate that the recipient is allowed to 3445 * receive the data. 3446 * 3447 * <p>Note: if the calling activity is not expecting a result (that is it 3448 * did not use the {@link #startActivityForResult} 3449 * form that includes a request code), then the calling package will be 3450 * null. 3451 * 3452 * @return String The full name of the activity that will receive your 3453 * reply, or null if none. 3454 */ 3455 public ComponentName getCallingActivity() { 3456 try { 3457 return ActivityManagerNative.getDefault().getCallingActivity(mToken); 3458 } catch (RemoteException e) { 3459 return null; 3460 } 3461 } 3462 3463 /** 3464 * Control whether this activity's main window is visible. This is intended 3465 * only for the special case of an activity that is not going to show a 3466 * UI itself, but can't just finish prior to onResume() because it needs 3467 * to wait for a service binding or such. Setting this to false allows 3468 * you to prevent your UI from being shown during that time. 3469 * 3470 * <p>The default value for this is taken from the 3471 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme. 3472 */ 3473 public void setVisible(boolean visible) { 3474 if (mVisibleFromClient != visible) { 3475 mVisibleFromClient = visible; 3476 if (mVisibleFromServer) { 3477 if (visible) makeVisible(); 3478 else mDecor.setVisibility(View.INVISIBLE); 3479 } 3480 } 3481 } 3482 3483 void makeVisible() { 3484 if (!mWindowAdded) { 3485 ViewManager wm = getWindowManager(); 3486 wm.addView(mDecor, getWindow().getAttributes()); 3487 mWindowAdded = true; 3488 } 3489 mDecor.setVisibility(View.VISIBLE); 3490 } 3491 3492 /** 3493 * Check to see whether this activity is in the process of finishing, 3494 * either because you called {@link #finish} on it or someone else 3495 * has requested that it finished. This is often used in 3496 * {@link #onPause} to determine whether the activity is simply pausing or 3497 * completely finishing. 3498 * 3499 * @return If the activity is finishing, returns true; else returns false. 3500 * 3501 * @see #finish 3502 */ 3503 public boolean isFinishing() { 3504 return mFinished; 3505 } 3506 3507 /** 3508 * Check to see whether this activity is in the process of being destroyed in order to be 3509 * recreated with a new configuration. This is often used in 3510 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed 3511 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}. 3512 * 3513 * @return If the activity is being torn down in order to be recreated with a new configuration, 3514 * returns true; else returns false. 3515 */ 3516 public boolean isChangingConfigurations() { 3517 return mChangingConfigurations; 3518 } 3519 3520 /** 3521 * Cause this Activity to be recreated with a new instance. This results 3522 * in essentially the same flow as when the Activity is created due to 3523 * a configuration change -- the current instance will go through its 3524 * lifecycle to {@link #onDestroy} and a new instance then created after it. 3525 */ 3526 public void recreate() { 3527 if (mParent != null) { 3528 throw new IllegalStateException("Can only be called on top-level activity"); 3529 } 3530 if (Looper.myLooper() != mMainThread.getLooper()) { 3531 throw new IllegalStateException("Must be called from main thread"); 3532 } 3533 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false); 3534 } 3535 3536 /** 3537 * Call this when your activity is done and should be closed. The 3538 * ActivityResult is propagated back to whoever launched you via 3539 * onActivityResult(). 3540 */ 3541 public void finish() { 3542 if (mParent == null) { 3543 int resultCode; 3544 Intent resultData; 3545 synchronized (this) { 3546 resultCode = mResultCode; 3547 resultData = mResultData; 3548 } 3549 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken); 3550 try { 3551 if (ActivityManagerNative.getDefault() 3552 .finishActivity(mToken, resultCode, resultData)) { 3553 mFinished = true; 3554 } 3555 } catch (RemoteException e) { 3556 // Empty 3557 } 3558 } else { 3559 mParent.finishFromChild(this); 3560 } 3561 } 3562 3563 /** 3564 * This is called when a child activity of this one calls its 3565 * {@link #finish} method. The default implementation simply calls 3566 * finish() on this activity (the parent), finishing the entire group. 3567 * 3568 * @param child The activity making the call. 3569 * 3570 * @see #finish 3571 */ 3572 public void finishFromChild(Activity child) { 3573 finish(); 3574 } 3575 3576 /** 3577 * Force finish another activity that you had previously started with 3578 * {@link #startActivityForResult}. 3579 * 3580 * @param requestCode The request code of the activity that you had 3581 * given to startActivityForResult(). If there are multiple 3582 * activities started with this request code, they 3583 * will all be finished. 3584 */ 3585 public void finishActivity(int requestCode) { 3586 if (mParent == null) { 3587 try { 3588 ActivityManagerNative.getDefault() 3589 .finishSubActivity(mToken, mEmbeddedID, requestCode); 3590 } catch (RemoteException e) { 3591 // Empty 3592 } 3593 } else { 3594 mParent.finishActivityFromChild(this, requestCode); 3595 } 3596 } 3597 3598 /** 3599 * This is called when a child activity of this one calls its 3600 * finishActivity(). 3601 * 3602 * @param child The activity making the call. 3603 * @param requestCode Request code that had been used to start the 3604 * activity. 3605 */ 3606 public void finishActivityFromChild(Activity child, int requestCode) { 3607 try { 3608 ActivityManagerNative.getDefault() 3609 .finishSubActivity(mToken, child.mEmbeddedID, requestCode); 3610 } catch (RemoteException e) { 3611 // Empty 3612 } 3613 } 3614 3615 /** 3616 * Called when an activity you launched exits, giving you the requestCode 3617 * you started it with, the resultCode it returned, and any additional 3618 * data from it. The <var>resultCode</var> will be 3619 * {@link #RESULT_CANCELED} if the activity explicitly returned that, 3620 * didn't return any result, or crashed during its operation. 3621 * 3622 * <p>You will receive this call immediately before onResume() when your 3623 * activity is re-starting. 3624 * 3625 * @param requestCode The integer request code originally supplied to 3626 * startActivityForResult(), allowing you to identify who this 3627 * result came from. 3628 * @param resultCode The integer result code returned by the child activity 3629 * through its setResult(). 3630 * @param data An Intent, which can return result data to the caller 3631 * (various data can be attached to Intent "extras"). 3632 * 3633 * @see #startActivityForResult 3634 * @see #createPendingResult 3635 * @see #setResult(int) 3636 */ 3637 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 3638 } 3639 3640 /** 3641 * Create a new PendingIntent object which you can hand to others 3642 * for them to use to send result data back to your 3643 * {@link #onActivityResult} callback. The created object will be either 3644 * one-shot (becoming invalid after a result is sent back) or multiple 3645 * (allowing any number of results to be sent through it). 3646 * 3647 * @param requestCode Private request code for the sender that will be 3648 * associated with the result data when it is returned. The sender can not 3649 * modify this value, allowing you to identify incoming results. 3650 * @param data Default data to supply in the result, which may be modified 3651 * by the sender. 3652 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT}, 3653 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE}, 3654 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT}, 3655 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT}, 3656 * or any of the flags as supported by 3657 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts 3658 * of the intent that can be supplied when the actual send happens. 3659 * 3660 * @return Returns an existing or new PendingIntent matching the given 3661 * parameters. May return null only if 3662 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been 3663 * supplied. 3664 * 3665 * @see PendingIntent 3666 */ 3667 public PendingIntent createPendingResult(int requestCode, Intent data, 3668 int flags) { 3669 String packageName = getPackageName(); 3670 try { 3671 IIntentSender target = 3672 ActivityManagerNative.getDefault().getIntentSender( 3673 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, 3674 mParent == null ? mToken : mParent.mToken, 3675 mEmbeddedID, requestCode, new Intent[] { data }, null, flags); 3676 return target != null ? new PendingIntent(target) : null; 3677 } catch (RemoteException e) { 3678 // Empty 3679 } 3680 return null; 3681 } 3682 3683 /** 3684 * Change the desired orientation of this activity. If the activity 3685 * is currently in the foreground or otherwise impacting the screen 3686 * orientation, the screen will immediately be changed (possibly causing 3687 * the activity to be restarted). Otherwise, this will be used the next 3688 * time the activity is visible. 3689 * 3690 * @param requestedOrientation An orientation constant as used in 3691 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}. 3692 */ 3693 public void setRequestedOrientation(int requestedOrientation) { 3694 if (mParent == null) { 3695 try { 3696 ActivityManagerNative.getDefault().setRequestedOrientation( 3697 mToken, requestedOrientation); 3698 } catch (RemoteException e) { 3699 // Empty 3700 } 3701 } else { 3702 mParent.setRequestedOrientation(requestedOrientation); 3703 } 3704 } 3705 3706 /** 3707 * Return the current requested orientation of the activity. This will 3708 * either be the orientation requested in its component's manifest, or 3709 * the last requested orientation given to 3710 * {@link #setRequestedOrientation(int)}. 3711 * 3712 * @return Returns an orientation constant as used in 3713 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}. 3714 */ 3715 public int getRequestedOrientation() { 3716 if (mParent == null) { 3717 try { 3718 return ActivityManagerNative.getDefault() 3719 .getRequestedOrientation(mToken); 3720 } catch (RemoteException e) { 3721 // Empty 3722 } 3723 } else { 3724 return mParent.getRequestedOrientation(); 3725 } 3726 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 3727 } 3728 3729 /** 3730 * Return the identifier of the task this activity is in. This identifier 3731 * will remain the same for the lifetime of the activity. 3732 * 3733 * @return Task identifier, an opaque integer. 3734 */ 3735 public int getTaskId() { 3736 try { 3737 return ActivityManagerNative.getDefault() 3738 .getTaskForActivity(mToken, false); 3739 } catch (RemoteException e) { 3740 return -1; 3741 } 3742 } 3743 3744 /** 3745 * Return whether this activity is the root of a task. The root is the 3746 * first activity in a task. 3747 * 3748 * @return True if this is the root activity, else false. 3749 */ 3750 public boolean isTaskRoot() { 3751 try { 3752 return ActivityManagerNative.getDefault() 3753 .getTaskForActivity(mToken, true) >= 0; 3754 } catch (RemoteException e) { 3755 return false; 3756 } 3757 } 3758 3759 /** 3760 * Move the task containing this activity to the back of the activity 3761 * stack. The activity's order within the task is unchanged. 3762 * 3763 * @param nonRoot If false then this only works if the activity is the root 3764 * of a task; if true it will work for any activity in 3765 * a task. 3766 * 3767 * @return If the task was moved (or it was already at the 3768 * back) true is returned, else false. 3769 */ 3770 public boolean moveTaskToBack(boolean nonRoot) { 3771 try { 3772 return ActivityManagerNative.getDefault().moveActivityTaskToBack( 3773 mToken, nonRoot); 3774 } catch (RemoteException e) { 3775 // Empty 3776 } 3777 return false; 3778 } 3779 3780 /** 3781 * Returns class name for this activity with the package prefix removed. 3782 * This is the default name used to read and write settings. 3783 * 3784 * @return The local class name. 3785 */ 3786 public String getLocalClassName() { 3787 final String pkg = getPackageName(); 3788 final String cls = mComponent.getClassName(); 3789 int packageLen = pkg.length(); 3790 if (!cls.startsWith(pkg) || cls.length() <= packageLen 3791 || cls.charAt(packageLen) != '.') { 3792 return cls; 3793 } 3794 return cls.substring(packageLen+1); 3795 } 3796 3797 /** 3798 * Returns complete component name of this activity. 3799 * 3800 * @return Returns the complete component name for this activity 3801 */ 3802 public ComponentName getComponentName() 3803 { 3804 return mComponent; 3805 } 3806 3807 /** 3808 * Retrieve a {@link SharedPreferences} object for accessing preferences 3809 * that are private to this activity. This simply calls the underlying 3810 * {@link #getSharedPreferences(String, int)} method by passing in this activity's 3811 * class name as the preferences name. 3812 * 3813 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default 3814 * operation, {@link #MODE_WORLD_READABLE} and 3815 * {@link #MODE_WORLD_WRITEABLE} to control permissions. 3816 * 3817 * @return Returns the single SharedPreferences instance that can be used 3818 * to retrieve and modify the preference values. 3819 */ 3820 public SharedPreferences getPreferences(int mode) { 3821 return getSharedPreferences(getLocalClassName(), mode); 3822 } 3823 3824 private void ensureSearchManager() { 3825 if (mSearchManager != null) { 3826 return; 3827 } 3828 3829 mSearchManager = new SearchManager(this, null); 3830 } 3831 3832 @Override 3833 public Object getSystemService(String name) { 3834 if (getBaseContext() == null) { 3835 throw new IllegalStateException( 3836 "System services not available to Activities before onCreate()"); 3837 } 3838 3839 if (WINDOW_SERVICE.equals(name)) { 3840 return mWindowManager; 3841 } else if (SEARCH_SERVICE.equals(name)) { 3842 ensureSearchManager(); 3843 return mSearchManager; 3844 } 3845 return super.getSystemService(name); 3846 } 3847 3848 /** 3849 * Change the title associated with this activity. If this is a 3850 * top-level activity, the title for its window will change. If it 3851 * is an embedded activity, the parent can do whatever it wants 3852 * with it. 3853 */ 3854 public void setTitle(CharSequence title) { 3855 mTitle = title; 3856 onTitleChanged(title, mTitleColor); 3857 3858 if (mParent != null) { 3859 mParent.onChildTitleChanged(this, title); 3860 } 3861 } 3862 3863 /** 3864 * Change the title associated with this activity. If this is a 3865 * top-level activity, the title for its window will change. If it 3866 * is an embedded activity, the parent can do whatever it wants 3867 * with it. 3868 */ 3869 public void setTitle(int titleId) { 3870 setTitle(getText(titleId)); 3871 } 3872 3873 public void setTitleColor(int textColor) { 3874 mTitleColor = textColor; 3875 onTitleChanged(mTitle, textColor); 3876 } 3877 3878 public final CharSequence getTitle() { 3879 return mTitle; 3880 } 3881 3882 public final int getTitleColor() { 3883 return mTitleColor; 3884 } 3885 3886 protected void onTitleChanged(CharSequence title, int color) { 3887 if (mTitleReady) { 3888 final Window win = getWindow(); 3889 if (win != null) { 3890 win.setTitle(title); 3891 if (color != 0) { 3892 win.setTitleColor(color); 3893 } 3894 } 3895 } 3896 } 3897 3898 protected void onChildTitleChanged(Activity childActivity, CharSequence title) { 3899 } 3900 3901 /** 3902 * Sets the visibility of the progress bar in the title. 3903 * <p> 3904 * In order for the progress bar to be shown, the feature must be requested 3905 * via {@link #requestWindowFeature(int)}. 3906 * 3907 * @param visible Whether to show the progress bars in the title. 3908 */ 3909 public final void setProgressBarVisibility(boolean visible) { 3910 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON : 3911 Window.PROGRESS_VISIBILITY_OFF); 3912 } 3913 3914 /** 3915 * Sets the visibility of the indeterminate progress bar in the title. 3916 * <p> 3917 * In order for the progress bar to be shown, the feature must be requested 3918 * via {@link #requestWindowFeature(int)}. 3919 * 3920 * @param visible Whether to show the progress bars in the title. 3921 */ 3922 public final void setProgressBarIndeterminateVisibility(boolean visible) { 3923 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 3924 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF); 3925 } 3926 3927 /** 3928 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular 3929 * is always indeterminate). 3930 * <p> 3931 * In order for the progress bar to be shown, the feature must be requested 3932 * via {@link #requestWindowFeature(int)}. 3933 * 3934 * @param indeterminate Whether the horizontal progress bar should be indeterminate. 3935 */ 3936 public final void setProgressBarIndeterminate(boolean indeterminate) { 3937 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 3938 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF); 3939 } 3940 3941 /** 3942 * Sets the progress for the progress bars in the title. 3943 * <p> 3944 * In order for the progress bar to be shown, the feature must be requested 3945 * via {@link #requestWindowFeature(int)}. 3946 * 3947 * @param progress The progress for the progress bar. Valid ranges are from 3948 * 0 to 10000 (both inclusive). If 10000 is given, the progress 3949 * bar will be completely filled and will fade out. 3950 */ 3951 public final void setProgress(int progress) { 3952 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START); 3953 } 3954 3955 /** 3956 * Sets the secondary progress for the progress bar in the title. This 3957 * progress is drawn between the primary progress (set via 3958 * {@link #setProgress(int)} and the background. It can be ideal for media 3959 * scenarios such as showing the buffering progress while the default 3960 * progress shows the play progress. 3961 * <p> 3962 * In order for the progress bar to be shown, the feature must be requested 3963 * via {@link #requestWindowFeature(int)}. 3964 * 3965 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from 3966 * 0 to 10000 (both inclusive). 3967 */ 3968 public final void setSecondaryProgress(int secondaryProgress) { 3969 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 3970 secondaryProgress + Window.PROGRESS_SECONDARY_START); 3971 } 3972 3973 /** 3974 * Suggests an audio stream whose volume should be changed by the hardware 3975 * volume controls. 3976 * <p> 3977 * The suggested audio stream will be tied to the window of this Activity. 3978 * If the Activity is switched, the stream set here is no longer the 3979 * suggested stream. The client does not need to save and restore the old 3980 * suggested stream value in onPause and onResume. 3981 * 3982 * @param streamType The type of the audio stream whose volume should be 3983 * changed by the hardware volume controls. It is not guaranteed that 3984 * the hardware volume controls will always change this stream's 3985 * volume (for example, if a call is in progress, its stream's volume 3986 * may be changed instead). To reset back to the default, use 3987 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}. 3988 */ 3989 public final void setVolumeControlStream(int streamType) { 3990 getWindow().setVolumeControlStream(streamType); 3991 } 3992 3993 /** 3994 * Gets the suggested audio stream whose volume should be changed by the 3995 * harwdare volume controls. 3996 * 3997 * @return The suggested audio stream type whose volume should be changed by 3998 * the hardware volume controls. 3999 * @see #setVolumeControlStream(int) 4000 */ 4001 public final int getVolumeControlStream() { 4002 return getWindow().getVolumeControlStream(); 4003 } 4004 4005 /** 4006 * Runs the specified action on the UI thread. If the current thread is the UI 4007 * thread, then the action is executed immediately. If the current thread is 4008 * not the UI thread, the action is posted to the event queue of the UI thread. 4009 * 4010 * @param action the action to run on the UI thread 4011 */ 4012 public final void runOnUiThread(Runnable action) { 4013 if (Thread.currentThread() != mUiThread) { 4014 mHandler.post(action); 4015 } else { 4016 action.run(); 4017 } 4018 } 4019 4020 /** 4021 * Standard implementation of 4022 * {@link android.view.LayoutInflater.Factory#onCreateView} used when 4023 * inflating with the LayoutInflater returned by {@link #getSystemService}. 4024 * This implementation does nothing and is for 4025 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps 4026 * should use {@link #onCreateView(View, String, Context, AttributeSet)}. 4027 * 4028 * @see android.view.LayoutInflater#createView 4029 * @see android.view.Window#getLayoutInflater 4030 */ 4031 public View onCreateView(String name, Context context, AttributeSet attrs) { 4032 return null; 4033 } 4034 4035 /** 4036 * Standard implementation of 4037 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)} 4038 * used when inflating with the LayoutInflater returned by {@link #getSystemService}. 4039 * This implementation handles <fragment> tags to embed fragments inside 4040 * of the activity. 4041 * 4042 * @see android.view.LayoutInflater#createView 4043 * @see android.view.Window#getLayoutInflater 4044 */ 4045 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { 4046 if (!"fragment".equals(name)) { 4047 return onCreateView(name, context, attrs); 4048 } 4049 4050 String fname = attrs.getAttributeValue(null, "class"); 4051 TypedArray a = 4052 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment); 4053 if (fname == null) { 4054 fname = a.getString(com.android.internal.R.styleable.Fragment_name); 4055 } 4056 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID); 4057 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag); 4058 a.recycle(); 4059 4060 int containerId = parent != null ? parent.getId() : 0; 4061 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) { 4062 throw new IllegalArgumentException(attrs.getPositionDescription() 4063 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname); 4064 } 4065 4066 // If we restored from a previous state, we may already have 4067 // instantiated this fragment from the state and should use 4068 // that instance instead of making a new one. 4069 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null; 4070 if (fragment == null && tag != null) { 4071 fragment = mFragments.findFragmentByTag(tag); 4072 } 4073 if (fragment == null && containerId != View.NO_ID) { 4074 fragment = mFragments.findFragmentById(containerId); 4075 } 4076 4077 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x" 4078 + Integer.toHexString(id) + " fname=" + fname 4079 + " existing=" + fragment); 4080 if (fragment == null) { 4081 fragment = Fragment.instantiate(this, fname); 4082 fragment.mFromLayout = true; 4083 fragment.mFragmentId = id != 0 ? id : containerId; 4084 fragment.mContainerId = containerId; 4085 fragment.mTag = tag; 4086 fragment.mInLayout = true; 4087 fragment.mImmediateActivity = this; 4088 fragment.mFragmentManager = mFragments; 4089 fragment.onInflate(attrs, fragment.mSavedFragmentState); 4090 mFragments.addFragment(fragment, true); 4091 4092 } else if (fragment.mInLayout) { 4093 // A fragment already exists and it is not one we restored from 4094 // previous state. 4095 throw new IllegalArgumentException(attrs.getPositionDescription() 4096 + ": Duplicate id 0x" + Integer.toHexString(id) 4097 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId) 4098 + " with another fragment for " + fname); 4099 } else { 4100 // This fragment was retained from a previous instance; get it 4101 // going now. 4102 fragment.mInLayout = true; 4103 fragment.mImmediateActivity = this; 4104 // If this fragment is newly instantiated (either right now, or 4105 // from last saved state), then give it the attributes to 4106 // initialize itself. 4107 if (!fragment.mRetaining) { 4108 fragment.onInflate(attrs, fragment.mSavedFragmentState); 4109 } 4110 mFragments.moveToState(fragment); 4111 } 4112 4113 if (fragment.mView == null) { 4114 throw new IllegalStateException("Fragment " + fname 4115 + " did not create a view."); 4116 } 4117 if (id != 0) { 4118 fragment.mView.setId(id); 4119 } 4120 if (fragment.mView.getTag() == null) { 4121 fragment.mView.setTag(tag); 4122 } 4123 return fragment.mView; 4124 } 4125 4126 /** 4127 * Print the Activity's state into the given stream. This gets invoked if 4128 * you run "adb shell dumpsys activity <activity_component_name>". 4129 * 4130 * @param prefix Desired prefix to prepend at each line of output. 4131 * @param fd The raw file descriptor that the dump is being sent to. 4132 * @param writer The PrintWriter to which you should dump your state. This will be 4133 * closed for you after you return. 4134 * @param args additional arguments to the dump request. 4135 */ 4136 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 4137 writer.print(prefix); writer.print("Local Activity "); 4138 writer.print(Integer.toHexString(System.identityHashCode(this))); 4139 writer.println(" State:"); 4140 String innerPrefix = prefix + " "; 4141 writer.print(innerPrefix); writer.print("mResumed="); 4142 writer.print(mResumed); writer.print(" mStopped="); 4143 writer.print(mStopped); writer.print(" mFinished="); 4144 writer.println(mFinished); 4145 writer.print(innerPrefix); writer.print("mLoadersStarted="); 4146 writer.println(mLoadersStarted); 4147 writer.print(innerPrefix); writer.print("mChangingConfigurations="); 4148 writer.println(mChangingConfigurations); 4149 writer.print(innerPrefix); writer.print("mCurrentConfig="); 4150 writer.println(mCurrentConfig); 4151 if (mLoaderManager != null) { 4152 writer.print(prefix); writer.print("Loader Manager "); 4153 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager))); 4154 writer.println(":"); 4155 mLoaderManager.dump(prefix + " ", fd, writer, args); 4156 } 4157 mFragments.dump(prefix, fd, writer, args); 4158 } 4159 4160 /** 4161 * Bit indicating that this activity is "immersive" and should not be 4162 * interrupted by notifications if possible. 4163 * 4164 * This value is initially set by the manifest property 4165 * <code>android:immersive</code> but may be changed at runtime by 4166 * {@link #setImmersive}. 4167 * 4168 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE 4169 * @hide 4170 */ 4171 public boolean isImmersive() { 4172 try { 4173 return ActivityManagerNative.getDefault().isImmersive(mToken); 4174 } catch (RemoteException e) { 4175 return false; 4176 } 4177 } 4178 4179 /** 4180 * Adjust the current immersive mode setting. 4181 * 4182 * Note that changing this value will have no effect on the activity's 4183 * {@link android.content.pm.ActivityInfo} structure; that is, if 4184 * <code>android:immersive</code> is set to <code>true</code> 4185 * in the application's manifest entry for this activity, the {@link 4186 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will 4187 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE 4188 * FLAG_IMMERSIVE} bit set. 4189 * 4190 * @see #isImmersive 4191 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE 4192 * @hide 4193 */ 4194 public void setImmersive(boolean i) { 4195 try { 4196 ActivityManagerNative.getDefault().setImmersive(mToken, i); 4197 } catch (RemoteException e) { 4198 // pass 4199 } 4200 } 4201 4202 /** 4203 * Start an action mode. 4204 * 4205 * @param callback Callback that will manage lifecycle events for this context mode 4206 * @return The ContextMode that was started, or null if it was canceled 4207 * 4208 * @see ActionMode 4209 */ 4210 public ActionMode startActionMode(ActionMode.Callback callback) { 4211 return mWindow.getDecorView().startActionMode(callback); 4212 } 4213 4214 /** 4215 * Give the Activity a chance to control the UI for an action mode requested 4216 * by the system. 4217 * 4218 * <p>Note: If you are looking for a notification callback that an action mode 4219 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p> 4220 * 4221 * @param callback The callback that should control the new action mode 4222 * @return The new action mode, or <code>null</code> if the activity does not want to 4223 * provide special handling for this action mode. (It will be handled by the system.) 4224 */ 4225 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) { 4226 initActionBar(); 4227 if (mActionBar != null) { 4228 return mActionBar.startActionMode(callback); 4229 } 4230 return null; 4231 } 4232 4233 /** 4234 * Notifies the Activity that an action mode has been started. 4235 * Activity subclasses overriding this method should call the superclass implementation. 4236 * 4237 * @param mode The new action mode. 4238 */ 4239 public void onActionModeStarted(ActionMode mode) { 4240 } 4241 4242 /** 4243 * Notifies the activity that an action mode has finished. 4244 * Activity subclasses overriding this method should call the superclass implementation. 4245 * 4246 * @param mode The action mode that just finished. 4247 */ 4248 public void onActionModeFinished(ActionMode mode) { 4249 } 4250 4251 // ------------------ Internal API ------------------ 4252 4253 final void setParent(Activity parent) { 4254 mParent = parent; 4255 } 4256 4257 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, 4258 Application application, Intent intent, ActivityInfo info, CharSequence title, 4259 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances, 4260 Configuration config) { 4261 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id, 4262 lastNonConfigurationInstances, config); 4263 } 4264 4265 final void attach(Context context, ActivityThread aThread, 4266 Instrumentation instr, IBinder token, int ident, 4267 Application application, Intent intent, ActivityInfo info, 4268 CharSequence title, Activity parent, String id, 4269 NonConfigurationInstances lastNonConfigurationInstances, 4270 Configuration config) { 4271 attachBaseContext(context); 4272 4273 mFragments.attachActivity(this); 4274 4275 mWindow = PolicyManager.makeNewWindow(this); 4276 mWindow.setCallback(this); 4277 mWindow.getLayoutInflater().setPrivateFactory(this); 4278 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) { 4279 mWindow.setSoftInputMode(info.softInputMode); 4280 } 4281 mUiThread = Thread.currentThread(); 4282 4283 mMainThread = aThread; 4284 mInstrumentation = instr; 4285 mToken = token; 4286 mIdent = ident; 4287 mApplication = application; 4288 mIntent = intent; 4289 mComponent = intent.getComponent(); 4290 mActivityInfo = info; 4291 mTitle = title; 4292 mParent = parent; 4293 mEmbeddedID = id; 4294 mLastNonConfigurationInstances = lastNonConfigurationInstances; 4295 4296 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(), 4297 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0); 4298 if (mParent != null) { 4299 mWindow.setContainer(mParent.getWindow()); 4300 } 4301 mWindowManager = mWindow.getWindowManager(); 4302 mCurrentConfig = config; 4303 } 4304 4305 final IBinder getActivityToken() { 4306 return mParent != null ? mParent.getActivityToken() : mToken; 4307 } 4308 4309 final void performCreate(Bundle icicle) { 4310 onCreate(icicle); 4311 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean( 4312 com.android.internal.R.styleable.Window_windowNoDisplay, false); 4313 mFragments.dispatchActivityCreated(); 4314 } 4315 4316 final void performStart() { 4317 mFragments.noteStateNotSaved(); 4318 mCalled = false; 4319 mFragments.execPendingActions(); 4320 mInstrumentation.callActivityOnStart(this); 4321 if (!mCalled) { 4322 throw new SuperNotCalledException( 4323 "Activity " + mComponent.toShortString() + 4324 " did not call through to super.onStart()"); 4325 } 4326 mFragments.dispatchStart(); 4327 if (mAllLoaderManagers != null) { 4328 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) { 4329 mAllLoaderManagers.valueAt(i).finishRetain(); 4330 } 4331 } 4332 } 4333 4334 final void performRestart() { 4335 mFragments.noteStateNotSaved(); 4336 4337 synchronized (mManagedCursors) { 4338 final int N = mManagedCursors.size(); 4339 for (int i=0; i<N; i++) { 4340 ManagedCursor mc = mManagedCursors.get(i); 4341 if (mc.mReleased || mc.mUpdated) { 4342 if (!mc.mCursor.requery()) { 4343 throw new IllegalStateException( 4344 "trying to requery an already closed cursor"); 4345 } 4346 mc.mReleased = false; 4347 mc.mUpdated = false; 4348 } 4349 } 4350 } 4351 4352 if (mStopped) { 4353 mStopped = false; 4354 mCalled = false; 4355 mInstrumentation.callActivityOnRestart(this); 4356 if (!mCalled) { 4357 throw new SuperNotCalledException( 4358 "Activity " + mComponent.toShortString() + 4359 " did not call through to super.onRestart()"); 4360 } 4361 performStart(); 4362 } 4363 } 4364 4365 final void performResume() { 4366 performRestart(); 4367 4368 mFragments.execPendingActions(); 4369 4370 mLastNonConfigurationInstances = null; 4371 4372 mCalled = false; 4373 // mResumed is set by the instrumentation 4374 mInstrumentation.callActivityOnResume(this); 4375 if (!mCalled) { 4376 throw new SuperNotCalledException( 4377 "Activity " + mComponent.toShortString() + 4378 " did not call through to super.onResume()"); 4379 } 4380 4381 // Now really resume, and install the current status bar and menu. 4382 mCalled = false; 4383 4384 mFragments.dispatchResume(); 4385 mFragments.execPendingActions(); 4386 4387 onPostResume(); 4388 if (!mCalled) { 4389 throw new SuperNotCalledException( 4390 "Activity " + mComponent.toShortString() + 4391 " did not call through to super.onPostResume()"); 4392 } 4393 } 4394 4395 final void performPause() { 4396 mFragments.dispatchPause(); 4397 mCalled = false; 4398 onPause(); 4399 mResumed = false; 4400 if (!mCalled && getApplicationInfo().targetSdkVersion 4401 >= android.os.Build.VERSION_CODES.GINGERBREAD) { 4402 throw new SuperNotCalledException( 4403 "Activity " + mComponent.toShortString() + 4404 " did not call through to super.onPause()"); 4405 } 4406 mResumed = false; 4407 } 4408 4409 final void performUserLeaving() { 4410 onUserInteraction(); 4411 onUserLeaveHint(); 4412 } 4413 4414 final void performStop() { 4415 if (mLoadersStarted) { 4416 mLoadersStarted = false; 4417 if (mLoaderManager != null) { 4418 if (!mChangingConfigurations) { 4419 mLoaderManager.doStop(); 4420 } else { 4421 mLoaderManager.doRetain(); 4422 } 4423 } 4424 } 4425 4426 if (!mStopped) { 4427 if (mWindow != null) { 4428 mWindow.closeAllPanels(); 4429 } 4430 4431 mFragments.dispatchStop(); 4432 4433 mCalled = false; 4434 mInstrumentation.callActivityOnStop(this); 4435 if (!mCalled) { 4436 throw new SuperNotCalledException( 4437 "Activity " + mComponent.toShortString() + 4438 " did not call through to super.onStop()"); 4439 } 4440 4441 synchronized (mManagedCursors) { 4442 final int N = mManagedCursors.size(); 4443 for (int i=0; i<N; i++) { 4444 ManagedCursor mc = mManagedCursors.get(i); 4445 if (!mc.mReleased) { 4446 mc.mCursor.deactivate(); 4447 mc.mReleased = true; 4448 } 4449 } 4450 } 4451 4452 mStopped = true; 4453 } 4454 mResumed = false; 4455 4456 // Check for Activity leaks, if enabled. 4457 StrictMode.conditionallyCheckInstanceCounts(); 4458 } 4459 4460 final void performDestroy() { 4461 mWindow.destroy(); 4462 mFragments.dispatchDestroy(); 4463 onDestroy(); 4464 if (mLoaderManager != null) { 4465 mLoaderManager.doDestroy(); 4466 } 4467 } 4468 4469 /** 4470 * @hide 4471 */ 4472 public final boolean isResumed() { 4473 return mResumed; 4474 } 4475 4476 void dispatchActivityResult(String who, int requestCode, 4477 int resultCode, Intent data) { 4478 if (Config.LOGV) Log.v( 4479 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode 4480 + ", resCode=" + resultCode + ", data=" + data); 4481 mFragments.noteStateNotSaved(); 4482 if (who == null) { 4483 onActivityResult(requestCode, resultCode, data); 4484 } else { 4485 Fragment frag = mFragments.findFragmentByWho(who); 4486 if (frag != null) { 4487 frag.onActivityResult(requestCode, resultCode, data); 4488 } 4489 } 4490 } 4491} 4492