OSDN Git Service

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