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