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