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