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