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