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