OSDN Git Service

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