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