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