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