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