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