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