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