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