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