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