• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app;
18 
19 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
20 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
21 import static android.app.WindowConfiguration.inMultiWindowMode;
22 import static android.os.Process.myUid;
23 
24 import static java.lang.Character.MIN_VALUE;
25 
26 import android.annotation.CallSuper;
27 import android.annotation.DrawableRes;
28 import android.annotation.IdRes;
29 import android.annotation.IntDef;
30 import android.annotation.LayoutRes;
31 import android.annotation.MainThread;
32 import android.annotation.NonNull;
33 import android.annotation.Nullable;
34 import android.annotation.RequiresPermission;
35 import android.annotation.StyleRes;
36 import android.annotation.SystemApi;
37 import android.annotation.TestApi;
38 import android.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      * You cannot request a permission if your activity sets {@link
5187      * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5188      * <code>true</code> because in this case the activity would not receive
5189      * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
5190      * </p>
5191      * <p>
5192      * The <a href="https://github.com/android/permissions-samples">
5193      * RuntimePermissions</a> sample apps demonstrate how to use this method to
5194      * request permissions at run time.
5195      * </p>
5196      *
5197      * @param permissions The requested permissions. Must me non-null and not empty.
5198      * @param requestCode Application specific request code to match with a result
5199      *    reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
5200      *    Should be >= 0.
5201      *
5202      * @throws IllegalArgumentException if requestCode is negative.
5203      *
5204      * @see #onRequestPermissionsResult(int, String[], int[])
5205      * @see #checkSelfPermission(String)
5206      * @see #shouldShowRequestPermissionRationale(String)
5207      */
5208     public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
5209         if (requestCode < 0) {
5210             throw new IllegalArgumentException("requestCode should be >= 0");
5211         }
5212         if (mHasCurrentPermissionsRequest) {
5213             Log.w(TAG, "Can request only one set of permissions at a time");
5214             // Dispatch the callback with empty arrays which means a cancellation.
5215             onRequestPermissionsResult(requestCode, new String[0], new int[0]);
5216             return;
5217         }
5218         Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
5219         startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
5220         mHasCurrentPermissionsRequest = true;
5221     }
5222 
5223     /**
5224      * Callback for the result from requesting permissions. This method
5225      * is invoked for every call on {@link #requestPermissions(String[], int)}.
5226      * <p>
5227      * <strong>Note:</strong> It is possible that the permissions request interaction
5228      * with the user is interrupted. In this case you will receive empty permissions
5229      * and results arrays which should be treated as a cancellation.
5230      * </p>
5231      *
5232      * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
5233      * @param permissions The requested permissions. Never null.
5234      * @param grantResults The grant results for the corresponding permissions
5235      *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
5236      *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
5237      *
5238      * @see #requestPermissions(String[], int)
5239      */
5240     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
5241             @NonNull int[] grantResults) {
5242         /* callback - no nothing */
5243     }
5244 
5245     /**
5246      * Gets whether you should show UI with rationale before requesting a permission.
5247      *
5248      * @param permission A permission your app wants to request.
5249      * @return Whether you should show permission rationale UI.
5250      *
5251      * @see #checkSelfPermission(String)
5252      * @see #requestPermissions(String[], int)
5253      * @see #onRequestPermissionsResult(int, String[], int[])
5254      */
5255     public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
5256         return getPackageManager().shouldShowRequestPermissionRationale(permission);
5257     }
5258 
5259     /**
5260      * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
5261      * with no options.
5262      *
5263      * @param intent The intent to start.
5264      * @param requestCode If >= 0, this code will be returned in
5265      *                    onActivityResult() when the activity exits.
5266      *
5267      * @throws android.content.ActivityNotFoundException
5268      *
5269      * @see #startActivity
5270      */
5271     public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
5272         startActivityForResult(intent, requestCode, null);
5273     }
5274 
5275     /**
5276      * Launch an activity for which you would like a result when it finished.
5277      * When this activity exits, your
5278      * onActivityResult() method will be called with the given requestCode.
5279      * Using a negative requestCode is the same as calling
5280      * {@link #startActivity} (the activity is not launched as a sub-activity).
5281      *
5282      * <p>Note that this method should only be used with Intent protocols
5283      * that are defined to return a result.  In other protocols (such as
5284      * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5285      * not get the result when you expect.  For example, if the activity you
5286      * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5287      * run in your task and thus you will immediately receive a cancel result.
5288      *
5289      * <p>As a special case, if you call startActivityForResult() with a requestCode
5290      * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
5291      * activity, then your window will not be displayed until a result is
5292      * returned back from the started activity.  This is to avoid visible
5293      * flickering when redirecting to another activity.
5294      *
5295      * <p>This method throws {@link android.content.ActivityNotFoundException}
5296      * if there was no Activity found to run the given Intent.
5297      *
5298      * @param intent The intent to start.
5299      * @param requestCode If >= 0, this code will be returned in
5300      *                    onActivityResult() when the activity exits.
5301      * @param options Additional options for how the Activity should be started.
5302      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5303      * Context.startActivity(Intent, Bundle)} for more details.
5304      *
5305      * @throws android.content.ActivityNotFoundException
5306      *
5307      * @see #startActivity
5308      */
5309     public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
5310             @Nullable Bundle options) {
5311         if (mParent == null) {
5312             options = transferSpringboardActivityOptions(options);
5313             Instrumentation.ActivityResult ar =
5314                 mInstrumentation.execStartActivity(
5315                     this, mMainThread.getApplicationThread(), mToken, this,
5316                     intent, requestCode, options);
5317             if (ar != null) {
5318                 mMainThread.sendActivityResult(
5319                     mToken, mEmbeddedID, requestCode, ar.getResultCode(),
5320                     ar.getResultData());
5321             }
5322             if (requestCode >= 0) {
5323                 // If this start is requesting a result, we can avoid making
5324                 // the activity visible until the result is received.  Setting
5325                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5326                 // activity hidden during this time, to avoid flickering.
5327                 // This can only be done when a result is requested because
5328                 // that guarantees we will get information back when the
5329                 // activity is finished, no matter what happens to it.
5330                 mStartedActivity = true;
5331             }
5332 
5333             cancelInputsAndStartExitTransition(options);
5334             // TODO Consider clearing/flushing other event sources and events for child windows.
5335         } else {
5336             if (options != null) {
5337                 mParent.startActivityFromChild(this, intent, requestCode, options);
5338             } else {
5339                 // Note we want to go through this method for compatibility with
5340                 // existing applications that may have overridden it.
5341                 mParent.startActivityFromChild(this, intent, requestCode);
5342             }
5343         }
5344     }
5345 
5346     /**
5347      * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
5348      *
5349      * @param options The ActivityOptions bundle used to start an Activity.
5350      */
5351     private void cancelInputsAndStartExitTransition(Bundle options) {
5352         final View decor = mWindow != null ? mWindow.peekDecorView() : null;
5353         if (decor != null) {
5354             decor.cancelPendingInputEvents();
5355         }
5356         if (options != null) {
5357             mActivityTransitionState.startExitOutTransition(this, options);
5358         }
5359     }
5360 
5361     /**
5362      * Returns whether there are any activity transitions currently running on this
5363      * activity. A return value of {@code true} can mean that either an enter or
5364      * exit transition is running, including whether the background of the activity
5365      * is animating as a part of that transition.
5366      *
5367      * @return true if a transition is currently running on this activity, false otherwise.
5368      */
5369     public boolean isActivityTransitionRunning() {
5370         return mActivityTransitionState.isTransitionRunning();
5371     }
5372 
5373     private Bundle transferSpringboardActivityOptions(Bundle options) {
5374         if (options == null && (mWindow != null && !mWindow.isActive())) {
5375             final ActivityOptions activityOptions = getActivityOptions();
5376             if (activityOptions != null &&
5377                     activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
5378                 return activityOptions.toBundle();
5379             }
5380         }
5381         return options;
5382     }
5383 
5384     /**
5385      * @hide Implement to provide correct calling token.
5386      */
5387     @UnsupportedAppUsage
5388     public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
5389         startActivityForResultAsUser(intent, requestCode, null, user);
5390     }
5391 
5392     /**
5393      * @hide Implement to provide correct calling token.
5394      */
5395     public void startActivityForResultAsUser(Intent intent, int requestCode,
5396             @Nullable Bundle options, UserHandle user) {
5397         startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
5398     }
5399 
5400     /**
5401      * @hide Implement to provide correct calling token.
5402      */
5403     public void startActivityForResultAsUser(Intent intent, String resultWho, int requestCode,
5404             @Nullable Bundle options, UserHandle user) {
5405         if (mParent != null) {
5406             throw new RuntimeException("Can't be called from a child");
5407         }
5408         options = transferSpringboardActivityOptions(options);
5409         Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
5410                 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
5411                 options, user);
5412         if (ar != null) {
5413             mMainThread.sendActivityResult(
5414                 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
5415         }
5416         if (requestCode >= 0) {
5417             // If this start is requesting a result, we can avoid making
5418             // the activity visible until the result is received.  Setting
5419             // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5420             // activity hidden during this time, to avoid flickering.
5421             // This can only be done when a result is requested because
5422             // that guarantees we will get information back when the
5423             // activity is finished, no matter what happens to it.
5424             mStartedActivity = true;
5425         }
5426 
5427         cancelInputsAndStartExitTransition(options);
5428     }
5429 
5430     /**
5431      * @hide Implement to provide correct calling token.
5432      */
5433     @Override
startActivityAsUser(Intent intent, UserHandle user)5434     public void startActivityAsUser(Intent intent, UserHandle user) {
5435         startActivityAsUser(intent, null, user);
5436     }
5437 
5438     /**
5439      * @hide Implement to provide correct calling token.
5440      */
startActivityAsUser(Intent intent, Bundle options, UserHandle user)5441     public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
5442         if (mParent != null) {
5443             throw new RuntimeException("Can't be called from a child");
5444         }
5445         options = transferSpringboardActivityOptions(options);
5446         Instrumentation.ActivityResult ar =
5447                 mInstrumentation.execStartActivity(
5448                         this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
5449                         intent, -1, options, user);
5450         if (ar != null) {
5451             mMainThread.sendActivityResult(
5452                 mToken, mEmbeddedID, -1, ar.getResultCode(),
5453                 ar.getResultData());
5454         }
5455         cancelInputsAndStartExitTransition(options);
5456     }
5457 
5458     /**
5459      * Start a new activity as if it was started by the activity that started our
5460      * current activity.  This is for the resolver and chooser activities, which operate
5461      * as intermediaries that dispatch their intent to the target the user selects -- to
5462      * do this, they must perform all security checks including permission grants as if
5463      * their launch had come from the original activity.
5464      * @param intent The Intent to start.
5465      * @param options ActivityOptions or null.
5466      * @param permissionToken Token received from the system that permits this call to be made.
5467      * @param ignoreTargetSecurity If true, the activity manager will not check whether the
5468      * caller it is doing the start is, is actually allowed to start the target activity.
5469      * If you set this to true, you must set an explicit component in the Intent and do any
5470      * appropriate security checks yourself.
5471      * @param userId The user the new activity should run as.
5472      * @hide
5473      */
startActivityAsCaller(Intent intent, @Nullable Bundle options, IBinder permissionToken, boolean ignoreTargetSecurity, int userId)5474     public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
5475             IBinder permissionToken, boolean ignoreTargetSecurity, int userId) {
5476         if (mParent != null) {
5477             throw new RuntimeException("Can't be called from a child");
5478         }
5479         options = transferSpringboardActivityOptions(options);
5480         Instrumentation.ActivityResult ar =
5481                 mInstrumentation.execStartActivityAsCaller(
5482                         this, mMainThread.getApplicationThread(), mToken, this,
5483                         intent, -1, options, permissionToken, ignoreTargetSecurity, userId);
5484         if (ar != null) {
5485             mMainThread.sendActivityResult(
5486                 mToken, mEmbeddedID, -1, ar.getResultCode(),
5487                 ar.getResultData());
5488         }
5489         cancelInputsAndStartExitTransition(options);
5490     }
5491 
5492     /**
5493      * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
5494      * Intent, int, int, int, Bundle)} with no options.
5495      *
5496      * @param intent The IntentSender to launch.
5497      * @param requestCode If >= 0, this code will be returned in
5498      *                    onActivityResult() when the activity exits.
5499      * @param fillInIntent If non-null, this will be provided as the
5500      * intent parameter to {@link IntentSender#sendIntent}.
5501      * @param flagsMask Intent flags in the original IntentSender that you
5502      * would like to change.
5503      * @param flagsValues Desired values for any bits set in
5504      * <var>flagsMask</var>
5505      * @param extraFlags Always set to 0.
5506      */
startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)5507     public void startIntentSenderForResult(IntentSender intent, int requestCode,
5508             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
5509             throws IntentSender.SendIntentException {
5510         startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
5511                 flagsValues, extraFlags, null);
5512     }
5513 
5514     /**
5515      * Like {@link #startActivityForResult(Intent, int)}, but allowing you
5516      * to use a IntentSender to describe the activity to be started.  If
5517      * the IntentSender is for an activity, that activity will be started
5518      * as if you had called the regular {@link #startActivityForResult(Intent, int)}
5519      * here; otherwise, its associated action will be executed (such as
5520      * sending a broadcast) as if you had called
5521      * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
5522      *
5523      * @param intent The IntentSender to launch.
5524      * @param requestCode If >= 0, this code will be returned in
5525      *                    onActivityResult() when the activity exits.
5526      * @param fillInIntent If non-null, this will be provided as the
5527      * intent parameter to {@link IntentSender#sendIntent}.
5528      * @param flagsMask Intent flags in the original IntentSender that you
5529      * would like to change.
5530      * @param flagsValues Desired values for any bits set in
5531      * <var>flagsMask</var>
5532      * @param extraFlags Always set to 0.
5533      * @param options Additional options for how the Activity should be started.
5534      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5535      * Context.startActivity(Intent, Bundle)} for more details.  If options
5536      * have also been supplied by the IntentSender, options given here will
5537      * override any that conflict with those given by the IntentSender.
5538      */
startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)5539     public void startIntentSenderForResult(IntentSender intent, int requestCode,
5540             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
5541             Bundle options) throws IntentSender.SendIntentException {
5542         if (mParent == null) {
5543             startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
5544                     flagsMask, flagsValues, options);
5545         } else if (options != null) {
5546             mParent.startIntentSenderFromChild(this, intent, requestCode,
5547                     fillInIntent, flagsMask, flagsValues, extraFlags, options);
5548         } else {
5549             // Note we want to go through this call for compatibility with
5550             // existing applications that may have overridden the method.
5551             mParent.startIntentSenderFromChild(this, intent, requestCode,
5552                     fillInIntent, flagsMask, flagsValues, extraFlags);
5553         }
5554     }
5555 
startIntentSenderForResultInner(IntentSender intent, String who, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, Bundle options)5556     private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
5557             Intent fillInIntent, int flagsMask, int flagsValues,
5558             Bundle options)
5559             throws IntentSender.SendIntentException {
5560         try {
5561             options = transferSpringboardActivityOptions(options);
5562             String resolvedType = null;
5563             if (fillInIntent != null) {
5564                 fillInIntent.migrateExtraStreamToClipData(this);
5565                 fillInIntent.prepareToLeaveProcess(this);
5566                 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
5567             }
5568             int result = ActivityTaskManager.getService()
5569                 .startActivityIntentSender(mMainThread.getApplicationThread(),
5570                         intent != null ? intent.getTarget() : null,
5571                         intent != null ? intent.getWhitelistToken() : null,
5572                         fillInIntent, resolvedType, mToken, who,
5573                         requestCode, flagsMask, flagsValues, options);
5574             if (result == ActivityManager.START_CANCELED) {
5575                 throw new IntentSender.SendIntentException();
5576             }
5577             Instrumentation.checkStartActivityResult(result, null);
5578 
5579             if (options != null) {
5580                 // Only when the options are not null, as the intent can point to something other
5581                 // than an Activity.
5582                 cancelInputsAndStartExitTransition(options);
5583             }
5584         } catch (RemoteException e) {
5585         }
5586         if (requestCode >= 0) {
5587             // If this start is requesting a result, we can avoid making
5588             // the activity visible until the result is received.  Setting
5589             // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5590             // activity hidden during this time, to avoid flickering.
5591             // This can only be done when a result is requested because
5592             // that guarantees we will get information back when the
5593             // activity is finished, no matter what happens to it.
5594             mStartedActivity = true;
5595         }
5596     }
5597 
5598     /**
5599      * Same as {@link #startActivity(Intent, Bundle)} with no options
5600      * specified.
5601      *
5602      * @param intent The intent to start.
5603      *
5604      * @throws android.content.ActivityNotFoundException
5605      *
5606      * @see #startActivity(Intent, Bundle)
5607      * @see #startActivityForResult
5608      */
5609     @Override
startActivity(Intent intent)5610     public void startActivity(Intent intent) {
5611         this.startActivity(intent, null);
5612     }
5613 
5614     /**
5615      * Launch a new activity.  You will not receive any information about when
5616      * the activity exits.  This implementation overrides the base version,
5617      * providing information about
5618      * the activity performing the launch.  Because of this additional
5619      * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5620      * required; if not specified, the new activity will be added to the
5621      * task of the caller.
5622      *
5623      * <p>This method throws {@link android.content.ActivityNotFoundException}
5624      * if there was no Activity found to run the given Intent.
5625      *
5626      * @param intent The intent to start.
5627      * @param options Additional options for how the Activity should be started.
5628      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5629      * Context.startActivity(Intent, Bundle)} for more details.
5630      *
5631      * @throws android.content.ActivityNotFoundException
5632      *
5633      * @see #startActivity(Intent)
5634      * @see #startActivityForResult
5635      */
5636     @Override
startActivity(Intent intent, @Nullable Bundle options)5637     public void startActivity(Intent intent, @Nullable Bundle options) {
5638         if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)
5639                 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) {
5640             if (TextUtils.equals(getPackageName(),
5641                     intent.resolveActivity(getPackageManager()).getPackageName())) {
5642                 // Apply Autofill restore mechanism on the started activity by startActivity()
5643                 final IBinder token =
5644                         mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
5645                 // Remove restore ability from current activity
5646                 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
5647                 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY);
5648                 // Put restore token
5649                 intent.putExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN, token);
5650                 intent.putExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY, true);
5651             }
5652         }
5653         if (options != null) {
5654             startActivityForResult(intent, -1, options);
5655         } else {
5656             // Note we want to go through this call for compatibility with
5657             // applications that may have overridden the method.
5658             startActivityForResult(intent, -1);
5659         }
5660     }
5661 
5662     /**
5663      * Same as {@link #startActivities(Intent[], Bundle)} with no options
5664      * specified.
5665      *
5666      * @param intents The intents to start.
5667      *
5668      * @throws android.content.ActivityNotFoundException
5669      *
5670      * @see #startActivities(Intent[], Bundle)
5671      * @see #startActivityForResult
5672      */
5673     @Override
startActivities(Intent[] intents)5674     public void startActivities(Intent[] intents) {
5675         startActivities(intents, null);
5676     }
5677 
5678     /**
5679      * Launch a new activity.  You will not receive any information about when
5680      * the activity exits.  This implementation overrides the base version,
5681      * providing information about
5682      * the activity performing the launch.  Because of this additional
5683      * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5684      * required; if not specified, the new activity will be added to the
5685      * task of the caller.
5686      *
5687      * <p>This method throws {@link android.content.ActivityNotFoundException}
5688      * if there was no Activity found to run the given Intent.
5689      *
5690      * @param intents The intents to start.
5691      * @param options Additional options for how the Activity should be started.
5692      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5693      * Context.startActivity(Intent, Bundle)} for more details.
5694      *
5695      * @throws android.content.ActivityNotFoundException
5696      *
5697      * @see #startActivities(Intent[])
5698      * @see #startActivityForResult
5699      */
5700     @Override
startActivities(Intent[] intents, @Nullable Bundle options)5701     public void startActivities(Intent[] intents, @Nullable Bundle options) {
5702         mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
5703                 mToken, this, intents, options);
5704     }
5705 
5706     /**
5707      * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
5708      * with no options.
5709      *
5710      * @param intent The IntentSender to launch.
5711      * @param fillInIntent If non-null, this will be provided as the
5712      * intent parameter to {@link IntentSender#sendIntent}.
5713      * @param flagsMask Intent flags in the original IntentSender that you
5714      * would like to change.
5715      * @param flagsValues Desired values for any bits set in
5716      * <var>flagsMask</var>
5717      * @param extraFlags Always set to 0.
5718      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)5719     public void startIntentSender(IntentSender intent,
5720             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
5721             throws IntentSender.SendIntentException {
5722         startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
5723                 extraFlags, null);
5724     }
5725 
5726     /**
5727      * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
5728      * to start; see
5729      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
5730      * for more information.
5731      *
5732      * @param intent The IntentSender to launch.
5733      * @param fillInIntent If non-null, this will be provided as the
5734      * intent parameter to {@link IntentSender#sendIntent}.
5735      * @param flagsMask Intent flags in the original IntentSender that you
5736      * would like to change.
5737      * @param flagsValues Desired values for any bits set in
5738      * <var>flagsMask</var>
5739      * @param extraFlags Always set to 0.
5740      * @param options Additional options for how the Activity should be started.
5741      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5742      * Context.startActivity(Intent, Bundle)} for more details.  If options
5743      * have also been supplied by the IntentSender, options given here will
5744      * override any that conflict with those given by the IntentSender.
5745      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)5746     public void startIntentSender(IntentSender intent,
5747             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
5748             Bundle options) throws IntentSender.SendIntentException {
5749         if (options != null) {
5750             startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
5751                     flagsValues, extraFlags, options);
5752         } else {
5753             // Note we want to go through this call for compatibility with
5754             // applications that may have overridden the method.
5755             startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
5756                     flagsValues, extraFlags);
5757         }
5758     }
5759 
5760     /**
5761      * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
5762      * with no options.
5763      *
5764      * @param intent The intent to start.
5765      * @param requestCode If >= 0, this code will be returned in
5766      *         onActivityResult() when the activity exits, as described in
5767      *         {@link #startActivityForResult}.
5768      *
5769      * @return If a new activity was launched then true is returned; otherwise
5770      *         false is returned and you must handle the Intent yourself.
5771      *
5772      * @see #startActivity
5773      * @see #startActivityForResult
5774      */
startActivityIfNeeded(@equiresPermission @onNull Intent intent, int requestCode)5775     public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
5776             int requestCode) {
5777         return startActivityIfNeeded(intent, requestCode, null);
5778     }
5779 
5780     /**
5781      * A special variation to launch an activity only if a new activity
5782      * instance is needed to handle the given Intent.  In other words, this is
5783      * just like {@link #startActivityForResult(Intent, int)} except: if you are
5784      * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
5785      * singleTask or singleTop
5786      * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
5787      * and the activity
5788      * that handles <var>intent</var> is the same as your currently running
5789      * activity, then a new instance is not needed.  In this case, instead of
5790      * the normal behavior of calling {@link #onNewIntent} this function will
5791      * return and you can handle the Intent yourself.
5792      *
5793      * <p>This function can only be called from a top-level activity; if it is
5794      * called from a child activity, a runtime exception will be thrown.
5795      *
5796      * @param intent The intent to start.
5797      * @param requestCode If >= 0, this code will be returned in
5798      *         onActivityResult() when the activity exits, as described in
5799      *         {@link #startActivityForResult}.
5800      * @param options Additional options for how the Activity should be started.
5801      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5802      * Context.startActivity(Intent, Bundle)} for more details.
5803      *
5804      * @return If a new activity was launched then true is returned; otherwise
5805      *         false is returned and you must handle the Intent yourself.
5806      *
5807      * @see #startActivity
5808      * @see #startActivityForResult
5809      */
startActivityIfNeeded(@equiresPermission @onNull Intent intent, int requestCode, @Nullable Bundle options)5810     public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
5811             int requestCode, @Nullable Bundle options) {
5812         if (mParent == null) {
5813             int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
5814             try {
5815                 Uri referrer = onProvideReferrer();
5816                 if (referrer != null) {
5817                     intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5818                 }
5819                 intent.migrateExtraStreamToClipData(this);
5820                 intent.prepareToLeaveProcess(this);
5821                 result = ActivityTaskManager.getService()
5822                     .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
5823                             getAttributionTag(), intent,
5824                             intent.resolveTypeIfNeeded(getContentResolver()), mToken, mEmbeddedID,
5825                             requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, options);
5826             } catch (RemoteException e) {
5827                 // Empty
5828             }
5829 
5830             Instrumentation.checkStartActivityResult(result, intent);
5831 
5832             if (requestCode >= 0) {
5833                 // If this start is requesting a result, we can avoid making
5834                 // the activity visible until the result is received.  Setting
5835                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5836                 // activity hidden during this time, to avoid flickering.
5837                 // This can only be done when a result is requested because
5838                 // that guarantees we will get information back when the
5839                 // activity is finished, no matter what happens to it.
5840                 mStartedActivity = true;
5841             }
5842             return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
5843         }
5844 
5845         throw new UnsupportedOperationException(
5846             "startActivityIfNeeded can only be called from a top-level activity");
5847     }
5848 
5849     /**
5850      * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
5851      * no options.
5852      *
5853      * @param intent The intent to dispatch to the next activity.  For
5854      * correct behavior, this must be the same as the Intent that started
5855      * your own activity; the only changes you can make are to the extras
5856      * inside of it.
5857      *
5858      * @return Returns a boolean indicating whether there was another Activity
5859      * to start: true if there was a next activity to start, false if there
5860      * wasn't.  In general, if true is returned you will then want to call
5861      * finish() on yourself.
5862      */
startNextMatchingActivity(@equiresPermission @onNull Intent intent)5863     public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
5864         return startNextMatchingActivity(intent, null);
5865     }
5866 
5867     /**
5868      * Special version of starting an activity, for use when you are replacing
5869      * other activity components.  You can use this to hand the Intent off
5870      * to the next Activity that can handle it.  You typically call this in
5871      * {@link #onCreate} with the Intent returned by {@link #getIntent}.
5872      *
5873      * @param intent The intent to dispatch to the next activity.  For
5874      * correct behavior, this must be the same as the Intent that started
5875      * your own activity; the only changes you can make are to the extras
5876      * inside of it.
5877      * @param options Additional options for how the Activity should be started.
5878      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5879      * Context.startActivity(Intent, Bundle)} for more details.
5880      *
5881      * @return Returns a boolean indicating whether there was another Activity
5882      * to start: true if there was a next activity to start, false if there
5883      * wasn't.  In general, if true is returned you will then want to call
5884      * finish() on yourself.
5885      */
startNextMatchingActivity(@equiresPermission @onNull Intent intent, @Nullable Bundle options)5886     public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
5887             @Nullable Bundle options) {
5888         if (mParent == null) {
5889             try {
5890                 intent.migrateExtraStreamToClipData(this);
5891                 intent.prepareToLeaveProcess(this);
5892                 return ActivityTaskManager.getService()
5893                     .startNextMatchingActivity(mToken, intent, options);
5894             } catch (RemoteException e) {
5895                 // Empty
5896             }
5897             return false;
5898         }
5899 
5900         throw new UnsupportedOperationException(
5901             "startNextMatchingActivity can only be called from a top-level activity");
5902     }
5903 
5904     /**
5905      * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
5906      * with no options.
5907      *
5908      * @param child The activity making the call.
5909      * @param intent The intent to start.
5910      * @param requestCode Reply request code.  < 0 if reply is not requested.
5911      *
5912      * @throws android.content.ActivityNotFoundException
5913      *
5914      * @see #startActivity
5915      * @see #startActivityForResult
5916      * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5917      * androidx.fragment.app.Fragment,Intent,int)}
5918      */
5919     @Deprecated
startActivityFromChild(@onNull Activity child, @RequiresPermission Intent intent, int requestCode)5920     public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5921             int requestCode) {
5922         startActivityFromChild(child, intent, requestCode, null);
5923     }
5924 
5925     /**
5926      * This is called when a child activity of this one calls its
5927      * {@link #startActivity} or {@link #startActivityForResult} method.
5928      *
5929      * <p>This method throws {@link android.content.ActivityNotFoundException}
5930      * if there was no Activity found to run the given Intent.
5931      *
5932      * @param child The activity making the call.
5933      * @param intent The intent to start.
5934      * @param requestCode Reply request code.  < 0 if reply is not requested.
5935      * @param options Additional options for how the Activity should be started.
5936      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5937      * Context.startActivity(Intent, Bundle)} for more details.
5938      *
5939      * @throws android.content.ActivityNotFoundException
5940      *
5941      * @see #startActivity
5942      * @see #startActivityForResult
5943      * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5944      * androidx.fragment.app.Fragment,Intent,int,Bundle)}
5945      */
5946     @Deprecated
startActivityFromChild(@onNull Activity child, @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options)5947     public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5948             int requestCode, @Nullable Bundle options) {
5949         options = transferSpringboardActivityOptions(options);
5950         Instrumentation.ActivityResult ar =
5951             mInstrumentation.execStartActivity(
5952                 this, mMainThread.getApplicationThread(), mToken, child,
5953                 intent, requestCode, options);
5954         if (ar != null) {
5955             mMainThread.sendActivityResult(
5956                 mToken, child.mEmbeddedID, requestCode,
5957                 ar.getResultCode(), ar.getResultData());
5958         }
5959         cancelInputsAndStartExitTransition(options);
5960     }
5961 
5962     /**
5963      * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
5964      * with no options.
5965      *
5966      * @param fragment The fragment making the call.
5967      * @param intent The intent to start.
5968      * @param requestCode Reply request code.  < 0 if reply is not requested.
5969      *
5970      * @throws android.content.ActivityNotFoundException
5971      *
5972      * @see Fragment#startActivity
5973      * @see Fragment#startActivityForResult
5974      *
5975      * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5976      * androidx.fragment.app.Fragment,Intent,int)}
5977      */
5978     @Deprecated
startActivityFromFragment(@onNull Fragment fragment, @RequiresPermission Intent intent, int requestCode)5979     public void startActivityFromFragment(@NonNull Fragment fragment,
5980             @RequiresPermission Intent intent, int requestCode) {
5981         startActivityFromFragment(fragment, intent, requestCode, null);
5982     }
5983 
5984     /**
5985      * This is called when a Fragment in this activity calls its
5986      * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
5987      * method.
5988      *
5989      * <p>This method throws {@link android.content.ActivityNotFoundException}
5990      * if there was no Activity found to run the given Intent.
5991      *
5992      * @param fragment The fragment making the call.
5993      * @param intent The intent to start.
5994      * @param requestCode Reply request code.  < 0 if reply is not requested.
5995      * @param options Additional options for how the Activity should be started.
5996      * See {@link android.content.Context#startActivity(Intent, Bundle)}
5997      * Context.startActivity(Intent, Bundle)} for more details.
5998      *
5999      * @throws android.content.ActivityNotFoundException
6000      *
6001      * @see Fragment#startActivity
6002      * @see Fragment#startActivityForResult
6003      *
6004      * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6005      * androidx.fragment.app.Fragment,Intent,int,Bundle)}
6006      */
6007     @Deprecated
startActivityFromFragment(@onNull Fragment fragment, @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options)6008     public void startActivityFromFragment(@NonNull Fragment fragment,
6009             @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
6010         startActivityForResult(fragment.mWho, intent, requestCode, options);
6011     }
6012 
startActivityAsUserFromFragment(@onNull Fragment fragment, @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options, UserHandle user)6013     private void startActivityAsUserFromFragment(@NonNull Fragment fragment,
6014             @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
6015             UserHandle user) {
6016         startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
6017     }
6018 
6019     /**
6020      * @hide
6021      */
6022     @Override
6023     @UnsupportedAppUsage
startActivityForResult( String who, Intent intent, int requestCode, @Nullable Bundle options)6024     public void startActivityForResult(
6025             String who, Intent intent, int requestCode, @Nullable Bundle options) {
6026         Uri referrer = onProvideReferrer();
6027         if (referrer != null) {
6028             intent.putExtra(Intent.EXTRA_REFERRER, referrer);
6029         }
6030         options = transferSpringboardActivityOptions(options);
6031         Instrumentation.ActivityResult ar =
6032             mInstrumentation.execStartActivity(
6033                 this, mMainThread.getApplicationThread(), mToken, who,
6034                 intent, requestCode, options);
6035         if (ar != null) {
6036             mMainThread.sendActivityResult(
6037                 mToken, who, requestCode,
6038                 ar.getResultCode(), ar.getResultData());
6039         }
6040         cancelInputsAndStartExitTransition(options);
6041     }
6042 
6043     /**
6044      * @hide
6045      */
6046     @Override
canStartActivityForResult()6047     public boolean canStartActivityForResult() {
6048         return true;
6049     }
6050 
6051     /**
6052      * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
6053      * int, Intent, int, int, int, Bundle)} with no options.
6054      * @deprecated Use {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6055      * instead.
6056      */
6057     @Deprecated
startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)6058     public void startIntentSenderFromChild(Activity child, IntentSender intent,
6059             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6060             int extraFlags)
6061             throws IntentSender.SendIntentException {
6062         startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
6063                 flagsMask, flagsValues, extraFlags, null);
6064     }
6065 
6066     /**
6067      * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
6068      * taking a IntentSender; see
6069      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6070      * for more information.
6071      * @deprecated Use
6072      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
6073      * instead.
6074      */
6075     @Deprecated
startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options)6076     public void startIntentSenderFromChild(Activity child, IntentSender intent,
6077             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6078             int extraFlags, @Nullable Bundle options)
6079             throws IntentSender.SendIntentException {
6080         startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
6081                 flagsMask, flagsValues, options);
6082     }
6083 
6084     /**
6085      * Like {@link #startIntentSender}, but taking a Fragment; see
6086      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6087      * for more information.
6088      */
startIntentSenderFromFragment(Fragment fragment, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, @Nullable Bundle options)6089     private void startIntentSenderFromFragment(Fragment fragment, IntentSender intent,
6090             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6091             @Nullable Bundle options)
6092             throws IntentSender.SendIntentException {
6093         startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
6094                 flagsMask, flagsValues, options);
6095     }
6096 
6097     /**
6098      * Call immediately after one of the flavors of {@link #startActivity(Intent)}
6099      * or {@link #finish} to specify an explicit transition animation to
6100      * perform next.
6101      *
6102      * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
6103      * to using this with starting activities is to supply the desired animation
6104      * information through a {@link ActivityOptions} bundle to
6105      * {@link #startActivity(Intent, Bundle)} or a related function.  This allows
6106      * you to specify a custom animation even when starting an activity from
6107      * outside the context of the current top activity.
6108      *
6109      * @param enterAnim A resource ID of the animation resource to use for
6110      * the incoming activity.  Use 0 for no animation.
6111      * @param exitAnim A resource ID of the animation resource to use for
6112      * the outgoing activity.  Use 0 for no animation.
6113      */
overridePendingTransition(int enterAnim, int exitAnim)6114     public void overridePendingTransition(int enterAnim, int exitAnim) {
6115         try {
6116             ActivityTaskManager.getService().overridePendingTransition(
6117                     mToken, getPackageName(), enterAnim, exitAnim);
6118         } catch (RemoteException e) {
6119         }
6120     }
6121 
6122     /**
6123      * Call this to set the result that your activity will return to its
6124      * caller.
6125      *
6126      * @param resultCode The result code to propagate back to the originating
6127      *                   activity, often RESULT_CANCELED or RESULT_OK
6128      *
6129      * @see #RESULT_CANCELED
6130      * @see #RESULT_OK
6131      * @see #RESULT_FIRST_USER
6132      * @see #setResult(int, Intent)
6133      */
setResult(int resultCode)6134     public final void setResult(int resultCode) {
6135         synchronized (this) {
6136             mResultCode = resultCode;
6137             mResultData = null;
6138         }
6139     }
6140 
6141     /**
6142      * Call this to set the result that your activity will return to its
6143      * caller.
6144      *
6145      * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
6146      * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
6147      * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
6148      * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set.  This will grant the
6149      * Activity receiving the result access to the specific URIs in the Intent.
6150      * Access will remain until the Activity has finished (it will remain across the hosting
6151      * process being killed and other temporary destruction) and will be added
6152      * to any existing set of URI permissions it already holds.
6153      *
6154      * @param resultCode The result code to propagate back to the originating
6155      *                   activity, often RESULT_CANCELED or RESULT_OK
6156      * @param data The data to propagate back to the originating activity.
6157      *
6158      * @see #RESULT_CANCELED
6159      * @see #RESULT_OK
6160      * @see #RESULT_FIRST_USER
6161      * @see #setResult(int)
6162      */
setResult(int resultCode, Intent data)6163     public final void setResult(int resultCode, Intent data) {
6164         synchronized (this) {
6165             mResultCode = resultCode;
6166             mResultData = data;
6167         }
6168     }
6169 
6170     /**
6171      * Return information about who launched this activity.  If the launching Intent
6172      * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
6173      * that will be returned as-is; otherwise, if known, an
6174      * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
6175      * package name that started the Intent will be returned.  This may return null if no
6176      * referrer can be identified -- it is neither explicitly specified, nor is it known which
6177      * application package was involved.
6178      *
6179      * <p>If called while inside the handling of {@link #onNewIntent}, this function will
6180      * return the referrer that submitted that new intent to the activity.  Otherwise, it
6181      * always returns the referrer of the original Intent.</p>
6182      *
6183      * <p>Note that this is <em>not</em> a security feature -- you can not trust the
6184      * referrer information, applications can spoof it.</p>
6185      */
6186     @Nullable
getReferrer()6187     public Uri getReferrer() {
6188         Intent intent = getIntent();
6189         try {
6190             Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
6191             if (referrer != null) {
6192                 return referrer;
6193             }
6194             String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
6195             if (referrerName != null) {
6196                 return Uri.parse(referrerName);
6197             }
6198         } catch (BadParcelableException e) {
6199             Log.w(TAG, "Cannot read referrer from intent;"
6200                     + " intent extras contain unknown custom Parcelable objects");
6201         }
6202         if (mReferrer != null) {
6203             return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
6204         }
6205         return null;
6206     }
6207 
6208     /**
6209      * Override to generate the desired referrer for the content currently being shown
6210      * by the app.  The default implementation returns null, meaning the referrer will simply
6211      * be the android-app: of the package name of this activity.  Return a non-null Uri to
6212      * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
6213      */
onProvideReferrer()6214     public Uri onProvideReferrer() {
6215         return null;
6216     }
6217 
6218     /**
6219      * Return the name of the package that invoked this activity.  This is who
6220      * the data in {@link #setResult setResult()} will be sent to.  You can
6221      * use this information to validate that the recipient is allowed to
6222      * receive the data.
6223      *
6224      * <p class="note">Note: if the calling activity is not expecting a result (that is it
6225      * did not use the {@link #startActivityForResult}
6226      * form that includes a request code), then the calling package will be
6227      * null.</p>
6228      *
6229      * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
6230      * the result from this method was unstable.  If the process hosting the calling
6231      * package was no longer running, it would return null instead of the proper package
6232      * name.  You can use {@link #getCallingActivity()} and retrieve the package name
6233      * from that instead.</p>
6234      *
6235      * @return The package of the activity that will receive your
6236      *         reply, or null if none.
6237      */
6238     @Nullable
getCallingPackage()6239     public String getCallingPackage() {
6240         try {
6241             return ActivityTaskManager.getService().getCallingPackage(mToken);
6242         } catch (RemoteException e) {
6243             return null;
6244         }
6245     }
6246 
6247     /**
6248      * Return the name of the activity that invoked this activity.  This is
6249      * who the data in {@link #setResult setResult()} will be sent to.  You
6250      * can use this information to validate that the recipient is allowed to
6251      * receive the data.
6252      *
6253      * <p class="note">Note: if the calling activity is not expecting a result (that is it
6254      * did not use the {@link #startActivityForResult}
6255      * form that includes a request code), then the calling package will be
6256      * null.
6257      *
6258      * @return The ComponentName of the activity that will receive your
6259      *         reply, or null if none.
6260      */
6261     @Nullable
getCallingActivity()6262     public ComponentName getCallingActivity() {
6263         try {
6264             return ActivityTaskManager.getService().getCallingActivity(mToken);
6265         } catch (RemoteException e) {
6266             return null;
6267         }
6268     }
6269 
6270     /**
6271      * Control whether this activity's main window is visible.  This is intended
6272      * only for the special case of an activity that is not going to show a
6273      * UI itself, but can't just finish prior to onResume() because it needs
6274      * to wait for a service binding or such.  Setting this to false allows
6275      * you to prevent your UI from being shown during that time.
6276      *
6277      * <p>The default value for this is taken from the
6278      * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
6279      */
setVisible(boolean visible)6280     public void setVisible(boolean visible) {
6281         if (mVisibleFromClient != visible) {
6282             mVisibleFromClient = visible;
6283             if (mVisibleFromServer) {
6284                 if (visible) makeVisible();
6285                 else mDecor.setVisibility(View.INVISIBLE);
6286             }
6287         }
6288     }
6289 
makeVisible()6290     void makeVisible() {
6291         if (!mWindowAdded) {
6292             ViewManager wm = getWindowManager();
6293             wm.addView(mDecor, getWindow().getAttributes());
6294             mWindowAdded = true;
6295         }
6296         mDecor.setVisibility(View.VISIBLE);
6297     }
6298 
6299     /**
6300      * Check to see whether this activity is in the process of finishing,
6301      * either because you called {@link #finish} on it or someone else
6302      * has requested that it finished.  This is often used in
6303      * {@link #onPause} to determine whether the activity is simply pausing or
6304      * completely finishing.
6305      *
6306      * @return If the activity is finishing, returns true; else returns false.
6307      *
6308      * @see #finish
6309      */
isFinishing()6310     public boolean isFinishing() {
6311         return mFinished;
6312     }
6313 
6314     /**
6315      * Returns true if the final {@link #onDestroy()} call has been made
6316      * on the Activity, so this instance is now dead.
6317      */
isDestroyed()6318     public boolean isDestroyed() {
6319         return mDestroyed;
6320     }
6321 
6322     /**
6323      * Check to see whether this activity is in the process of being destroyed in order to be
6324      * recreated with a new configuration. This is often used in
6325      * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
6326      * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
6327      *
6328      * @return If the activity is being torn down in order to be recreated with a new configuration,
6329      * returns true; else returns false.
6330      */
isChangingConfigurations()6331     public boolean isChangingConfigurations() {
6332         return mChangingConfigurations;
6333     }
6334 
6335     /**
6336      * Cause this Activity to be recreated with a new instance.  This results
6337      * in essentially the same flow as when the Activity is created due to
6338      * a configuration change -- the current instance will go through its
6339      * lifecycle to {@link #onDestroy} and a new instance then created after it.
6340      */
recreate()6341     public void recreate() {
6342         if (mParent != null) {
6343             throw new IllegalStateException("Can only be called on top-level activity");
6344         }
6345         if (Looper.myLooper() != mMainThread.getLooper()) {
6346             throw new IllegalStateException("Must be called from main thread");
6347         }
6348         mMainThread.scheduleRelaunchActivity(mToken);
6349     }
6350 
6351     /**
6352      * Finishes the current activity and specifies whether to remove the task associated with this
6353      * activity.
6354      */
6355     @UnsupportedAppUsage
finish(int finishTask)6356     private void finish(int finishTask) {
6357         if (mParent == null) {
6358             int resultCode;
6359             Intent resultData;
6360             synchronized (this) {
6361                 resultCode = mResultCode;
6362                 resultData = mResultData;
6363             }
6364             if (false) Log.v(TAG, "Finishing self: token=" + mToken);
6365             try {
6366                 if (resultData != null) {
6367                     resultData.prepareToLeaveProcess(this);
6368                 }
6369                 if (ActivityTaskManager.getService()
6370                         .finishActivity(mToken, resultCode, resultData, finishTask)) {
6371                     mFinished = true;
6372                 }
6373             } catch (RemoteException e) {
6374                 // Empty
6375             }
6376         } else {
6377             mParent.finishFromChild(this);
6378         }
6379 
6380         // Activity was launched when user tapped a link in the Autofill Save UI - Save UI must
6381         // be restored now.
6382         if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
6383             restoreAutofillSaveUi();
6384         }
6385     }
6386 
6387     /**
6388      * Restores Autofill Save UI
6389      */
restoreAutofillSaveUi()6390     private void restoreAutofillSaveUi() {
6391         final IBinder token =
6392                 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
6393         // Make only restore Autofill once
6394         mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
6395         mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY);
6396         getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_RESTORE,
6397                 token);
6398     }
6399 
6400     /**
6401      * Call this when your activity is done and should be closed.  The
6402      * ActivityResult is propagated back to whoever launched you via
6403      * onActivityResult().
6404      */
finish()6405     public void finish() {
6406         finish(DONT_FINISH_TASK_WITH_ACTIVITY);
6407     }
6408 
6409     /**
6410      * Finish this activity as well as all activities immediately below it
6411      * in the current task that have the same affinity.  This is typically
6412      * used when an application can be launched on to another task (such as
6413      * from an ACTION_VIEW of a content type it understands) and the user
6414      * has used the up navigation to switch out of the current task and in
6415      * to its own task.  In this case, if the user has navigated down into
6416      * any other activities of the second application, all of those should
6417      * be removed from the original task as part of the task switch.
6418      *
6419      * <p>Note that this finish does <em>not</em> allow you to deliver results
6420      * to the previous activity, and an exception will be thrown if you are trying
6421      * to do so.</p>
6422      */
finishAffinity()6423     public void finishAffinity() {
6424         if (mParent != null) {
6425             throw new IllegalStateException("Can not be called from an embedded activity");
6426         }
6427         if (mResultCode != RESULT_CANCELED || mResultData != null) {
6428             throw new IllegalStateException("Can not be called to deliver a result");
6429         }
6430         try {
6431             if (ActivityTaskManager.getService().finishActivityAffinity(mToken)) {
6432                 mFinished = true;
6433             }
6434         } catch (RemoteException e) {
6435             // Empty
6436         }
6437     }
6438 
6439     /**
6440      * This is called when a child activity of this one calls its
6441      * {@link #finish} method.  The default implementation simply calls
6442      * finish() on this activity (the parent), finishing the entire group.
6443      *
6444      * @param child The activity making the call.
6445      *
6446      * @see #finish
6447      * @deprecated Use {@link #finish()} instead.
6448      */
6449     @Deprecated
finishFromChild(Activity child)6450     public void finishFromChild(Activity child) {
6451         finish();
6452     }
6453 
6454     /**
6455      * Reverses the Activity Scene entry Transition and triggers the calling Activity
6456      * to reverse its exit Transition. When the exit Transition completes,
6457      * {@link #finish()} is called. If no entry Transition was used, finish() is called
6458      * immediately and the Activity exit Transition is run.
6459      * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
6460      */
finishAfterTransition()6461     public void finishAfterTransition() {
6462         if (!mActivityTransitionState.startExitBackTransition(this)) {
6463             finish();
6464         }
6465     }
6466 
6467     /**
6468      * Force finish another activity that you had previously started with
6469      * {@link #startActivityForResult}.
6470      *
6471      * @param requestCode The request code of the activity that you had
6472      *                    given to startActivityForResult().  If there are multiple
6473      *                    activities started with this request code, they
6474      *                    will all be finished.
6475      */
finishActivity(int requestCode)6476     public void finishActivity(int requestCode) {
6477         if (mParent == null) {
6478             try {
6479                 ActivityTaskManager.getService()
6480                     .finishSubActivity(mToken, mEmbeddedID, requestCode);
6481             } catch (RemoteException e) {
6482                 // Empty
6483             }
6484         } else {
6485             mParent.finishActivityFromChild(this, requestCode);
6486         }
6487     }
6488 
6489     /**
6490      * This is called when a child activity of this one calls its
6491      * finishActivity().
6492      *
6493      * @param child The activity making the call.
6494      * @param requestCode Request code that had been used to start the
6495      *                    activity.
6496      * @deprecated Use {@link #finishActivity(int)} instead.
6497      */
6498     @Deprecated
finishActivityFromChild(@onNull Activity child, int requestCode)6499     public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
6500         try {
6501             ActivityTaskManager.getService()
6502                 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
6503         } catch (RemoteException e) {
6504             // Empty
6505         }
6506     }
6507 
6508     /**
6509      * Call this when your activity is done and should be closed and the task should be completely
6510      * removed as a part of finishing the root activity of the task.
6511      */
finishAndRemoveTask()6512     public void finishAndRemoveTask() {
6513         finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
6514     }
6515 
6516     /**
6517      * Ask that the local app instance of this activity be released to free up its memory.
6518      * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
6519      * a new instance of the activity will later be re-created if needed due to the user
6520      * navigating back to it.
6521      *
6522      * @return Returns true if the activity was in a state that it has started the process
6523      * of destroying its current instance; returns false if for any reason this could not
6524      * be done: it is currently visible to the user, it is already being destroyed, it is
6525      * being finished, it hasn't yet saved its state, etc.
6526      */
releaseInstance()6527     public boolean releaseInstance() {
6528         try {
6529             return ActivityTaskManager.getService().releaseActivityInstance(mToken);
6530         } catch (RemoteException e) {
6531             // Empty
6532         }
6533         return false;
6534     }
6535 
6536     /**
6537      * Called when an activity you launched exits, giving you the requestCode
6538      * you started it with, the resultCode it returned, and any additional
6539      * data from it.  The <var>resultCode</var> will be
6540      * {@link #RESULT_CANCELED} if the activity explicitly returned that,
6541      * didn't return any result, or crashed during its operation.
6542      *
6543      * <p>An activity can never receive a result in the resumed state. You can count on
6544      * {@link #onResume} being called after this method, though not necessarily immediately after.
6545      * If the activity was resumed, it will be paused and the result will be delivered, followed
6546      * by {@link #onResume}.  If the activity wasn't in the resumed state, then the result will
6547      * be delivered, with {@link #onResume} called sometime later when the activity becomes active
6548      * again.
6549      *
6550      * <p>This method is never invoked if your activity sets
6551      * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
6552      * <code>true</code>.
6553      *
6554      * @param requestCode The integer request code originally supplied to
6555      *                    startActivityForResult(), allowing you to identify who this
6556      *                    result came from.
6557      * @param resultCode The integer result code returned by the child activity
6558      *                   through its setResult().
6559      * @param data An Intent, which can return result data to the caller
6560      *               (various data can be attached to Intent "extras").
6561      *
6562      * @see #startActivityForResult
6563      * @see #createPendingResult
6564      * @see #setResult(int)
6565      */
onActivityResult(int requestCode, int resultCode, Intent data)6566     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
6567     }
6568 
6569     /**
6570      * Called when an activity you launched with an activity transition exposes this
6571      * Activity through a returning activity transition, giving you the resultCode
6572      * and any additional data from it. This method will only be called if the activity
6573      * set a result code other than {@link #RESULT_CANCELED} and it supports activity
6574      * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6575      *
6576      * <p>The purpose of this function is to let the called Activity send a hint about
6577      * its state so that this underlying Activity can prepare to be exposed. A call to
6578      * this method does not guarantee that the called Activity has or will be exiting soon.
6579      * It only indicates that it will expose this Activity's Window and it has
6580      * some data to pass to prepare it.</p>
6581      *
6582      * @param resultCode The integer result code returned by the child activity
6583      *                   through its setResult().
6584      * @param data An Intent, which can return result data to the caller
6585      *               (various data can be attached to Intent "extras").
6586      */
onActivityReenter(int resultCode, Intent data)6587     public void onActivityReenter(int resultCode, Intent data) {
6588     }
6589 
6590     /**
6591      * Create a new PendingIntent object which you can hand to others
6592      * for them to use to send result data back to your
6593      * {@link #onActivityResult} callback.  The created object will be either
6594      * one-shot (becoming invalid after a result is sent back) or multiple
6595      * (allowing any number of results to be sent through it).
6596      *
6597      * @param requestCode Private request code for the sender that will be
6598      * associated with the result data when it is returned.  The sender can not
6599      * modify this value, allowing you to identify incoming results.
6600      * @param data Default data to supply in the result, which may be modified
6601      * by the sender.
6602      * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
6603      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
6604      * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
6605      * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
6606      * or any of the flags as supported by
6607      * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
6608      * of the intent that can be supplied when the actual send happens.
6609      *
6610      * @return Returns an existing or new PendingIntent matching the given
6611      * parameters.  May return null only if
6612      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
6613      * supplied.
6614      *
6615      * @see PendingIntent
6616      */
createPendingResult(int requestCode, @NonNull Intent data, @PendingIntent.Flags int flags)6617     public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
6618             @PendingIntent.Flags int flags) {
6619         String packageName = getPackageName();
6620         try {
6621             data.prepareToLeaveProcess(this);
6622             IIntentSender target = ActivityManager.getService().getIntentSenderWithFeature(
6623                     ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, getAttributionTag(),
6624                     mParent == null ? mToken : mParent.mToken, mEmbeddedID, requestCode,
6625                     new Intent[]{data}, null, flags, null, getUserId());
6626             return target != null ? new PendingIntent(target) : null;
6627         } catch (RemoteException e) {
6628             // Empty
6629         }
6630         return null;
6631     }
6632 
6633     /**
6634      * Change the desired orientation of this activity.  If the activity
6635      * is currently in the foreground or otherwise impacting the screen
6636      * orientation, the screen will immediately be changed (possibly causing
6637      * the activity to be restarted). Otherwise, this will be used the next
6638      * time the activity is visible.
6639      *
6640      * @param requestedOrientation An orientation constant as used in
6641      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6642      */
setRequestedOrientation(@ctivityInfo.ScreenOrientation int requestedOrientation)6643     public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
6644         if (mParent == null) {
6645             try {
6646                 ActivityTaskManager.getService().setRequestedOrientation(
6647                         mToken, requestedOrientation);
6648             } catch (RemoteException e) {
6649                 // Empty
6650             }
6651         } else {
6652             mParent.setRequestedOrientation(requestedOrientation);
6653         }
6654     }
6655 
6656     /**
6657      * Return the current requested orientation of the activity.  This will
6658      * either be the orientation requested in its component's manifest, or
6659      * the last requested orientation given to
6660      * {@link #setRequestedOrientation(int)}.
6661      *
6662      * @return Returns an orientation constant as used in
6663      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6664      */
6665     @ActivityInfo.ScreenOrientation
getRequestedOrientation()6666     public int getRequestedOrientation() {
6667         if (mParent == null) {
6668             try {
6669                 return ActivityTaskManager.getService()
6670                         .getRequestedOrientation(mToken);
6671             } catch (RemoteException e) {
6672                 // Empty
6673             }
6674         } else {
6675             return mParent.getRequestedOrientation();
6676         }
6677         return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
6678     }
6679 
6680     /**
6681      * Return the identifier of the task this activity is in.  This identifier
6682      * will remain the same for the lifetime of the activity.
6683      *
6684      * @return Task identifier, an opaque integer.
6685      */
getTaskId()6686     public int getTaskId() {
6687         try {
6688             return ActivityTaskManager.getService().getTaskForActivity(mToken, false);
6689         } catch (RemoteException e) {
6690             return -1;
6691         }
6692     }
6693 
6694     /**
6695      * Return whether this activity is the root of a task.  The root is the
6696      * first activity in a task.
6697      *
6698      * @return True if this is the root activity, else false.
6699      */
isTaskRoot()6700     public boolean isTaskRoot() {
6701         return mWindowControllerCallback.isTaskRoot();
6702     }
6703 
6704     /**
6705      * Move the task containing this activity to the back of the activity
6706      * stack.  The activity's order within the task is unchanged.
6707      *
6708      * @param nonRoot If false then this only works if the activity is the root
6709      *                of a task; if true it will work for any activity in
6710      *                a task.
6711      *
6712      * @return If the task was moved (or it was already at the
6713      *         back) true is returned, else false.
6714      */
moveTaskToBack(boolean nonRoot)6715     public boolean moveTaskToBack(boolean nonRoot) {
6716         try {
6717             return ActivityTaskManager.getService().moveActivityTaskToBack(mToken, nonRoot);
6718         } catch (RemoteException e) {
6719             // Empty
6720         }
6721         return false;
6722     }
6723 
6724     /**
6725      * Returns class name for this activity with the package prefix removed.
6726      * This is the default name used to read and write settings.
6727      *
6728      * @return The local class name.
6729      */
6730     @NonNull
getLocalClassName()6731     public String getLocalClassName() {
6732         final String pkg = getPackageName();
6733         final String cls = mComponent.getClassName();
6734         int packageLen = pkg.length();
6735         if (!cls.startsWith(pkg) || cls.length() <= packageLen
6736                 || cls.charAt(packageLen) != '.') {
6737             return cls;
6738         }
6739         return cls.substring(packageLen+1);
6740     }
6741 
6742     /**
6743      * Returns the complete component name of this activity.
6744      *
6745      * @return Returns the complete component name for this activity
6746      */
getComponentName()6747     public ComponentName getComponentName() {
6748         return mComponent;
6749     }
6750 
6751     /** @hide */
6752     @Override
autofillClientGetComponentName()6753     public final ComponentName autofillClientGetComponentName() {
6754         return getComponentName();
6755     }
6756 
6757     /** @hide */
6758     @Override
contentCaptureClientGetComponentName()6759     public final ComponentName contentCaptureClientGetComponentName() {
6760         return getComponentName();
6761     }
6762 
6763     /**
6764      * Retrieve a {@link SharedPreferences} object for accessing preferences
6765      * that are private to this activity.  This simply calls the underlying
6766      * {@link #getSharedPreferences(String, int)} method by passing in this activity's
6767      * class name as the preferences name.
6768      *
6769      * @param mode Operating mode.  Use {@link #MODE_PRIVATE} for the default
6770      *             operation.
6771      *
6772      * @return Returns the single SharedPreferences instance that can be used
6773      *         to retrieve and modify the preference values.
6774      */
getPreferences(@ontext.PreferencesMode int mode)6775     public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
6776         return getSharedPreferences(getLocalClassName(), mode);
6777     }
6778 
ensureSearchManager()6779     private void ensureSearchManager() {
6780         if (mSearchManager != null) {
6781             return;
6782         }
6783 
6784         try {
6785             mSearchManager = new SearchManager(this, null);
6786         } catch (ServiceNotFoundException e) {
6787             throw new IllegalStateException(e);
6788         }
6789     }
6790 
6791     @Override
getSystemService(@erviceName @onNull String name)6792     public Object getSystemService(@ServiceName @NonNull String name) {
6793         if (getBaseContext() == null) {
6794             throw new IllegalStateException(
6795                     "System services not available to Activities before onCreate()");
6796         }
6797 
6798         if (WINDOW_SERVICE.equals(name)) {
6799             return mWindowManager;
6800         } else if (SEARCH_SERVICE.equals(name)) {
6801             ensureSearchManager();
6802             return mSearchManager;
6803         }
6804         return super.getSystemService(name);
6805     }
6806 
6807     /**
6808      * Change the title associated with this activity.  If this is a
6809      * top-level activity, the title for its window will change.  If it
6810      * is an embedded activity, the parent can do whatever it wants
6811      * with it.
6812      */
setTitle(CharSequence title)6813     public void setTitle(CharSequence title) {
6814         mTitle = title;
6815         onTitleChanged(title, mTitleColor);
6816 
6817         if (mParent != null) {
6818             mParent.onChildTitleChanged(this, title);
6819         }
6820     }
6821 
6822     /**
6823      * Change the title associated with this activity.  If this is a
6824      * top-level activity, the title for its window will change.  If it
6825      * is an embedded activity, the parent can do whatever it wants
6826      * with it.
6827      */
setTitle(int titleId)6828     public void setTitle(int titleId) {
6829         setTitle(getText(titleId));
6830     }
6831 
6832     /**
6833      * Change the color of the title associated with this activity.
6834      * <p>
6835      * This method is deprecated starting in API Level 11 and replaced by action
6836      * bar styles. For information on styling the Action Bar, read the <a
6837      * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
6838      * guide.
6839      *
6840      * @deprecated Use action bar styles instead.
6841      */
6842     @Deprecated
setTitleColor(int textColor)6843     public void setTitleColor(int textColor) {
6844         mTitleColor = textColor;
6845         onTitleChanged(mTitle, textColor);
6846     }
6847 
getTitle()6848     public final CharSequence getTitle() {
6849         return mTitle;
6850     }
6851 
getTitleColor()6852     public final int getTitleColor() {
6853         return mTitleColor;
6854     }
6855 
onTitleChanged(CharSequence title, int color)6856     protected void onTitleChanged(CharSequence title, int color) {
6857         if (mTitleReady) {
6858             final Window win = getWindow();
6859             if (win != null) {
6860                 win.setTitle(title);
6861                 if (color != 0) {
6862                     win.setTitleColor(color);
6863                 }
6864             }
6865             if (mActionBar != null) {
6866                 mActionBar.setWindowTitle(title);
6867             }
6868         }
6869     }
6870 
onChildTitleChanged(Activity childActivity, CharSequence title)6871     protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
6872     }
6873 
6874     /**
6875      * Sets information describing the task with this activity for presentation inside the Recents
6876      * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
6877      * are traversed in order from the topmost activity to the bottommost. The traversal continues
6878      * for each property until a suitable value is found. For each task the taskDescription will be
6879      * returned in {@link android.app.ActivityManager.TaskDescription}.
6880      *
6881      * @see ActivityManager#getRecentTasks
6882      * @see android.app.ActivityManager.TaskDescription
6883      *
6884      * @param taskDescription The TaskDescription properties that describe the task with this activity
6885      */
setTaskDescription(ActivityManager.TaskDescription taskDescription)6886     public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
6887         if (mTaskDescription != taskDescription) {
6888             mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
6889             // Scale the icon down to something reasonable if it is provided
6890             if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
6891                 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
6892                 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
6893                         true);
6894                 mTaskDescription.setIcon(Icon.createWithBitmap(icon));
6895             }
6896         }
6897         try {
6898             ActivityTaskManager.getService().setTaskDescription(mToken, mTaskDescription);
6899         } catch (RemoteException e) {
6900         }
6901     }
6902 
6903     /**
6904      * Sets the visibility of the progress bar in the title.
6905      * <p>
6906      * In order for the progress bar to be shown, the feature must be requested
6907      * via {@link #requestWindowFeature(int)}.
6908      *
6909      * @param visible Whether to show the progress bars in the title.
6910      * @deprecated No longer supported starting in API 21.
6911      */
6912     @Deprecated
setProgressBarVisibility(boolean visible)6913     public final void setProgressBarVisibility(boolean visible) {
6914         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
6915             Window.PROGRESS_VISIBILITY_OFF);
6916     }
6917 
6918     /**
6919      * Sets the visibility of the indeterminate progress bar in the title.
6920      * <p>
6921      * In order for the progress bar to be shown, the feature must be requested
6922      * via {@link #requestWindowFeature(int)}.
6923      *
6924      * @param visible Whether to show the progress bars in the title.
6925      * @deprecated No longer supported starting in API 21.
6926      */
6927     @Deprecated
setProgressBarIndeterminateVisibility(boolean visible)6928     public final void setProgressBarIndeterminateVisibility(boolean visible) {
6929         getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
6930                 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
6931     }
6932 
6933     /**
6934      * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
6935      * is always indeterminate).
6936      * <p>
6937      * In order for the progress bar to be shown, the feature must be requested
6938      * via {@link #requestWindowFeature(int)}.
6939      *
6940      * @param indeterminate Whether the horizontal progress bar should be indeterminate.
6941      * @deprecated No longer supported starting in API 21.
6942      */
6943     @Deprecated
setProgressBarIndeterminate(boolean indeterminate)6944     public final void setProgressBarIndeterminate(boolean indeterminate) {
6945         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6946                 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
6947                         : Window.PROGRESS_INDETERMINATE_OFF);
6948     }
6949 
6950     /**
6951      * Sets the progress for the progress bars in the title.
6952      * <p>
6953      * In order for the progress bar to be shown, the feature must be requested
6954      * via {@link #requestWindowFeature(int)}.
6955      *
6956      * @param progress The progress for the progress bar. Valid ranges are from
6957      *            0 to 10000 (both inclusive). If 10000 is given, the progress
6958      *            bar will be completely filled and will fade out.
6959      * @deprecated No longer supported starting in API 21.
6960      */
6961     @Deprecated
setProgress(int progress)6962     public final void setProgress(int progress) {
6963         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
6964     }
6965 
6966     /**
6967      * Sets the secondary progress for the progress bar in the title. This
6968      * progress is drawn between the primary progress (set via
6969      * {@link #setProgress(int)} and the background. It can be ideal for media
6970      * scenarios such as showing the buffering progress while the default
6971      * progress shows the play progress.
6972      * <p>
6973      * In order for the progress bar to be shown, the feature must be requested
6974      * via {@link #requestWindowFeature(int)}.
6975      *
6976      * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
6977      *            0 to 10000 (both inclusive).
6978      * @deprecated No longer supported starting in API 21.
6979      */
6980     @Deprecated
setSecondaryProgress(int secondaryProgress)6981     public final void setSecondaryProgress(int secondaryProgress) {
6982         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6983                 secondaryProgress + Window.PROGRESS_SECONDARY_START);
6984     }
6985 
6986     /**
6987      * Suggests an audio stream whose volume should be changed by the hardware
6988      * volume controls.
6989      * <p>
6990      * The suggested audio stream will be tied to the window of this Activity.
6991      * Volume requests which are received while the Activity is in the
6992      * foreground will affect this stream.
6993      * <p>
6994      * It is not guaranteed that the hardware volume controls will always change
6995      * this stream's volume (for example, if a call is in progress, its stream's
6996      * volume may be changed instead). To reset back to the default, use
6997      * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
6998      *
6999      * @param streamType The type of the audio stream whose volume should be
7000      *            changed by the hardware volume controls.
7001      */
setVolumeControlStream(int streamType)7002     public final void setVolumeControlStream(int streamType) {
7003         getWindow().setVolumeControlStream(streamType);
7004     }
7005 
7006     /**
7007      * Gets the suggested audio stream whose volume should be changed by the
7008      * hardware volume controls.
7009      *
7010      * @return The suggested audio stream type whose volume should be changed by
7011      *         the hardware volume controls.
7012      * @see #setVolumeControlStream(int)
7013      */
getVolumeControlStream()7014     public final int getVolumeControlStream() {
7015         return getWindow().getVolumeControlStream();
7016     }
7017 
7018     /**
7019      * Sets a {@link MediaController} to send media keys and volume changes to.
7020      * <p>
7021      * The controller will be tied to the window of this Activity. Media key and
7022      * volume events which are received while the Activity is in the foreground
7023      * will be forwarded to the controller and used to invoke transport controls
7024      * or adjust the volume. This may be used instead of or in addition to
7025      * {@link #setVolumeControlStream} to affect a specific session instead of a
7026      * specific stream.
7027      * <p>
7028      * It is not guaranteed that the hardware volume controls will always change
7029      * this session's volume (for example, if a call is in progress, its
7030      * stream's volume may be changed instead). To reset back to the default use
7031      * null as the controller.
7032      *
7033      * @param controller The controller for the session which should receive
7034      *            media keys and volume changes.
7035      */
setMediaController(MediaController controller)7036     public final void setMediaController(MediaController controller) {
7037         getWindow().setMediaController(controller);
7038     }
7039 
7040     /**
7041      * Gets the controller which should be receiving media key and volume events
7042      * while this activity is in the foreground.
7043      *
7044      * @return The controller which should receive events.
7045      * @see #setMediaController(android.media.session.MediaController)
7046      */
getMediaController()7047     public final MediaController getMediaController() {
7048         return getWindow().getMediaController();
7049     }
7050 
7051     /**
7052      * Runs the specified action on the UI thread. If the current thread is the UI
7053      * thread, then the action is executed immediately. If the current thread is
7054      * not the UI thread, the action is posted to the event queue of the UI thread.
7055      *
7056      * @param action the action to run on the UI thread
7057      */
runOnUiThread(Runnable action)7058     public final void runOnUiThread(Runnable action) {
7059         if (Thread.currentThread() != mUiThread) {
7060             mHandler.post(action);
7061         } else {
7062             action.run();
7063         }
7064     }
7065 
7066     /** @hide */
7067     @Override
autofillClientRunOnUiThread(Runnable action)7068     public final void autofillClientRunOnUiThread(Runnable action) {
7069         runOnUiThread(action);
7070     }
7071 
7072     /**
7073      * Standard implementation of
7074      * {@link android.view.LayoutInflater.Factory#onCreateView} used when
7075      * inflating with the LayoutInflater returned by {@link #getSystemService}.
7076      * This implementation does nothing and is for
7077      * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps.  Newer apps
7078      * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
7079      *
7080      * @see android.view.LayoutInflater#createView
7081      * @see android.view.Window#getLayoutInflater
7082      */
7083     @Nullable
onCreateView(@onNull String name, @NonNull Context context, @NonNull AttributeSet attrs)7084     public View onCreateView(@NonNull String name, @NonNull Context context,
7085             @NonNull AttributeSet attrs) {
7086         return null;
7087     }
7088 
7089     /**
7090      * Standard implementation of
7091      * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
7092      * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
7093      * This implementation handles <fragment> tags to embed fragments inside
7094      * of the activity.
7095      *
7096      * @see android.view.LayoutInflater#createView
7097      * @see android.view.Window#getLayoutInflater
7098      */
7099     @Nullable
onCreateView(@ullable View parent, @NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs)7100     public View onCreateView(@Nullable View parent, @NonNull String name,
7101             @NonNull Context context, @NonNull AttributeSet attrs) {
7102         if (!"fragment".equals(name)) {
7103             return onCreateView(name, context, attrs);
7104         }
7105 
7106         return mFragments.onCreateView(parent, name, context, attrs);
7107     }
7108 
7109     /**
7110      * Print the Activity's state into the given stream.  This gets invoked if
7111      * you run "adb shell dumpsys activity &lt;activity_component_name&gt;".
7112      *
7113      * @param prefix Desired prefix to prepend at each line of output.
7114      * @param fd The raw file descriptor that the dump is being sent to.
7115      * @param writer The PrintWriter to which you should dump your state.  This will be
7116      * closed for you after you return.
7117      * @param args additional arguments to the dump request.
7118      */
dump(@onNull String prefix, @Nullable FileDescriptor fd, @NonNull PrintWriter writer, @Nullable String[] args)7119     public void dump(@NonNull String prefix, @Nullable FileDescriptor fd,
7120             @NonNull PrintWriter writer, @Nullable String[] args) {
7121         dumpInner(prefix, fd, writer, args);
7122     }
7123 
dumpInner(@onNull String prefix, @Nullable FileDescriptor fd, @NonNull PrintWriter writer, @Nullable String[] args)7124     void dumpInner(@NonNull String prefix, @Nullable FileDescriptor fd,
7125             @NonNull PrintWriter writer, @Nullable String[] args) {
7126         if (args != null && args.length > 0) {
7127             // Handle special cases
7128             switch (args[0]) {
7129                 case "--autofill":
7130                     dumpAutofillManager(prefix, writer);
7131                     return;
7132                 case "--contentcapture":
7133                     dumpContentCaptureManager(prefix, writer);
7134                     return;
7135             }
7136         }
7137         writer.print(prefix); writer.print("Local Activity ");
7138                 writer.print(Integer.toHexString(System.identityHashCode(this)));
7139                 writer.println(" State:");
7140         String innerPrefix = prefix + "  ";
7141         writer.print(innerPrefix); writer.print("mResumed=");
7142                 writer.print(mResumed); writer.print(" mStopped=");
7143                 writer.print(mStopped); writer.print(" mFinished=");
7144                 writer.println(mFinished);
7145         writer.print(innerPrefix); writer.print("mIsInMultiWindowMode=");
7146                 writer.print(mIsInMultiWindowMode);
7147                 writer.print(" mIsInPictureInPictureMode=");
7148                 writer.println(mIsInPictureInPictureMode);
7149         writer.print(innerPrefix); writer.print("mChangingConfigurations=");
7150                 writer.println(mChangingConfigurations);
7151         writer.print(innerPrefix); writer.print("mCurrentConfig=");
7152                 writer.println(mCurrentConfig);
7153         if (getResources().hasOverrideDisplayAdjustments()) {
7154             writer.print(innerPrefix);
7155             writer.print("FixedRotationAdjustments=");
7156             writer.println(getResources().getDisplayAdjustments().getFixedRotationAdjustments());
7157         }
7158 
7159         mFragments.dumpLoaders(innerPrefix, fd, writer, args);
7160         mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
7161         if (mVoiceInteractor != null) {
7162             mVoiceInteractor.dump(innerPrefix, fd, writer, args);
7163         }
7164 
7165         if (getWindow() != null &&
7166                 getWindow().peekDecorView() != null &&
7167                 getWindow().peekDecorView().getViewRootImpl() != null) {
7168             getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
7169         }
7170 
7171         mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
7172 
7173         dumpAutofillManager(prefix, writer);
7174         dumpContentCaptureManager(prefix, writer);
7175 
7176         ResourcesManager.getInstance().dump(prefix, writer);
7177     }
7178 
dumpAutofillManager(String prefix, PrintWriter writer)7179     void dumpAutofillManager(String prefix, PrintWriter writer) {
7180         final AutofillManager afm = getAutofillManager();
7181         if (afm != null) {
7182             afm.dump(prefix, writer);
7183             writer.print(prefix); writer.print("Autofill Compat Mode: ");
7184             writer.println(isAutofillCompatibilityEnabled());
7185         } else {
7186             writer.print(prefix); writer.println("No AutofillManager");
7187         }
7188     }
7189 
dumpContentCaptureManager(String prefix, PrintWriter writer)7190     void dumpContentCaptureManager(String prefix, PrintWriter writer) {
7191         final ContentCaptureManager cm = getContentCaptureManager();
7192         if (cm != null) {
7193             cm.dump(prefix, writer);
7194         } else {
7195             writer.print(prefix); writer.println("No ContentCaptureManager");
7196         }
7197     }
7198 
7199     /**
7200      * Bit indicating that this activity is "immersive" and should not be
7201      * interrupted by notifications if possible.
7202      *
7203      * This value is initially set by the manifest property
7204      * <code>android:immersive</code> but may be changed at runtime by
7205      * {@link #setImmersive}.
7206      *
7207      * @see #setImmersive(boolean)
7208      * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7209      */
isImmersive()7210     public boolean isImmersive() {
7211         try {
7212             return ActivityTaskManager.getService().isImmersive(mToken);
7213         } catch (RemoteException e) {
7214             return false;
7215         }
7216     }
7217 
7218     /**
7219      * Indication of whether this is the highest level activity in this task. Can be used to
7220      * determine whether an activity launched by this activity was placed in the same task or
7221      * another task.
7222      *
7223      * @return true if this is the topmost, non-finishing activity in its task.
7224      */
isTopOfTask()7225     final boolean isTopOfTask() {
7226         if (mToken == null || mWindow == null) {
7227             return false;
7228         }
7229         try {
7230             return ActivityTaskManager.getService().isTopOfTask(getActivityToken());
7231         } catch (RemoteException e) {
7232             return false;
7233         }
7234     }
7235 
7236     /**
7237      * Convert an activity, which particularly with {@link android.R.attr#windowIsTranslucent} or
7238      * {@link android.R.attr#windowIsFloating} attribute, to a fullscreen opaque activity, or
7239      * convert it from opaque back to translucent.
7240      *
7241      * @param translucent {@code true} convert from opaque to translucent.
7242      *                    {@code false} convert from translucent to opaque.
7243      * @return The result of setting translucency. Return {@code true} if set successfully,
7244      *         {@code false} otherwise.
7245      */
setTranslucent(boolean translucent)7246     public boolean setTranslucent(boolean translucent) {
7247         if (translucent) {
7248             return convertToTranslucent(null /* callback */, null /* options */);
7249         } else {
7250             return convertFromTranslucentInternal();
7251         }
7252     }
7253 
7254     /**
7255      * Convert an activity to a fullscreen opaque activity.
7256      * <p>
7257      * Call this whenever the background of a translucent activity has changed to become opaque.
7258      * Doing so will allow the {@link android.view.Surface} of the activity behind to be released.
7259      *
7260      * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7261      * ActivityOptions)
7262      * @see TranslucentConversionListener
7263      *
7264      * @hide
7265      */
7266     @SystemApi
convertFromTranslucent()7267     public void convertFromTranslucent() {
7268         convertFromTranslucentInternal();
7269     }
7270 
convertFromTranslucentInternal()7271     private boolean convertFromTranslucentInternal() {
7272         try {
7273             mTranslucentCallback = null;
7274             if (ActivityTaskManager.getService().convertFromTranslucent(mToken)) {
7275                 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
7276                 return true;
7277             }
7278         } catch (RemoteException e) {
7279             // pass
7280         }
7281         return false;
7282     }
7283 
7284     /**
7285      * Convert an activity to a translucent activity.
7286      * <p>
7287      * Calling this allows the activity behind this one to be seen again. Once all such activities
7288      * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
7289      * be called indicating that it is safe to make this activity translucent again. Until
7290      * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
7291      * behind the frontmost activity will be indeterminate.
7292      *
7293      * @param callback the method to call when all visible activities behind this one have been
7294      * drawn and it is safe to make this activity translucent again.
7295      * @param options activity options delivered to the activity below this one. The options
7296      * are retrieved using {@link #getActivityOptions}.
7297      * @return <code>true</code> if Window was opaque and will become translucent or
7298      * <code>false</code> if window was translucent and no change needed to be made.
7299      *
7300      * @see #convertFromTranslucent()
7301      * @see TranslucentConversionListener
7302      *
7303      * @hide
7304      */
7305     @SystemApi
convertToTranslucent(TranslucentConversionListener callback, ActivityOptions options)7306     public boolean convertToTranslucent(TranslucentConversionListener callback,
7307             ActivityOptions options) {
7308         boolean drawComplete;
7309         try {
7310             mTranslucentCallback = callback;
7311             mChangeCanvasToTranslucent = ActivityTaskManager.getService().convertToTranslucent(
7312                     mToken, options == null ? null : options.toBundle());
7313             WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
7314             drawComplete = true;
7315         } catch (RemoteException e) {
7316             // Make callback return as though it timed out.
7317             mChangeCanvasToTranslucent = false;
7318             drawComplete = false;
7319         }
7320         if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
7321             // Window is already translucent.
7322             mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
7323         }
7324         return mChangeCanvasToTranslucent;
7325     }
7326 
7327     /** @hide */
onTranslucentConversionComplete(boolean drawComplete)7328     void onTranslucentConversionComplete(boolean drawComplete) {
7329         if (mTranslucentCallback != null) {
7330             mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
7331             mTranslucentCallback = null;
7332         }
7333         if (mChangeCanvasToTranslucent) {
7334             WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
7335         }
7336     }
7337 
7338     /** @hide */
onNewActivityOptions(ActivityOptions options)7339     public void onNewActivityOptions(ActivityOptions options) {
7340         mActivityTransitionState.setEnterActivityOptions(this, options);
7341         if (!mStopped) {
7342             mActivityTransitionState.enterReady(this);
7343         }
7344     }
7345 
7346     /**
7347      * Retrieve the ActivityOptions passed in from the launching activity or passed back
7348      * from an activity launched by this activity in its call to {@link
7349      * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
7350      *
7351      * @return The ActivityOptions passed to {@link #convertToTranslucent}.
7352      * @hide
7353      */
7354     @UnsupportedAppUsage
getActivityOptions()7355     ActivityOptions getActivityOptions() {
7356         try {
7357             return ActivityOptions.fromBundle(
7358                     ActivityTaskManager.getService().getActivityOptions(mToken));
7359         } catch (RemoteException e) {
7360         }
7361         return null;
7362     }
7363 
7364     /**
7365      * Activities that want to remain visible behind a translucent activity above them must call
7366      * this method anytime between the start of {@link #onResume()} and the return from
7367      * {@link #onPause()}. If this call is successful then the activity will remain visible after
7368      * {@link #onPause()} is called, and is allowed to continue playing media in the background.
7369      *
7370      * <p>The actions of this call are reset each time that this activity is brought to the
7371      * front. That is, every time {@link #onResume()} is called the activity will be assumed
7372      * to not have requested visible behind. Therefore, if you want this activity to continue to
7373      * be visible in the background you must call this method again.
7374      *
7375      * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
7376      * for dialog and translucent activities.
7377      *
7378      * <p>Under all circumstances, the activity must stop playing and release resources prior to or
7379      * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
7380      *
7381      * <p>False will be returned any time this method is called between the return of onPause and
7382      *      the next call to onResume.
7383      *
7384      * @deprecated This method's functionality is no longer supported as of
7385      *             {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7386      *
7387      * @param visible true to notify the system that the activity wishes to be visible behind other
7388      *                translucent activities, false to indicate otherwise. Resources must be
7389      *                released when passing false to this method.
7390      *
7391      * @return the resulting visibiity state. If true the activity will remain visible beyond
7392      *      {@link #onPause()} if the next activity is translucent or not fullscreen. If false
7393      *      then the activity may not count on being visible behind other translucent activities,
7394      *      and must stop any media playback and release resources.
7395      *      Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
7396      *      the return value must be checked.
7397      *
7398      * @see #onVisibleBehindCanceled()
7399      */
7400     @Deprecated
requestVisibleBehind(boolean visible)7401     public boolean requestVisibleBehind(boolean visible) {
7402         return false;
7403     }
7404 
7405     /**
7406      * Called when a translucent activity over this activity is becoming opaque or another
7407      * activity is being launched. Activities that override this method must call
7408      * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
7409      *
7410      * <p>When this method is called the activity has 500 msec to release any resources it may be
7411      * using while visible in the background.
7412      * If the activity has not returned from this method in 500 msec the system will destroy
7413      * the activity and kill the process in order to recover the resources for another
7414      * process. Otherwise {@link #onStop()} will be called following return.
7415      *
7416      * @see #requestVisibleBehind(boolean)
7417      *
7418      * @deprecated This method's functionality is no longer supported as of
7419      * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7420      */
7421     @Deprecated
7422     @CallSuper
onVisibleBehindCanceled()7423     public void onVisibleBehindCanceled() {
7424         mCalled = true;
7425     }
7426 
7427     /**
7428      * Translucent activities may call this to determine if there is an activity below them that
7429      * is currently set to be visible in the background.
7430      *
7431      * @deprecated This method's functionality is no longer supported as of
7432      * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7433      *
7434      * @return true if an activity below is set to visible according to the most recent call to
7435      * {@link #requestVisibleBehind(boolean)}, false otherwise.
7436      *
7437      * @see #requestVisibleBehind(boolean)
7438      * @see #onVisibleBehindCanceled()
7439      * @see #onBackgroundVisibleBehindChanged(boolean)
7440      * @hide
7441      */
7442     @Deprecated
7443     @SystemApi
isBackgroundVisibleBehind()7444     public boolean isBackgroundVisibleBehind() {
7445         return false;
7446     }
7447 
7448     /**
7449      * The topmost foreground activity will receive this call when the background visibility state
7450      * of the activity below it changes.
7451      *
7452      * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
7453      * due to a background activity finishing itself.
7454      *
7455      * @deprecated This method's functionality is no longer supported as of
7456      * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7457      *
7458      * @param visible true if a background activity is visible, false otherwise.
7459      *
7460      * @see #requestVisibleBehind(boolean)
7461      * @see #onVisibleBehindCanceled()
7462      * @hide
7463      */
7464     @Deprecated
7465     @SystemApi
onBackgroundVisibleBehindChanged(boolean visible)7466     public void onBackgroundVisibleBehindChanged(boolean visible) {
7467     }
7468 
7469     /**
7470      * Activities cannot draw during the period that their windows are animating in. In order
7471      * to know when it is safe to begin drawing they can override this method which will be
7472      * called when the entering animation has completed.
7473      */
onEnterAnimationComplete()7474     public void onEnterAnimationComplete() {
7475     }
7476 
7477     /**
7478      * @hide
7479      */
dispatchEnterAnimationComplete()7480     public void dispatchEnterAnimationComplete() {
7481         mEnterAnimationComplete = true;
7482         mInstrumentation.onEnterAnimationComplete();
7483         onEnterAnimationComplete();
7484         if (getWindow() != null && getWindow().getDecorView() != null) {
7485             View decorView = getWindow().getDecorView();
7486             decorView.getViewTreeObserver().dispatchOnEnterAnimationComplete();
7487         }
7488     }
7489 
7490     /**
7491      * Adjust the current immersive mode setting.
7492      *
7493      * Note that changing this value will have no effect on the activity's
7494      * {@link android.content.pm.ActivityInfo} structure; that is, if
7495      * <code>android:immersive</code> is set to <code>true</code>
7496      * in the application's manifest entry for this activity, the {@link
7497      * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
7498      * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7499      * FLAG_IMMERSIVE} bit set.
7500      *
7501      * @see #isImmersive()
7502      * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7503      */
setImmersive(boolean i)7504     public void setImmersive(boolean i) {
7505         try {
7506             ActivityTaskManager.getService().setImmersive(mToken, i);
7507         } catch (RemoteException e) {
7508             // pass
7509         }
7510     }
7511 
7512     /**
7513      * Enable or disable virtual reality (VR) mode for this Activity.
7514      *
7515      * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
7516      * while this Activity has user focus.</p>
7517      *
7518      * <p>It is recommended that applications additionally declare
7519      * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
7520      * transitions when switching between VR activities.</p>
7521      *
7522      * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
7523      * VR mode will not be started.  Developers can handle this case as follows:</p>
7524      *
7525      * <pre>
7526      * String servicePackage = "com.whatever.app";
7527      * String serviceClass = "com.whatever.app.MyVrListenerService";
7528      *
7529      * // Name of the component of the VrListenerService to start.
7530      * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
7531      *
7532      * try {
7533      *    setVrModeEnabled(true, myComponentName);
7534      * } catch (PackageManager.NameNotFoundException e) {
7535      *        List&lt;ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
7536      *        boolean isInstalled = false;
7537      *        for (ApplicationInfo app : installed) {
7538      *            if (app.packageName.equals(servicePackage)) {
7539      *                isInstalled = true;
7540      *                break;
7541      *            }
7542      *        }
7543      *        if (isInstalled) {
7544      *            // Package is installed, but not enabled in Settings.  Let user enable it.
7545      *            startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
7546      *        } else {
7547      *            // Package is not installed.  Send an intent to download this.
7548      *            sentIntentToLaunchAppStore(servicePackage);
7549      *        }
7550      * }
7551      * </pre>
7552      *
7553      * @param enabled {@code true} to enable this mode.
7554      * @param requestedComponent the name of the component to use as a
7555      *        {@link android.service.vr.VrListenerService} while VR mode is enabled.
7556      *
7557      * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
7558      *    to run as a {@link android.service.vr.VrListenerService} is not installed, or has
7559      *    not been enabled in user settings.
7560      *
7561      * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
7562      * @see android.service.vr.VrListenerService
7563      * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
7564      * @see android.R.attr#enableVrMode
7565      */
setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)7566     public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
7567           throws PackageManager.NameNotFoundException {
7568         try {
7569             if (ActivityTaskManager.getService().setVrMode(mToken, enabled, requestedComponent)
7570                     != 0) {
7571                 throw new PackageManager.NameNotFoundException(
7572                         requestedComponent.flattenToString());
7573             }
7574         } catch (RemoteException e) {
7575             // pass
7576         }
7577     }
7578 
7579     /**
7580      * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
7581      *
7582      * @param callback Callback that will manage lifecycle events for this action mode
7583      * @return The ActionMode that was started, or null if it was canceled
7584      *
7585      * @see ActionMode
7586      */
7587     @Nullable
startActionMode(ActionMode.Callback callback)7588     public ActionMode startActionMode(ActionMode.Callback callback) {
7589         return mWindow.getDecorView().startActionMode(callback);
7590     }
7591 
7592     /**
7593      * Start an action mode of the given type.
7594      *
7595      * @param callback Callback that will manage lifecycle events for this action mode
7596      * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
7597      * @return The ActionMode that was started, or null if it was canceled
7598      *
7599      * @see ActionMode
7600      */
7601     @Nullable
startActionMode(ActionMode.Callback callback, int type)7602     public ActionMode startActionMode(ActionMode.Callback callback, int type) {
7603         return mWindow.getDecorView().startActionMode(callback, type);
7604     }
7605 
7606     /**
7607      * Give the Activity a chance to control the UI for an action mode requested
7608      * by the system.
7609      *
7610      * <p>Note: If you are looking for a notification callback that an action mode
7611      * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
7612      *
7613      * @param callback The callback that should control the new action mode
7614      * @return The new action mode, or <code>null</code> if the activity does not want to
7615      *         provide special handling for this action mode. (It will be handled by the system.)
7616      */
7617     @Nullable
7618     @Override
onWindowStartingActionMode(ActionMode.Callback callback)7619     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
7620         // Only Primary ActionModes are represented in the ActionBar.
7621         if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
7622             initWindowDecorActionBar();
7623             if (mActionBar != null) {
7624                 return mActionBar.startActionMode(callback);
7625             }
7626         }
7627         return null;
7628     }
7629 
7630     /**
7631      * {@inheritDoc}
7632      */
7633     @Nullable
7634     @Override
onWindowStartingActionMode(ActionMode.Callback callback, int type)7635     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
7636         try {
7637             mActionModeTypeStarting = type;
7638             return onWindowStartingActionMode(callback);
7639         } finally {
7640             mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
7641         }
7642     }
7643 
7644     /**
7645      * Notifies the Activity that an action mode has been started.
7646      * Activity subclasses overriding this method should call the superclass implementation.
7647      *
7648      * @param mode The new action mode.
7649      */
7650     @CallSuper
7651     @Override
onActionModeStarted(ActionMode mode)7652     public void onActionModeStarted(ActionMode mode) {
7653     }
7654 
7655     /**
7656      * Notifies the activity that an action mode has finished.
7657      * Activity subclasses overriding this method should call the superclass implementation.
7658      *
7659      * @param mode The action mode that just finished.
7660      */
7661     @CallSuper
7662     @Override
onActionModeFinished(ActionMode mode)7663     public void onActionModeFinished(ActionMode mode) {
7664     }
7665 
7666     /**
7667      * Returns true if the app should recreate the task when navigating 'up' from this activity
7668      * by using targetIntent.
7669      *
7670      * <p>If this method returns false the app can trivially call
7671      * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
7672      * up navigation. If this method returns false, the app should synthesize a new task stack
7673      * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
7674      *
7675      * @param targetIntent An intent representing the target destination for up navigation
7676      * @return true if navigating up should recreate a new task stack, false if the same task
7677      *         should be used for the destination
7678      */
shouldUpRecreateTask(Intent targetIntent)7679     public boolean shouldUpRecreateTask(Intent targetIntent) {
7680         try {
7681             PackageManager pm = getPackageManager();
7682             ComponentName cn = targetIntent.getComponent();
7683             if (cn == null) {
7684                 cn = targetIntent.resolveActivity(pm);
7685             }
7686             ActivityInfo info = pm.getActivityInfo(cn, 0);
7687             if (info.taskAffinity == null) {
7688                 return false;
7689             }
7690             return ActivityTaskManager.getService().shouldUpRecreateTask(mToken, info.taskAffinity);
7691         } catch (RemoteException e) {
7692             return false;
7693         } catch (NameNotFoundException e) {
7694             return false;
7695         }
7696     }
7697 
7698     /**
7699      * Navigate from this activity to the activity specified by upIntent, finishing this activity
7700      * in the process. If the activity indicated by upIntent already exists in the task's history,
7701      * this activity and all others before the indicated activity in the history stack will be
7702      * finished.
7703      *
7704      * <p>If the indicated activity does not appear in the history stack, this will finish
7705      * each activity in this task until the root activity of the task is reached, resulting in
7706      * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
7707      * when an activity may be reached by a path not passing through a canonical parent
7708      * activity.</p>
7709      *
7710      * <p>This method should be used when performing up navigation from within the same task
7711      * as the destination. If up navigation should cross tasks in some cases, see
7712      * {@link #shouldUpRecreateTask(Intent)}.</p>
7713      *
7714      * @param upIntent An intent representing the target destination for up navigation
7715      *
7716      * @return true if up navigation successfully reached the activity indicated by upIntent and
7717      *         upIntent was delivered to it. false if an instance of the indicated activity could
7718      *         not be found and this activity was simply finished normally.
7719      */
navigateUpTo(Intent upIntent)7720     public boolean navigateUpTo(Intent upIntent) {
7721         if (mParent == null) {
7722             ComponentName destInfo = upIntent.getComponent();
7723             if (destInfo == null) {
7724                 destInfo = upIntent.resolveActivity(getPackageManager());
7725                 if (destInfo == null) {
7726                     return false;
7727                 }
7728                 upIntent = new Intent(upIntent);
7729                 upIntent.setComponent(destInfo);
7730             }
7731             int resultCode;
7732             Intent resultData;
7733             synchronized (this) {
7734                 resultCode = mResultCode;
7735                 resultData = mResultData;
7736             }
7737             if (resultData != null) {
7738                 resultData.prepareToLeaveProcess(this);
7739             }
7740             try {
7741                 upIntent.prepareToLeaveProcess(this);
7742                 return ActivityTaskManager.getService().navigateUpTo(mToken, upIntent,
7743                         resultCode, resultData);
7744             } catch (RemoteException e) {
7745                 return false;
7746             }
7747         } else {
7748             return mParent.navigateUpToFromChild(this, upIntent);
7749         }
7750     }
7751 
7752     /**
7753      * This is called when a child activity of this one calls its
7754      * {@link #navigateUpTo} method.  The default implementation simply calls
7755      * navigateUpTo(upIntent) on this activity (the parent).
7756      *
7757      * @param child The activity making the call.
7758      * @param upIntent An intent representing the target destination for up navigation
7759      *
7760      * @return true if up navigation successfully reached the activity indicated by upIntent and
7761      *         upIntent was delivered to it. false if an instance of the indicated activity could
7762      *         not be found and this activity was simply finished normally.
7763      * @deprecated Use {@link #navigateUpTo(Intent)} instead.
7764      */
7765     @Deprecated
navigateUpToFromChild(Activity child, Intent upIntent)7766     public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
7767         return navigateUpTo(upIntent);
7768     }
7769 
7770     /**
7771      * Obtain an {@link Intent} that will launch an explicit target activity specified by
7772      * this activity's logical parent. The logical parent is named in the application's manifest
7773      * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
7774      * Activity subclasses may override this method to modify the Intent returned by
7775      * super.getParentActivityIntent() or to implement a different mechanism of retrieving
7776      * the parent intent entirely.
7777      *
7778      * @return a new Intent targeting the defined parent of this activity or null if
7779      *         there is no valid parent.
7780      */
7781     @Nullable
getParentActivityIntent()7782     public Intent getParentActivityIntent() {
7783         final String parentName = mActivityInfo.parentActivityName;
7784         if (TextUtils.isEmpty(parentName)) {
7785             return null;
7786         }
7787 
7788         // If the parent itself has no parent, generate a main activity intent.
7789         final ComponentName target = new ComponentName(this, parentName);
7790         try {
7791             final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
7792             final String parentActivity = parentInfo.parentActivityName;
7793             final Intent parentIntent = parentActivity == null
7794                     ? Intent.makeMainActivity(target)
7795                     : new Intent().setComponent(target);
7796             return parentIntent;
7797         } catch (NameNotFoundException e) {
7798             Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
7799                     "' in manifest");
7800             return null;
7801         }
7802     }
7803 
7804     /**
7805      * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7806      * android.view.View, String)} was used to start an Activity, <var>callback</var>
7807      * will be called to handle shared elements on the <i>launched</i> Activity. This requires
7808      * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
7809      *
7810      * @param callback Used to manipulate shared element transitions on the launched Activity.
7811      */
setEnterSharedElementCallback(SharedElementCallback callback)7812     public void setEnterSharedElementCallback(SharedElementCallback callback) {
7813         if (callback == null) {
7814             callback = SharedElementCallback.NULL_CALLBACK;
7815         }
7816         mEnterTransitionListener = callback;
7817     }
7818 
7819     /**
7820      * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7821      * android.view.View, String)} was used to start an Activity, <var>callback</var>
7822      * will be called to handle shared elements on the <i>launching</i> Activity. Most
7823      * calls will only come when returning from the started Activity.
7824      * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
7825      *
7826      * @param callback Used to manipulate shared element transitions on the launching Activity.
7827      */
setExitSharedElementCallback(SharedElementCallback callback)7828     public void setExitSharedElementCallback(SharedElementCallback callback) {
7829         if (callback == null) {
7830             callback = SharedElementCallback.NULL_CALLBACK;
7831         }
7832         mExitTransitionListener = callback;
7833     }
7834 
7835     /**
7836      * Postpone the entering activity transition when Activity was started with
7837      * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7838      * android.util.Pair[])}.
7839      * <p>This method gives the Activity the ability to delay starting the entering and
7840      * shared element transitions until all data is loaded. Until then, the Activity won't
7841      * draw into its window, leaving the window transparent. This may also cause the
7842      * returning animation to be delayed until data is ready. This method should be
7843      * called in {@link #onCreate(android.os.Bundle)} or in
7844      * {@link #onActivityReenter(int, android.content.Intent)}.
7845      * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
7846      * start the transitions. If the Activity did not use
7847      * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7848      * android.util.Pair[])}, then this method does nothing.</p>
7849      */
postponeEnterTransition()7850     public void postponeEnterTransition() {
7851         mActivityTransitionState.postponeEnterTransition();
7852     }
7853 
7854     /**
7855      * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
7856      * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
7857      * to have your Activity start drawing.
7858      */
startPostponedEnterTransition()7859     public void startPostponedEnterTransition() {
7860         mActivityTransitionState.startPostponedEnterTransition();
7861     }
7862 
7863     /**
7864      * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
7865      * access permissions for content URIs associated with the {@link DragEvent}.
7866      * @param event Drag event
7867      * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
7868      * Null if no content URIs are associated with the event or if permissions could not be granted.
7869      */
requestDragAndDropPermissions(DragEvent event)7870     public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
7871         DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
7872         if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
7873             return dragAndDropPermissions;
7874         }
7875         return null;
7876     }
7877 
7878     // ------------------ Internal API ------------------
7879 
7880     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
setParent(Activity parent)7881     final void setParent(Activity parent) {
7882         mParent = parent;
7883     }
7884 
7885     @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)7886     final void attach(Context context, ActivityThread aThread,
7887             Instrumentation instr, IBinder token, int ident,
7888             Application application, Intent intent, ActivityInfo info,
7889             CharSequence title, Activity parent, String id,
7890             NonConfigurationInstances lastNonConfigurationInstances,
7891             Configuration config, String referrer, IVoiceInteractor voiceInteractor,
7892             Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
7893         attachBaseContext(context);
7894 
7895         mFragments.attachHost(null /*parent*/);
7896 
7897         mWindow = new PhoneWindow(this, window, activityConfigCallback);
7898         mWindow.setWindowControllerCallback(mWindowControllerCallback);
7899         mWindow.setCallback(this);
7900         mWindow.setOnWindowDismissedCallback(this);
7901         mWindow.getLayoutInflater().setPrivateFactory(this);
7902         if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
7903             mWindow.setSoftInputMode(info.softInputMode);
7904         }
7905         if (info.uiOptions != 0) {
7906             mWindow.setUiOptions(info.uiOptions);
7907         }
7908         mUiThread = Thread.currentThread();
7909 
7910         mMainThread = aThread;
7911         mInstrumentation = instr;
7912         mToken = token;
7913         mAssistToken = assistToken;
7914         mIdent = ident;
7915         mApplication = application;
7916         mIntent = intent;
7917         mReferrer = referrer;
7918         mComponent = intent.getComponent();
7919         mActivityInfo = info;
7920         mTitle = title;
7921         mParent = parent;
7922         mEmbeddedID = id;
7923         mLastNonConfigurationInstances = lastNonConfigurationInstances;
7924         if (voiceInteractor != null) {
7925             if (lastNonConfigurationInstances != null) {
7926                 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
7927             } else {
7928                 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
7929                         Looper.myLooper());
7930             }
7931         }
7932 
7933         mWindow.setWindowManager(
7934                 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
7935                 mToken, mComponent.flattenToString(),
7936                 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
7937         if (mParent != null) {
7938             mWindow.setContainer(mParent.getWindow());
7939         }
7940         mWindowManager = mWindow.getWindowManager();
7941         mCurrentConfig = config;
7942 
7943         mWindow.setColorMode(info.colorMode);
7944         mWindow.setPreferMinimalPostProcessing(
7945                 (info.flags & ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING) != 0);
7946 
7947         setAutofillOptions(application.getAutofillOptions());
7948         setContentCaptureOptions(application.getContentCaptureOptions());
7949     }
7950 
enableAutofillCompatibilityIfNeeded()7951     private void enableAutofillCompatibilityIfNeeded() {
7952         if (isAutofillCompatibilityEnabled()) {
7953             final AutofillManager afm = getSystemService(AutofillManager.class);
7954             if (afm != null) {
7955                 afm.enableCompatibilityMode();
7956             }
7957         }
7958     }
7959 
7960     /** @hide */
7961     @UnsupportedAppUsage
getActivityToken()7962     public final IBinder getActivityToken() {
7963         return mParent != null ? mParent.getActivityToken() : mToken;
7964     }
7965 
7966     /** @hide */
getAssistToken()7967     public final IBinder getAssistToken() {
7968         return mParent != null ? mParent.getAssistToken() : mAssistToken;
7969     }
7970 
7971     /** @hide */
7972     @VisibleForTesting
getActivityThread()7973     public final ActivityThread getActivityThread() {
7974         return mMainThread;
7975     }
7976 
performCreate(Bundle icicle)7977     final void performCreate(Bundle icicle) {
7978         performCreate(icicle, null);
7979     }
7980 
7981     @UnsupportedAppUsage
performCreate(Bundle icicle, PersistableBundle persistentState)7982     final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7983         dispatchActivityPreCreated(icicle);
7984         mCanEnterPictureInPicture = true;
7985         // initialize mIsInMultiWindowMode and mIsInPictureInPictureMode before onCreate
7986         final int windowingMode = getResources().getConfiguration().windowConfiguration
7987                 .getWindowingMode();
7988         mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
7989         mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
7990         restoreHasCurrentPermissionRequest(icicle);
7991         if (persistentState != null) {
7992             onCreate(icicle, persistentState);
7993         } else {
7994             onCreate(icicle);
7995         }
7996         EventLogTags.writeWmOnCreateCalled(mIdent, getComponentName().getClassName(),
7997                 "performCreate");
7998         mActivityTransitionState.readState(icicle);
7999 
8000         mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
8001                 com.android.internal.R.styleable.Window_windowNoDisplay, false);
8002         mFragments.dispatchActivityCreated();
8003         mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
8004         dispatchActivityPostCreated(icicle);
8005     }
8006 
performNewIntent(@onNull Intent intent)8007     final void performNewIntent(@NonNull Intent intent) {
8008         mCanEnterPictureInPicture = true;
8009         onNewIntent(intent);
8010     }
8011 
performStart(String reason)8012     final void performStart(String reason) {
8013         dispatchActivityPreStarted();
8014         mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
8015         mFragments.noteStateNotSaved();
8016         mCalled = false;
8017         mFragments.execPendingActions();
8018         mInstrumentation.callActivityOnStart(this);
8019         EventLogTags.writeWmOnStartCalled(mIdent, getComponentName().getClassName(), reason);
8020 
8021         if (!mCalled) {
8022             throw new SuperNotCalledException(
8023                 "Activity " + mComponent.toShortString() +
8024                 " did not call through to super.onStart()");
8025         }
8026         mFragments.dispatchStart();
8027         mFragments.reportLoaderStart();
8028 
8029         // Warn app developers if the dynamic linker logged anything during startup.
8030         boolean isAppDebuggable =
8031                 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8032         if (isAppDebuggable) {
8033             String dlwarning = getDlWarning();
8034             if (dlwarning != null) {
8035                 String appName = getApplicationInfo().loadLabel(getPackageManager())
8036                         .toString();
8037                 String warning = "Detected problems with app native libraries\n" +
8038                                  "(please consult log for detail):\n" + dlwarning;
8039                 if (isAppDebuggable) {
8040                       new AlertDialog.Builder(this).
8041                           setTitle(appName).
8042                           setMessage(warning).
8043                           setPositiveButton(android.R.string.ok, null).
8044                           setCancelable(false).
8045                           show();
8046                 } else {
8047                     Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
8048                 }
8049             }
8050         }
8051 
8052         GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
8053 
8054         mActivityTransitionState.enterReady(this);
8055         dispatchActivityPostStarted();
8056     }
8057 
8058     /**
8059      * Restart the activity.
8060      * @param start Indicates whether the activity should also be started after restart.
8061      *              The option to not start immediately is needed in case a transaction with
8062      *              multiple lifecycle transitions is in progress.
8063      */
performRestart(boolean start, String reason)8064     final void performRestart(boolean start, String reason) {
8065         mCanEnterPictureInPicture = true;
8066         mFragments.noteStateNotSaved();
8067 
8068         if (mToken != null && mParent == null) {
8069             // No need to check mStopped, the roots will check if they were actually stopped.
8070             WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
8071         }
8072 
8073         if (mStopped) {
8074             mStopped = false;
8075 
8076             synchronized (mManagedCursors) {
8077                 final int N = mManagedCursors.size();
8078                 for (int i=0; i<N; i++) {
8079                     ManagedCursor mc = mManagedCursors.get(i);
8080                     if (mc.mReleased || mc.mUpdated) {
8081                         if (!mc.mCursor.requery()) {
8082                             if (getApplicationInfo().targetSdkVersion
8083                                     >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
8084                                 throw new IllegalStateException(
8085                                         "trying to requery an already closed cursor  "
8086                                         + mc.mCursor);
8087                             }
8088                         }
8089                         mc.mReleased = false;
8090                         mc.mUpdated = false;
8091                     }
8092                 }
8093             }
8094 
8095             mCalled = false;
8096             mInstrumentation.callActivityOnRestart(this);
8097             EventLogTags.writeWmOnRestartCalled(mIdent, getComponentName().getClassName(), reason);
8098             if (!mCalled) {
8099                 throw new SuperNotCalledException(
8100                     "Activity " + mComponent.toShortString() +
8101                     " did not call through to super.onRestart()");
8102             }
8103             if (start) {
8104                 performStart(reason);
8105             }
8106         }
8107     }
8108 
performResume(boolean followedByPause, String reason)8109     final void performResume(boolean followedByPause, String reason) {
8110         dispatchActivityPreResumed();
8111         performRestart(true /* start */, reason);
8112 
8113         mFragments.execPendingActions();
8114 
8115         mLastNonConfigurationInstances = null;
8116 
8117         if (mAutoFillResetNeeded) {
8118             // When Activity is destroyed in paused state, and relaunch activity, there will be
8119             // extra onResume and onPause event,  ignore the first onResume and onPause.
8120             // see ActivityThread.handleRelaunchActivity()
8121             mAutoFillIgnoreFirstResumePause = followedByPause;
8122             if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
8123                 Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
8124             }
8125         }
8126 
8127         mCalled = false;
8128         // mResumed is set by the instrumentation
8129         mInstrumentation.callActivityOnResume(this);
8130         EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
8131         if (!mCalled) {
8132             throw new SuperNotCalledException(
8133                 "Activity " + mComponent.toShortString() +
8134                 " did not call through to super.onResume()");
8135         }
8136 
8137         // invisible activities must be finished before onResume() completes
8138         if (!mVisibleFromClient && !mFinished) {
8139             Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
8140             if (getApplicationInfo().targetSdkVersion
8141                     > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
8142                 throw new IllegalStateException(
8143                         "Activity " + mComponent.toShortString() +
8144                         " did not call finish() prior to onResume() completing");
8145             }
8146         }
8147 
8148         // Now really resume, and install the current status bar and menu.
8149         mCalled = false;
8150 
8151         mFragments.dispatchResume();
8152         mFragments.execPendingActions();
8153 
8154         onPostResume();
8155         if (!mCalled) {
8156             throw new SuperNotCalledException(
8157                 "Activity " + mComponent.toShortString() +
8158                 " did not call through to super.onPostResume()");
8159         }
8160         dispatchActivityPostResumed();
8161     }
8162 
performPause()8163     final void performPause() {
8164         dispatchActivityPrePaused();
8165         mDoReportFullyDrawn = false;
8166         mFragments.dispatchPause();
8167         mCalled = false;
8168         onPause();
8169         EventLogTags.writeWmOnPausedCalled(mIdent, getComponentName().getClassName(),
8170                 "performPause");
8171         mResumed = false;
8172         if (!mCalled && getApplicationInfo().targetSdkVersion
8173                 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
8174             throw new SuperNotCalledException(
8175                     "Activity " + mComponent.toShortString() +
8176                     " did not call through to super.onPause()");
8177         }
8178         dispatchActivityPostPaused();
8179     }
8180 
performUserLeaving()8181     final void performUserLeaving() {
8182         onUserInteraction();
8183         onUserLeaveHint();
8184     }
8185 
performStop(boolean preserveWindow, String reason)8186     final void performStop(boolean preserveWindow, String reason) {
8187         mDoReportFullyDrawn = false;
8188         mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
8189 
8190         // Disallow entering picture-in-picture after the activity has been stopped
8191         mCanEnterPictureInPicture = false;
8192 
8193         if (!mStopped) {
8194             dispatchActivityPreStopped();
8195             if (mWindow != null) {
8196                 mWindow.closeAllPanels();
8197             }
8198 
8199             // If we're preserving the window, don't setStoppedState to true, since we
8200             // need the window started immediately again. Stopping the window will
8201             // destroys hardware resources and causes flicker.
8202             if (!preserveWindow && mToken != null && mParent == null) {
8203                 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
8204             }
8205 
8206             mFragments.dispatchStop();
8207 
8208             mCalled = false;
8209             mInstrumentation.callActivityOnStop(this);
8210             EventLogTags.writeWmOnStopCalled(mIdent, getComponentName().getClassName(), reason);
8211             if (!mCalled) {
8212                 throw new SuperNotCalledException(
8213                     "Activity " + mComponent.toShortString() +
8214                     " did not call through to super.onStop()");
8215             }
8216 
8217             synchronized (mManagedCursors) {
8218                 final int N = mManagedCursors.size();
8219                 for (int i=0; i<N; i++) {
8220                     ManagedCursor mc = mManagedCursors.get(i);
8221                     if (!mc.mReleased) {
8222                         mc.mCursor.deactivate();
8223                         mc.mReleased = true;
8224                     }
8225                 }
8226             }
8227 
8228             mStopped = true;
8229             dispatchActivityPostStopped();
8230         }
8231         mResumed = false;
8232     }
8233 
performDestroy()8234     final void performDestroy() {
8235         dispatchActivityPreDestroyed();
8236         mDestroyed = true;
8237         mWindow.destroy();
8238         mFragments.dispatchDestroy();
8239         onDestroy();
8240         EventLogTags.writeWmOnDestroyCalled(mIdent, getComponentName().getClassName(),
8241                 "performDestroy");
8242         mFragments.doLoaderDestroy();
8243         if (mVoiceInteractor != null) {
8244             mVoiceInteractor.detachActivity();
8245         }
8246         dispatchActivityPostDestroyed();
8247     }
8248 
dispatchMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig)8249     final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
8250             Configuration newConfig) {
8251         if (DEBUG_LIFECYCLE) Slog.v(TAG,
8252                 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
8253                         + " " + newConfig);
8254         mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
8255         if (mWindow != null) {
8256             mWindow.onMultiWindowModeChanged();
8257         }
8258         mIsInMultiWindowMode = isInMultiWindowMode;
8259         onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
8260     }
8261 
dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig)8262     final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
8263             Configuration newConfig) {
8264         if (DEBUG_LIFECYCLE) Slog.v(TAG,
8265                 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
8266                         + " " + newConfig);
8267         mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
8268         if (mWindow != null) {
8269             mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
8270         }
8271         mIsInPictureInPictureMode = isInPictureInPictureMode;
8272         onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
8273     }
8274 
8275     /**
8276      * @hide
8277      */
8278     @UnsupportedAppUsage
isResumed()8279     public final boolean isResumed() {
8280         return mResumed;
8281     }
8282 
storeHasCurrentPermissionRequest(Bundle bundle)8283     private void storeHasCurrentPermissionRequest(Bundle bundle) {
8284         if (bundle != null && mHasCurrentPermissionsRequest) {
8285             bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
8286         }
8287     }
8288 
restoreHasCurrentPermissionRequest(Bundle bundle)8289     private void restoreHasCurrentPermissionRequest(Bundle bundle) {
8290         if (bundle != null) {
8291             mHasCurrentPermissionsRequest = bundle.getBoolean(
8292                     HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
8293         }
8294     }
8295 
8296     @UnsupportedAppUsage
dispatchActivityResult(String who, int requestCode, int resultCode, Intent data, String reason)8297     void dispatchActivityResult(String who, int requestCode, int resultCode, Intent data,
8298             String reason) {
8299         if (false) Log.v(
8300             TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
8301             + ", resCode=" + resultCode + ", data=" + data);
8302         mFragments.noteStateNotSaved();
8303         if (who == null) {
8304             onActivityResult(requestCode, resultCode, data);
8305         } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
8306             who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
8307             if (TextUtils.isEmpty(who)) {
8308                 dispatchRequestPermissionsResult(requestCode, data);
8309             } else {
8310                 Fragment frag = mFragments.findFragmentByWho(who);
8311                 if (frag != null) {
8312                     dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
8313                 }
8314             }
8315         } else if (who.startsWith("@android:view:")) {
8316             ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
8317                     getActivityToken());
8318             for (ViewRootImpl viewRoot : views) {
8319                 if (viewRoot.getView() != null
8320                         && viewRoot.getView().dispatchActivityResult(
8321                                 who, requestCode, resultCode, data)) {
8322                     return;
8323                 }
8324             }
8325         } else if (who.startsWith(AUTO_FILL_AUTH_WHO_PREFIX)) {
8326             Intent resultData = (resultCode == Activity.RESULT_OK) ? data : null;
8327             getAutofillManager().onAuthenticationResult(requestCode, resultData, getCurrentFocus());
8328         } else {
8329             Fragment frag = mFragments.findFragmentByWho(who);
8330             if (frag != null) {
8331                 frag.onActivityResult(requestCode, resultCode, data);
8332             }
8333         }
8334 
8335         EventLogTags.writeWmOnActivityResultCalled(mIdent, getComponentName().getClassName(),
8336                 reason);
8337     }
8338 
8339     /**
8340      * Request to put this activity in a mode where the user is locked to a restricted set of
8341      * applications.
8342      *
8343      * <p>If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns {@code true}
8344      * for this component, the current task will be launched directly into LockTask mode. Only apps
8345      * whitelisted by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])} can
8346      * be launched while LockTask mode is active. The user will not be able to leave this mode
8347      * until this activity calls {@link #stopLockTask()}. Calling this method while the device is
8348      * already in LockTask mode has no effect.
8349      *
8350      * <p>Otherwise, the current task will be launched into screen pinning mode. In this case, the
8351      * system will prompt the user with a dialog requesting permission to use this mode.
8352      * The user can exit at any time through instructions shown on the request dialog. Calling
8353      * {@link #stopLockTask()} will also terminate this mode.
8354      *
8355      * <p><strong>Note:</strong> this method can only be called when the activity is foreground.
8356      * That is, between {@link #onResume()} and {@link #onPause()}.
8357      *
8358      * @see #stopLockTask()
8359      * @see android.R.attr#lockTaskMode
8360      */
startLockTask()8361     public void startLockTask() {
8362         try {
8363             ActivityTaskManager.getService().startLockTaskModeByToken(mToken);
8364         } catch (RemoteException e) {
8365         }
8366     }
8367 
8368     /**
8369      * Stop the current task from being locked.
8370      *
8371      * <p>Called to end the LockTask or screen pinning mode started by {@link #startLockTask()}.
8372      * This can only be called by activities that have called {@link #startLockTask()} previously.
8373      *
8374      * <p><strong>Note:</strong> If the device is in LockTask mode that is not initially started
8375      * by this activity, then calling this method will not terminate the LockTask mode, but only
8376      * finish its own task. The device will remain in LockTask mode, until the activity which
8377      * started the LockTask mode calls this method, or until its whitelist authorization is revoked
8378      * by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])}.
8379      *
8380      * @see #startLockTask()
8381      * @see android.R.attr#lockTaskMode
8382      * @see ActivityManager#getLockTaskModeState()
8383      */
stopLockTask()8384     public void stopLockTask() {
8385         try {
8386             ActivityTaskManager.getService().stopLockTaskModeByToken(mToken);
8387         } catch (RemoteException e) {
8388         }
8389     }
8390 
8391     /**
8392      * Shows the user the system defined message for telling the user how to exit
8393      * lock task mode. The task containing this activity must be in lock task mode at the time
8394      * of this call for the message to be displayed.
8395      */
showLockTaskEscapeMessage()8396     public void showLockTaskEscapeMessage() {
8397         try {
8398             ActivityTaskManager.getService().showLockTaskEscapeMessage(mToken);
8399         } catch (RemoteException e) {
8400         }
8401     }
8402 
8403     /**
8404      * Check whether the caption on freeform windows is displayed directly on the content.
8405      *
8406      * @return True if caption is displayed on content, false if it pushes the content down.
8407      *
8408      * @see #setOverlayWithDecorCaptionEnabled(boolean)
8409      * @hide
8410      */
isOverlayWithDecorCaptionEnabled()8411     public boolean isOverlayWithDecorCaptionEnabled() {
8412         return mWindow.isOverlayWithDecorCaptionEnabled();
8413     }
8414 
8415     /**
8416      * Set whether the caption should displayed directly on the content rather than push it down.
8417      *
8418      * This affects only freeform windows since they display the caption and only the main
8419      * window of the activity. The caption is used to drag the window around and also shows
8420      * maximize and close action buttons.
8421      * @hide
8422      */
setOverlayWithDecorCaptionEnabled(boolean enabled)8423     public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
8424         mWindow.setOverlayWithDecorCaptionEnabled(enabled);
8425     }
8426 
8427     /**
8428      * Interface for informing a translucent {@link Activity} once all visible activities below it
8429      * have completed drawing. This is necessary only after an {@link Activity} has been made
8430      * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
8431      * translucent again following a call to {@link
8432      * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
8433      * ActivityOptions)}
8434      *
8435      * @hide
8436      */
8437     @SystemApi
8438     public interface TranslucentConversionListener {
8439         /**
8440          * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
8441          * below the top one have been redrawn. Following this callback it is safe to make the top
8442          * Activity translucent because the underlying Activity has been drawn.
8443          *
8444          * @param drawComplete True if the background Activity has drawn itself. False if a timeout
8445          * occurred waiting for the Activity to complete drawing.
8446          *
8447          * @see Activity#convertFromTranslucent()
8448          * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
8449          */
onTranslucentConversionComplete(boolean drawComplete)8450         public void onTranslucentConversionComplete(boolean drawComplete);
8451     }
8452 
dispatchRequestPermissionsResult(int requestCode, Intent data)8453     private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
8454         mHasCurrentPermissionsRequest = false;
8455         // If the package installer crashed we may have not data - best effort.
8456         String[] permissions = (data != null) ? data.getStringArrayExtra(
8457                 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8458         final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8459                 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
8460         onRequestPermissionsResult(requestCode, permissions, grantResults);
8461     }
8462 
dispatchRequestPermissionsResultToFragment(int requestCode, Intent data, Fragment fragment)8463     private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
8464             Fragment fragment) {
8465         // If the package installer crashed we may have not data - best effort.
8466         String[] permissions = (data != null) ? data.getStringArrayExtra(
8467                 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8468         final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8469                 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
8470         fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
8471     }
8472 
8473     /** @hide */
8474     @Override
autofillClientAuthenticate(int authenticationId, IntentSender intent, Intent fillInIntent, boolean authenticateInline)8475     public final void autofillClientAuthenticate(int authenticationId, IntentSender intent,
8476             Intent fillInIntent, boolean authenticateInline) {
8477         try {
8478             startIntentSenderForResultInner(intent, AUTO_FILL_AUTH_WHO_PREFIX,
8479                     authenticationId, fillInIntent, 0, 0, null);
8480         } catch (IntentSender.SendIntentException e) {
8481             Log.e(TAG, "authenticate() failed for intent:" + intent, e);
8482         }
8483     }
8484 
8485     /** @hide */
8486     @Override
autofillClientResetableStateAvailable()8487     public final void autofillClientResetableStateAvailable() {
8488         mAutoFillResetNeeded = true;
8489     }
8490 
8491     /** @hide */
8492     @Override
autofillClientRequestShowFillUi(@onNull View anchor, int width, int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter)8493     public final boolean autofillClientRequestShowFillUi(@NonNull View anchor, int width,
8494             int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter) {
8495         final boolean wasShowing;
8496 
8497         if (mAutofillPopupWindow == null) {
8498             wasShowing = false;
8499             mAutofillPopupWindow = new AutofillPopupWindow(presenter);
8500         } else {
8501             wasShowing = mAutofillPopupWindow.isShowing();
8502         }
8503         mAutofillPopupWindow.update(anchor, 0, 0, width, height, anchorBounds);
8504 
8505         return !wasShowing && mAutofillPopupWindow.isShowing();
8506     }
8507 
8508     /** @hide */
8509     @Override
autofillClientDispatchUnhandledKey(@onNull View anchor, @NonNull KeyEvent keyEvent)8510     public final void autofillClientDispatchUnhandledKey(@NonNull View anchor,
8511             @NonNull KeyEvent keyEvent) {
8512         ViewRootImpl rootImpl = anchor.getViewRootImpl();
8513         if (rootImpl != null) {
8514             // dont care if anchorView is current focus, for example a custom view may only receive
8515             // touchEvent, not focusable but can still trigger autofill window. The Key handling
8516             // might be inside parent of the custom view.
8517             rootImpl.dispatchKeyFromAutofill(keyEvent);
8518         }
8519     }
8520 
8521     /** @hide */
8522     @Override
autofillClientRequestHideFillUi()8523     public final boolean autofillClientRequestHideFillUi() {
8524         if (mAutofillPopupWindow == null) {
8525             return false;
8526         }
8527         mAutofillPopupWindow.dismiss();
8528         mAutofillPopupWindow = null;
8529         return true;
8530     }
8531 
8532     /** @hide */
8533     @Override
autofillClientIsFillUiShowing()8534     public final boolean autofillClientIsFillUiShowing() {
8535         return mAutofillPopupWindow != null && mAutofillPopupWindow.isShowing();
8536     }
8537 
8538     /** @hide */
8539     @Override
8540     @NonNull
autofillClientFindViewsByAutofillIdTraversal( @onNull AutofillId[] autofillId)8541     public final View[] autofillClientFindViewsByAutofillIdTraversal(
8542             @NonNull AutofillId[] autofillId) {
8543         final View[] views = new View[autofillId.length];
8544         final ArrayList<ViewRootImpl> roots =
8545                 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
8546 
8547         for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8548             final View rootView = roots.get(rootNum).getView();
8549 
8550             if (rootView != null) {
8551                 final int viewCount = autofillId.length;
8552                 for (int viewNum = 0; viewNum < viewCount; viewNum++) {
8553                     if (views[viewNum] == null) {
8554                         views[viewNum] = rootView.findViewByAutofillIdTraversal(
8555                                 autofillId[viewNum].getViewId());
8556                     }
8557                 }
8558             }
8559         }
8560 
8561         return views;
8562     }
8563 
8564     /** @hide */
8565     @Override
8566     @Nullable
autofillClientFindViewByAutofillIdTraversal(AutofillId autofillId)8567     public final View autofillClientFindViewByAutofillIdTraversal(AutofillId autofillId) {
8568         final ArrayList<ViewRootImpl> roots =
8569                 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
8570         for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8571             final View rootView = roots.get(rootNum).getView();
8572 
8573             if (rootView != null) {
8574                 final View view = rootView.findViewByAutofillIdTraversal(autofillId.getViewId());
8575                 if (view != null) {
8576                     return view;
8577                 }
8578             }
8579         }
8580 
8581         return null;
8582     }
8583 
8584     /** @hide */
8585     @Override
autofillClientGetViewVisibility( @onNull AutofillId[] autofillIds)8586     public final @NonNull boolean[] autofillClientGetViewVisibility(
8587             @NonNull AutofillId[] autofillIds) {
8588         final int autofillIdCount = autofillIds.length;
8589         final boolean[] visible = new boolean[autofillIdCount];
8590         for (int i = 0; i < autofillIdCount; i++) {
8591             final AutofillId autofillId = autofillIds[i];
8592             final View view = autofillClientFindViewByAutofillIdTraversal(autofillId);
8593             if (view != null) {
8594                 if (!autofillId.isVirtualInt()) {
8595                     visible[i] = view.isVisibleToUser();
8596                 } else {
8597                     visible[i] = view.isVisibleToUserForAutofill(autofillId.getVirtualChildIntId());
8598                 }
8599             }
8600         }
8601         if (android.view.autofill.Helper.sVerbose) {
8602             Log.v(TAG, "autofillClientGetViewVisibility(): " + Arrays.toString(visible));
8603         }
8604         return visible;
8605     }
8606 
8607     /** @hide */
autofillClientFindViewByAccessibilityIdTraversal(int viewId, int windowId)8608     public final @Nullable View autofillClientFindViewByAccessibilityIdTraversal(int viewId,
8609             int windowId) {
8610         final ArrayList<ViewRootImpl> roots = WindowManagerGlobal.getInstance()
8611                 .getRootViews(getActivityToken());
8612         for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8613             final View rootView = roots.get(rootNum).getView();
8614             if (rootView != null && rootView.getAccessibilityWindowId() == windowId) {
8615                 final View view = rootView.findViewByAccessibilityIdTraversal(viewId);
8616                 if (view != null) {
8617                     return view;
8618                 }
8619             }
8620         }
8621         return null;
8622     }
8623 
8624     /** @hide */
8625     @Override
autofillClientGetActivityToken()8626     public final @Nullable IBinder autofillClientGetActivityToken() {
8627         return getActivityToken();
8628     }
8629 
8630     /** @hide */
8631     @Override
autofillClientIsVisibleForAutofill()8632     public final boolean autofillClientIsVisibleForAutofill() {
8633         return !mStopped;
8634     }
8635 
8636     /** @hide */
8637     @Override
autofillClientIsCompatibilityModeEnabled()8638     public final boolean autofillClientIsCompatibilityModeEnabled() {
8639         return isAutofillCompatibilityEnabled();
8640     }
8641 
8642     /** @hide */
8643     @Override
isDisablingEnterExitEventForAutofill()8644     public final boolean isDisablingEnterExitEventForAutofill() {
8645         return mAutoFillIgnoreFirstResumePause || !mResumed;
8646     }
8647 
8648     /**
8649      * If set to true, this indicates to the system that it should never take a
8650      * screenshot of the activity to be used as a representation while it is not in a started state.
8651      * <p>
8652      * Note that the system may use the window background of the theme instead to represent
8653      * the window when it is not running.
8654      * <p>
8655      * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
8656      * this only affects the behavior when the activity's screenshot would be used as a
8657      * representation when the activity is not in a started state, i.e. in Overview. The system may
8658      * still take screenshots of the activity in other contexts; for example, when the user takes a
8659      * screenshot of the entire screen, or when the active
8660      * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
8661      * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
8662      *
8663      * @param disable {@code true} to disable preview screenshots; {@code false} otherwise.
8664      * @hide
8665      */
8666     @UnsupportedAppUsage
setDisablePreviewScreenshots(boolean disable)8667     public void setDisablePreviewScreenshots(boolean disable) {
8668         try {
8669             ActivityTaskManager.getService().setDisablePreviewScreenshots(mToken, disable);
8670         } catch (RemoteException e) {
8671             throw e.rethrowFromSystemServer();
8672         }
8673     }
8674 
8675     /**
8676      * Specifies whether an {@link Activity} should be shown on top of the lock screen whenever
8677      * the lockscreen is up and the activity is resumed. Normally an activity will be transitioned
8678      * to the stopped state if it is started while the lockscreen is up, but with this flag set the
8679      * activity will remain in the resumed state visible on-top of the lock screen. This value can
8680      * be set as a manifest attribute using {@link android.R.attr#showWhenLocked}.
8681      *
8682      * @param showWhenLocked {@code true} to show the {@link Activity} on top of the lock screen;
8683      *                                   {@code false} otherwise.
8684      * @see #setTurnScreenOn(boolean)
8685      * @see android.R.attr#turnScreenOn
8686      * @see android.R.attr#showWhenLocked
8687      */
setShowWhenLocked(boolean showWhenLocked)8688     public void setShowWhenLocked(boolean showWhenLocked) {
8689         try {
8690             ActivityTaskManager.getService().setShowWhenLocked(mToken, showWhenLocked);
8691         } catch (RemoteException e) {
8692             throw e.rethrowFromSystemServer();
8693         }
8694     }
8695 
8696     /**
8697      * Specifies whether this {@link Activity} should be shown on top of the lock screen whenever
8698      * the lockscreen is up and this activity has another activity behind it with the showWhenLock
8699      * attribute set. That is, this activity is only visible on the lock screen if there is another
8700      * activity with the showWhenLock attribute visible at the same time on the lock screen. A use
8701      * case for this is permission dialogs, that should only be visible on the lock screen if their
8702      * requesting activity is also visible. This value can be set as a manifest attribute using
8703      * android.R.attr#inheritShowWhenLocked.
8704      *
8705      * @param inheritShowWhenLocked {@code true} to show the {@link Activity} on top of the lock
8706      *                              screen when this activity has another activity behind it with
8707      *                              the showWhenLock attribute set; {@code false} otherwise.
8708      * @see #setShowWhenLocked(boolean)
8709      * @see android.R.attr#inheritShowWhenLocked
8710      */
setInheritShowWhenLocked(boolean inheritShowWhenLocked)8711     public void setInheritShowWhenLocked(boolean inheritShowWhenLocked) {
8712         try {
8713             ActivityTaskManager.getService().setInheritShowWhenLocked(
8714                     mToken, inheritShowWhenLocked);
8715         } catch (RemoteException e) {
8716             throw e.rethrowFromSystemServer();
8717         }
8718     }
8719 
8720     /**
8721      * Specifies whether the screen should be turned on when the {@link Activity} is resumed.
8722      * Normally an activity will be transitioned to the stopped state if it is started while the
8723      * screen if off, but with this flag set the activity will cause the screen to turn on if the
8724      * activity will be visible and resumed due to the screen coming on. The screen will not be
8725      * turned on if the activity won't be visible after the screen is turned on. This flag is
8726      * normally used in conjunction with the {@link android.R.attr#showWhenLocked} flag to make sure
8727      * the activity is visible after the screen is turned on when the lockscreen is up. In addition,
8728      * if this flag is set and the activity calls {@link
8729      * KeyguardManager#requestDismissKeyguard(Activity, KeyguardManager.KeyguardDismissCallback)}
8730      * the screen will turn on.
8731      *
8732      * @param turnScreenOn {@code true} to turn on the screen; {@code false} otherwise.
8733      *
8734      * @see #setShowWhenLocked(boolean)
8735      * @see android.R.attr#turnScreenOn
8736      * @see android.R.attr#showWhenLocked
8737      */
setTurnScreenOn(boolean turnScreenOn)8738     public void setTurnScreenOn(boolean turnScreenOn) {
8739         try {
8740             ActivityTaskManager.getService().setTurnScreenOn(mToken, turnScreenOn);
8741         } catch (RemoteException e) {
8742             throw e.rethrowFromSystemServer();
8743         }
8744     }
8745 
8746     /**
8747      * Registers remote animations per transition type for this activity.
8748      *
8749      * @param definition The remote animation definition that defines which transition whould run
8750      *                   which remote animation.
8751      * @hide
8752      */
8753     @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
registerRemoteAnimations(RemoteAnimationDefinition definition)8754     public void registerRemoteAnimations(RemoteAnimationDefinition definition) {
8755         try {
8756             ActivityTaskManager.getService().registerRemoteAnimations(mToken, definition);
8757         } catch (RemoteException e) {
8758             throw e.rethrowFromSystemServer();
8759         }
8760     }
8761 
8762     /**
8763      * Unregisters all remote animations for this activity.
8764      *
8765      * @hide
8766      */
8767     @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
unregisterRemoteAnimations()8768     public void unregisterRemoteAnimations() {
8769         try {
8770             ActivityTaskManager.getService().unregisterRemoteAnimations(mToken);
8771         } catch (RemoteException e) {
8772             throw e.rethrowFromSystemServer();
8773         }
8774     }
8775 
8776     class HostCallbacks extends FragmentHostCallback<Activity> {
HostCallbacks()8777         public HostCallbacks() {
8778             super(Activity.this /*activity*/);
8779         }
8780 
8781         @Override
onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)8782         public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
8783             Activity.this.dump(prefix, fd, writer, args);
8784         }
8785 
8786         @Override
onShouldSaveFragmentState(Fragment fragment)8787         public boolean onShouldSaveFragmentState(Fragment fragment) {
8788             return !isFinishing();
8789         }
8790 
8791         @Override
onGetLayoutInflater()8792         public LayoutInflater onGetLayoutInflater() {
8793             final LayoutInflater result = Activity.this.getLayoutInflater();
8794             if (onUseFragmentManagerInflaterFactory()) {
8795                 return result.cloneInContext(Activity.this);
8796             }
8797             return result;
8798         }
8799 
8800         @Override
onUseFragmentManagerInflaterFactory()8801         public boolean onUseFragmentManagerInflaterFactory() {
8802             // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
8803             return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
8804         }
8805 
8806         @Override
onGetHost()8807         public Activity onGetHost() {
8808             return Activity.this;
8809         }
8810 
8811         @Override
onInvalidateOptionsMenu()8812         public void onInvalidateOptionsMenu() {
8813             Activity.this.invalidateOptionsMenu();
8814         }
8815 
8816         @Override
onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)8817         public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
8818                 Bundle options) {
8819             Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
8820         }
8821 
8822         @Override
onStartActivityAsUserFromFragment( Fragment fragment, Intent intent, int requestCode, Bundle options, UserHandle user)8823         public void onStartActivityAsUserFromFragment(
8824                 Fragment fragment, Intent intent, int requestCode, Bundle options,
8825                 UserHandle user) {
8826             Activity.this.startActivityAsUserFromFragment(
8827                     fragment, intent, requestCode, options, user);
8828         }
8829 
8830         @Override
onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)8831         public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
8832                 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
8833                 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
8834             if (mParent == null) {
8835                 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
8836                         flagsMask, flagsValues, options);
8837             } else if (options != null) {
8838                 mParent.startIntentSenderFromFragment(fragment, intent, requestCode,
8839                         fillInIntent, flagsMask, flagsValues, options);
8840             }
8841         }
8842 
8843         @Override
onRequestPermissionsFromFragment(Fragment fragment, String[] permissions, int requestCode)8844         public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
8845                 int requestCode) {
8846             String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
8847             Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
8848             startActivityForResult(who, intent, requestCode, null);
8849         }
8850 
8851         @Override
onHasWindowAnimations()8852         public boolean onHasWindowAnimations() {
8853             return getWindow() != null;
8854         }
8855 
8856         @Override
onGetWindowAnimations()8857         public int onGetWindowAnimations() {
8858             final Window w = getWindow();
8859             return (w == null) ? 0 : w.getAttributes().windowAnimations;
8860         }
8861 
8862         @Override
onAttachFragment(Fragment fragment)8863         public void onAttachFragment(Fragment fragment) {
8864             Activity.this.onAttachFragment(fragment);
8865         }
8866 
8867         @Nullable
8868         @Override
onFindViewById(int id)8869         public <T extends View> T onFindViewById(int id) {
8870             return Activity.this.findViewById(id);
8871         }
8872 
8873         @Override
onHasView()8874         public boolean onHasView() {
8875             final Window w = getWindow();
8876             return (w != null && w.peekDecorView() != null);
8877         }
8878     }
8879 }
8880