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