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