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