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