OSDN Git Service

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