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