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