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