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