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