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