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