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