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