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