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