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