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