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