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