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