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