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