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