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