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