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