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