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