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