OSDN Git Service

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