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