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