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