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