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