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