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