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