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