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