• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/components/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/components/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/components/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             options = transferSpringboardActivityOptions(options);
4224             Instrumentation.ActivityResult ar =
4225                 mInstrumentation.execStartActivity(
4226                     this, mMainThread.getApplicationThread(), mToken, this,
4227                     intent, requestCode, options);
4228             if (ar != null) {
4229                 mMainThread.sendActivityResult(
4230                     mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4231                     ar.getResultData());
4232             }
4233             if (requestCode >= 0) {
4234                 // If this start is requesting a result, we can avoid making
4235                 // the activity visible until the result is received.  Setting
4236                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4237                 // activity hidden during this time, to avoid flickering.
4238                 // This can only be done when a result is requested because
4239                 // that guarantees we will get information back when the
4240                 // activity is finished, no matter what happens to it.
4241                 mStartedActivity = true;
4242             }
4243 
4244             cancelInputsAndStartExitTransition(options);
4245             // TODO Consider clearing/flushing other event sources and events for child windows.
4246         } else {
4247             if (options != null) {
4248                 mParent.startActivityFromChild(this, intent, requestCode, options);
4249             } else {
4250                 // Note we want to go through this method for compatibility with
4251                 // existing applications that may have overridden it.
4252                 mParent.startActivityFromChild(this, intent, requestCode);
4253             }
4254         }
4255     }
4256 
4257     /**
4258      * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
4259      *
4260      * @param options The ActivityOptions bundle used to start an Activity.
4261      */
cancelInputsAndStartExitTransition(Bundle options)4262     private void cancelInputsAndStartExitTransition(Bundle options) {
4263         final View decor = mWindow != null ? mWindow.peekDecorView() : null;
4264         if (decor != null) {
4265             decor.cancelPendingInputEvents();
4266         }
4267         if (options != null && !isTopOfTask()) {
4268             mActivityTransitionState.startExitOutTransition(this, options);
4269         }
4270     }
4271 
transferSpringboardActivityOptions(Bundle options)4272     private Bundle transferSpringboardActivityOptions(Bundle options) {
4273         if (options == null && (mWindow != null && !mWindow.isActive())) {
4274             final ActivityOptions activityOptions = getActivityOptions();
4275             if (activityOptions != null &&
4276                     activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
4277                 return activityOptions.toBundle();
4278             }
4279         }
4280         return options;
4281     }
4282 
4283     /**
4284      * @hide Implement to provide correct calling token.
4285      */
startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user)4286     public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
4287         startActivityForResultAsUser(intent, requestCode, null, user);
4288     }
4289 
4290     /**
4291      * @hide Implement to provide correct calling token.
4292      */
startActivityForResultAsUser(Intent intent, int requestCode, @Nullable Bundle options, UserHandle user)4293     public void startActivityForResultAsUser(Intent intent, int requestCode,
4294             @Nullable Bundle options, UserHandle user) {
4295         if (mParent != null) {
4296             throw new RuntimeException("Can't be called from a child");
4297         }
4298         options = transferSpringboardActivityOptions(options);
4299         Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4300                 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode,
4301                 options, user);
4302         if (ar != null) {
4303             mMainThread.sendActivityResult(
4304                 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4305         }
4306         if (requestCode >= 0) {
4307             // If this start is requesting a result, we can avoid making
4308             // the activity visible until the result is received.  Setting
4309             // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4310             // activity hidden during this time, to avoid flickering.
4311             // This can only be done when a result is requested because
4312             // that guarantees we will get information back when the
4313             // activity is finished, no matter what happens to it.
4314             mStartedActivity = true;
4315         }
4316 
4317         cancelInputsAndStartExitTransition(options);
4318     }
4319 
4320     /**
4321      * @hide Implement to provide correct calling token.
4322      */
startActivityAsUser(Intent intent, UserHandle user)4323     public void startActivityAsUser(Intent intent, UserHandle user) {
4324         startActivityAsUser(intent, null, user);
4325     }
4326 
4327     /**
4328      * @hide Implement to provide correct calling token.
4329      */
startActivityAsUser(Intent intent, Bundle options, UserHandle user)4330     public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4331         if (mParent != null) {
4332             throw new RuntimeException("Can't be called from a child");
4333         }
4334         options = transferSpringboardActivityOptions(options);
4335         Instrumentation.ActivityResult ar =
4336                 mInstrumentation.execStartActivity(
4337                         this, mMainThread.getApplicationThread(), mToken, this,
4338                         intent, -1, options, user);
4339         if (ar != null) {
4340             mMainThread.sendActivityResult(
4341                 mToken, mEmbeddedID, -1, ar.getResultCode(),
4342                 ar.getResultData());
4343         }
4344         cancelInputsAndStartExitTransition(options);
4345     }
4346 
4347     /**
4348      * Start a new activity as if it was started by the activity that started our
4349      * current activity.  This is for the resolver and chooser activities, which operate
4350      * as intermediaries that dispatch their intent to the target the user selects -- to
4351      * do this, they must perform all security checks including permission grants as if
4352      * their launch had come from the original activity.
4353      * @param intent The Intent to start.
4354      * @param options ActivityOptions or null.
4355      * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4356      * caller it is doing the start is, is actually allowed to start the target activity.
4357      * If you set this to true, you must set an explicit component in the Intent and do any
4358      * appropriate security checks yourself.
4359      * @param userId The user the new activity should run as.
4360      * @hide
4361      */
startActivityAsCaller(Intent intent, @Nullable Bundle options, boolean ignoreTargetSecurity, int userId)4362     public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4363             boolean ignoreTargetSecurity, int userId) {
4364         if (mParent != null) {
4365             throw new RuntimeException("Can't be called from a child");
4366         }
4367         options = transferSpringboardActivityOptions(options);
4368         Instrumentation.ActivityResult ar =
4369                 mInstrumentation.execStartActivityAsCaller(
4370                         this, mMainThread.getApplicationThread(), mToken, this,
4371                         intent, -1, options, ignoreTargetSecurity, userId);
4372         if (ar != null) {
4373             mMainThread.sendActivityResult(
4374                 mToken, mEmbeddedID, -1, ar.getResultCode(),
4375                 ar.getResultData());
4376         }
4377         cancelInputsAndStartExitTransition(options);
4378     }
4379 
4380     /**
4381      * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4382      * Intent, int, int, int, Bundle)} with no options.
4383      *
4384      * @param intent The IntentSender to launch.
4385      * @param requestCode If >= 0, this code will be returned in
4386      *                    onActivityResult() when the activity exits.
4387      * @param fillInIntent If non-null, this will be provided as the
4388      * intent parameter to {@link IntentSender#sendIntent}.
4389      * @param flagsMask Intent flags in the original IntentSender that you
4390      * would like to change.
4391      * @param flagsValues Desired values for any bits set in
4392      * <var>flagsMask</var>
4393      * @param extraFlags Always set to 0.
4394      */
startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)4395     public void startIntentSenderForResult(IntentSender intent, int requestCode,
4396             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4397             throws IntentSender.SendIntentException {
4398         startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4399                 flagsValues, extraFlags, null);
4400     }
4401 
4402     /**
4403      * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4404      * to use a IntentSender to describe the activity to be started.  If
4405      * the IntentSender is for an activity, that activity will be started
4406      * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4407      * here; otherwise, its associated action will be executed (such as
4408      * sending a broadcast) as if you had called
4409      * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4410      *
4411      * @param intent The IntentSender to launch.
4412      * @param requestCode If >= 0, this code will be returned in
4413      *                    onActivityResult() when the activity exits.
4414      * @param fillInIntent If non-null, this will be provided as the
4415      * intent parameter to {@link IntentSender#sendIntent}.
4416      * @param flagsMask Intent flags in the original IntentSender that you
4417      * would like to change.
4418      * @param flagsValues Desired values for any bits set in
4419      * <var>flagsMask</var>
4420      * @param extraFlags Always set to 0.
4421      * @param options Additional options for how the Activity should be started.
4422      * See {@link android.content.Context#startActivity(Intent, Bundle)
4423      * Context.startActivity(Intent, Bundle)} for more details.  If options
4424      * have also been supplied by the IntentSender, options given here will
4425      * override any that conflict with those given by the IntentSender.
4426      */
startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)4427     public void startIntentSenderForResult(IntentSender intent, int requestCode,
4428             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4429             Bundle options) throws IntentSender.SendIntentException {
4430         if (mParent == null) {
4431             startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
4432                     flagsMask, flagsValues, options);
4433         } else if (options != null) {
4434             mParent.startIntentSenderFromChild(this, intent, requestCode,
4435                     fillInIntent, flagsMask, flagsValues, extraFlags, options);
4436         } else {
4437             // Note we want to go through this call for compatibility with
4438             // existing applications that may have overridden the method.
4439             mParent.startIntentSenderFromChild(this, intent, requestCode,
4440                     fillInIntent, flagsMask, flagsValues, extraFlags);
4441         }
4442     }
4443 
startIntentSenderForResultInner(IntentSender intent, String who, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, Bundle options)4444     private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
4445             Intent fillInIntent, int flagsMask, int flagsValues,
4446             Bundle options)
4447             throws IntentSender.SendIntentException {
4448         try {
4449             String resolvedType = null;
4450             if (fillInIntent != null) {
4451                 fillInIntent.migrateExtraStreamToClipData();
4452                 fillInIntent.prepareToLeaveProcess(this);
4453                 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4454             }
4455             int result = ActivityManagerNative.getDefault()
4456                 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
4457                         fillInIntent, resolvedType, mToken, who,
4458                         requestCode, flagsMask, flagsValues, options);
4459             if (result == ActivityManager.START_CANCELED) {
4460                 throw new IntentSender.SendIntentException();
4461             }
4462             Instrumentation.checkStartActivityResult(result, null);
4463         } catch (RemoteException e) {
4464         }
4465         if (requestCode >= 0) {
4466             // If this start is requesting a result, we can avoid making
4467             // the activity visible until the result is received.  Setting
4468             // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4469             // activity hidden during this time, to avoid flickering.
4470             // This can only be done when a result is requested because
4471             // that guarantees we will get information back when the
4472             // activity is finished, no matter what happens to it.
4473             mStartedActivity = true;
4474         }
4475     }
4476 
4477     /**
4478      * Same as {@link #startActivity(Intent, Bundle)} with no options
4479      * specified.
4480      *
4481      * @param intent The intent to start.
4482      *
4483      * @throws android.content.ActivityNotFoundException
4484      *
4485      * @see #startActivity(Intent, Bundle)
4486      * @see #startActivityForResult
4487      */
4488     @Override
startActivity(Intent intent)4489     public void startActivity(Intent intent) {
4490         this.startActivity(intent, null);
4491     }
4492 
4493     /**
4494      * Launch a new activity.  You will not receive any information about when
4495      * the activity exits.  This implementation overrides the base version,
4496      * providing information about
4497      * the activity performing the launch.  Because of this additional
4498      * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4499      * required; if not specified, the new activity will be added to the
4500      * task of the caller.
4501      *
4502      * <p>This method throws {@link android.content.ActivityNotFoundException}
4503      * if there was no Activity found to run the given Intent.
4504      *
4505      * @param intent The intent to start.
4506      * @param options Additional options for how the Activity should be started.
4507      * See {@link android.content.Context#startActivity(Intent, Bundle)
4508      * Context.startActivity(Intent, Bundle)} for more details.
4509      *
4510      * @throws android.content.ActivityNotFoundException
4511      *
4512      * @see #startActivity(Intent)
4513      * @see #startActivityForResult
4514      */
4515     @Override
startActivity(Intent intent, @Nullable Bundle options)4516     public void startActivity(Intent intent, @Nullable Bundle options) {
4517         if (options != null) {
4518             startActivityForResult(intent, -1, options);
4519         } else {
4520             // Note we want to go through this call for compatibility with
4521             // applications that may have overridden the method.
4522             startActivityForResult(intent, -1);
4523         }
4524     }
4525 
4526     /**
4527      * Same as {@link #startActivities(Intent[], Bundle)} with no options
4528      * specified.
4529      *
4530      * @param intents The intents to start.
4531      *
4532      * @throws android.content.ActivityNotFoundException
4533      *
4534      * @see #startActivities(Intent[], Bundle)
4535      * @see #startActivityForResult
4536      */
4537     @Override
startActivities(Intent[] intents)4538     public void startActivities(Intent[] intents) {
4539         startActivities(intents, null);
4540     }
4541 
4542     /**
4543      * Launch a new activity.  You will not receive any information about when
4544      * the activity exits.  This implementation overrides the base version,
4545      * providing information about
4546      * the activity performing the launch.  Because of this additional
4547      * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4548      * required; if not specified, the new activity will be added to the
4549      * task of the caller.
4550      *
4551      * <p>This method throws {@link android.content.ActivityNotFoundException}
4552      * if there was no Activity found to run the given Intent.
4553      *
4554      * @param intents The intents to start.
4555      * @param options Additional options for how the Activity should be started.
4556      * See {@link android.content.Context#startActivity(Intent, Bundle)
4557      * Context.startActivity(Intent, Bundle)} for more details.
4558      *
4559      * @throws android.content.ActivityNotFoundException
4560      *
4561      * @see #startActivities(Intent[])
4562      * @see #startActivityForResult
4563      */
4564     @Override
startActivities(Intent[] intents, @Nullable Bundle options)4565     public void startActivities(Intent[] intents, @Nullable Bundle options) {
4566         mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4567                 mToken, this, intents, options);
4568     }
4569 
4570     /**
4571      * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4572      * with no options.
4573      *
4574      * @param intent The IntentSender to launch.
4575      * @param fillInIntent If non-null, this will be provided as the
4576      * intent parameter to {@link IntentSender#sendIntent}.
4577      * @param flagsMask Intent flags in the original IntentSender that you
4578      * would like to change.
4579      * @param flagsValues Desired values for any bits set in
4580      * <var>flagsMask</var>
4581      * @param extraFlags Always set to 0.
4582      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)4583     public void startIntentSender(IntentSender intent,
4584             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4585             throws IntentSender.SendIntentException {
4586         startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4587                 extraFlags, null);
4588     }
4589 
4590     /**
4591      * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4592      * to start; see
4593      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4594      * for more information.
4595      *
4596      * @param intent The IntentSender to launch.
4597      * @param fillInIntent If non-null, this will be provided as the
4598      * intent parameter to {@link IntentSender#sendIntent}.
4599      * @param flagsMask Intent flags in the original IntentSender that you
4600      * would like to change.
4601      * @param flagsValues Desired values for any bits set in
4602      * <var>flagsMask</var>
4603      * @param extraFlags Always set to 0.
4604      * @param options Additional options for how the Activity should be started.
4605      * See {@link android.content.Context#startActivity(Intent, Bundle)
4606      * Context.startActivity(Intent, Bundle)} for more details.  If options
4607      * have also been supplied by the IntentSender, options given here will
4608      * override any that conflict with those given by the IntentSender.
4609      */
startIntentSender(IntentSender intent, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)4610     public void startIntentSender(IntentSender intent,
4611             @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4612             Bundle options) throws IntentSender.SendIntentException {
4613         if (options != null) {
4614             startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4615                     flagsValues, extraFlags, options);
4616         } else {
4617             // Note we want to go through this call for compatibility with
4618             // applications that may have overridden the method.
4619             startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4620                     flagsValues, extraFlags);
4621         }
4622     }
4623 
4624     /**
4625      * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4626      * with no options.
4627      *
4628      * @param intent The intent to start.
4629      * @param requestCode If >= 0, this code will be returned in
4630      *         onActivityResult() when the activity exits, as described in
4631      *         {@link #startActivityForResult}.
4632      *
4633      * @return If a new activity was launched then true is returned; otherwise
4634      *         false is returned and you must handle the Intent yourself.
4635      *
4636      * @see #startActivity
4637      * @see #startActivityForResult
4638      */
startActivityIfNeeded(@equiresPermission @onNull Intent intent, int requestCode)4639     public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4640             int requestCode) {
4641         return startActivityIfNeeded(intent, requestCode, null);
4642     }
4643 
4644     /**
4645      * A special variation to launch an activity only if a new activity
4646      * instance is needed to handle the given Intent.  In other words, this is
4647      * just like {@link #startActivityForResult(Intent, int)} except: if you are
4648      * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4649      * singleTask or singleTop
4650      * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4651      * and the activity
4652      * that handles <var>intent</var> is the same as your currently running
4653      * activity, then a new instance is not needed.  In this case, instead of
4654      * the normal behavior of calling {@link #onNewIntent} this function will
4655      * return and you can handle the Intent yourself.
4656      *
4657      * <p>This function can only be called from a top-level activity; if it is
4658      * called from a child activity, a runtime exception will be thrown.
4659      *
4660      * @param intent The intent to start.
4661      * @param requestCode If >= 0, this code will be returned in
4662      *         onActivityResult() when the activity exits, as described in
4663      *         {@link #startActivityForResult}.
4664      * @param options Additional options for how the Activity should be started.
4665      * See {@link android.content.Context#startActivity(Intent, Bundle)
4666      * Context.startActivity(Intent, Bundle)} for more details.
4667      *
4668      * @return If a new activity was launched then true is returned; otherwise
4669      *         false is returned and you must handle the Intent yourself.
4670      *
4671      * @see #startActivity
4672      * @see #startActivityForResult
4673      */
startActivityIfNeeded(@equiresPermission @onNull Intent intent, int requestCode, @Nullable Bundle options)4674     public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4675             int requestCode, @Nullable Bundle options) {
4676         if (mParent == null) {
4677             int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4678             try {
4679                 Uri referrer = onProvideReferrer();
4680                 if (referrer != null) {
4681                     intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4682                 }
4683                 intent.migrateExtraStreamToClipData();
4684                 intent.prepareToLeaveProcess(this);
4685                 result = ActivityManagerNative.getDefault()
4686                     .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4687                             intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4688                             mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4689                             null, options);
4690             } catch (RemoteException e) {
4691                 // Empty
4692             }
4693 
4694             Instrumentation.checkStartActivityResult(result, intent);
4695 
4696             if (requestCode >= 0) {
4697                 // If this start is requesting a result, we can avoid making
4698                 // the activity visible until the result is received.  Setting
4699                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4700                 // activity hidden during this time, to avoid flickering.
4701                 // This can only be done when a result is requested because
4702                 // that guarantees we will get information back when the
4703                 // activity is finished, no matter what happens to it.
4704                 mStartedActivity = true;
4705             }
4706             return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4707         }
4708 
4709         throw new UnsupportedOperationException(
4710             "startActivityIfNeeded can only be called from a top-level activity");
4711     }
4712 
4713     /**
4714      * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4715      * no options.
4716      *
4717      * @param intent The intent to dispatch to the next activity.  For
4718      * correct behavior, this must be the same as the Intent that started
4719      * your own activity; the only changes you can make are to the extras
4720      * inside of it.
4721      *
4722      * @return Returns a boolean indicating whether there was another Activity
4723      * to start: true if there was a next activity to start, false if there
4724      * wasn't.  In general, if true is returned you will then want to call
4725      * finish() on yourself.
4726      */
startNextMatchingActivity(@equiresPermission @onNull Intent intent)4727     public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
4728         return startNextMatchingActivity(intent, null);
4729     }
4730 
4731     /**
4732      * Special version of starting an activity, for use when you are replacing
4733      * other activity components.  You can use this to hand the Intent off
4734      * to the next Activity that can handle it.  You typically call this in
4735      * {@link #onCreate} with the Intent returned by {@link #getIntent}.
4736      *
4737      * @param intent The intent to dispatch to the next activity.  For
4738      * correct behavior, this must be the same as the Intent that started
4739      * your own activity; the only changes you can make are to the extras
4740      * inside of it.
4741      * @param options Additional options for how the Activity should be started.
4742      * See {@link android.content.Context#startActivity(Intent, Bundle)
4743      * Context.startActivity(Intent, Bundle)} for more details.
4744      *
4745      * @return Returns a boolean indicating whether there was another Activity
4746      * to start: true if there was a next activity to start, false if there
4747      * wasn't.  In general, if true is returned you will then want to call
4748      * finish() on yourself.
4749      */
startNextMatchingActivity(@equiresPermission @onNull Intent intent, @Nullable Bundle options)4750     public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
4751             @Nullable Bundle options) {
4752         if (mParent == null) {
4753             try {
4754                 intent.migrateExtraStreamToClipData();
4755                 intent.prepareToLeaveProcess(this);
4756                 return ActivityManagerNative.getDefault()
4757                     .startNextMatchingActivity(mToken, intent, options);
4758             } catch (RemoteException e) {
4759                 // Empty
4760             }
4761             return false;
4762         }
4763 
4764         throw new UnsupportedOperationException(
4765             "startNextMatchingActivity can only be called from a top-level activity");
4766     }
4767 
4768     /**
4769      * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
4770      * with no options.
4771      *
4772      * @param child The activity making the call.
4773      * @param intent The intent to start.
4774      * @param requestCode Reply request code.  < 0 if reply is not requested.
4775      *
4776      * @throws android.content.ActivityNotFoundException
4777      *
4778      * @see #startActivity
4779      * @see #startActivityForResult
4780      */
startActivityFromChild(@onNull Activity child, @RequiresPermission Intent intent, int requestCode)4781     public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
4782             int requestCode) {
4783         startActivityFromChild(child, intent, requestCode, null);
4784     }
4785 
4786     /**
4787      * This is called when a child activity of this one calls its
4788      * {@link #startActivity} or {@link #startActivityForResult} method.
4789      *
4790      * <p>This method throws {@link android.content.ActivityNotFoundException}
4791      * if there was no Activity found to run the given Intent.
4792      *
4793      * @param child The activity making the call.
4794      * @param intent The intent to start.
4795      * @param requestCode Reply request code.  < 0 if reply is not requested.
4796      * @param options Additional options for how the Activity should be started.
4797      * See {@link android.content.Context#startActivity(Intent, Bundle)
4798      * Context.startActivity(Intent, Bundle)} for more details.
4799      *
4800      * @throws android.content.ActivityNotFoundException
4801      *
4802      * @see #startActivity
4803      * @see #startActivityForResult
4804      */
startActivityFromChild(@onNull Activity child, @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options)4805     public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
4806             int requestCode, @Nullable Bundle options) {
4807         options = transferSpringboardActivityOptions(options);
4808         Instrumentation.ActivityResult ar =
4809             mInstrumentation.execStartActivity(
4810                 this, mMainThread.getApplicationThread(), mToken, child,
4811                 intent, requestCode, options);
4812         if (ar != null) {
4813             mMainThread.sendActivityResult(
4814                 mToken, child.mEmbeddedID, requestCode,
4815                 ar.getResultCode(), ar.getResultData());
4816         }
4817         cancelInputsAndStartExitTransition(options);
4818     }
4819 
4820     /**
4821      * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
4822      * with no options.
4823      *
4824      * @param fragment The fragment making the call.
4825      * @param intent The intent to start.
4826      * @param requestCode Reply request code.  < 0 if reply is not requested.
4827      *
4828      * @throws android.content.ActivityNotFoundException
4829      *
4830      * @see Fragment#startActivity
4831      * @see Fragment#startActivityForResult
4832      */
startActivityFromFragment(@onNull Fragment fragment, @RequiresPermission Intent intent, int requestCode)4833     public void startActivityFromFragment(@NonNull Fragment fragment,
4834             @RequiresPermission Intent intent, int requestCode) {
4835         startActivityFromFragment(fragment, intent, requestCode, null);
4836     }
4837 
4838     /**
4839      * This is called when a Fragment in this activity calls its
4840      * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
4841      * method.
4842      *
4843      * <p>This method throws {@link android.content.ActivityNotFoundException}
4844      * if there was no Activity found to run the given Intent.
4845      *
4846      * @param fragment The fragment making the call.
4847      * @param intent The intent to start.
4848      * @param requestCode Reply request code.  < 0 if reply is not requested.
4849      * @param options Additional options for how the Activity should be started.
4850      * See {@link android.content.Context#startActivity(Intent, Bundle)
4851      * Context.startActivity(Intent, Bundle)} for more details.
4852      *
4853      * @throws android.content.ActivityNotFoundException
4854      *
4855      * @see Fragment#startActivity
4856      * @see Fragment#startActivityForResult
4857      */
startActivityFromFragment(@onNull Fragment fragment, @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options)4858     public void startActivityFromFragment(@NonNull Fragment fragment,
4859             @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
4860         startActivityForResult(fragment.mWho, intent, requestCode, options);
4861     }
4862 
4863     /**
4864      * @hide
4865      */
4866     @Override
startActivityForResult( String who, Intent intent, int requestCode, @Nullable Bundle options)4867     public void startActivityForResult(
4868             String who, Intent intent, int requestCode, @Nullable Bundle options) {
4869         Uri referrer = onProvideReferrer();
4870         if (referrer != null) {
4871             intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4872         }
4873         options = transferSpringboardActivityOptions(options);
4874         Instrumentation.ActivityResult ar =
4875             mInstrumentation.execStartActivity(
4876                 this, mMainThread.getApplicationThread(), mToken, who,
4877                 intent, requestCode, options);
4878         if (ar != null) {
4879             mMainThread.sendActivityResult(
4880                 mToken, who, requestCode,
4881                 ar.getResultCode(), ar.getResultData());
4882         }
4883         cancelInputsAndStartExitTransition(options);
4884     }
4885 
4886     /**
4887      * @hide
4888      */
4889     @Override
canStartActivityForResult()4890     public boolean canStartActivityForResult() {
4891         return true;
4892     }
4893 
4894     /**
4895      * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
4896      * int, Intent, int, int, int, Bundle)} with no options.
4897      */
startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)4898     public void startIntentSenderFromChild(Activity child, IntentSender intent,
4899             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4900             int extraFlags)
4901             throws IntentSender.SendIntentException {
4902         startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
4903                 flagsMask, flagsValues, extraFlags, null);
4904     }
4905 
4906     /**
4907      * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
4908      * taking a IntentSender; see
4909      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4910      * for more information.
4911      */
startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options)4912     public void startIntentSenderFromChild(Activity child, IntentSender intent,
4913             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4914             int extraFlags, @Nullable Bundle options)
4915             throws IntentSender.SendIntentException {
4916         startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
4917                 flagsMask, flagsValues, options);
4918     }
4919 
4920     /**
4921      * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see
4922      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4923      * for more information.
4924      *
4925      * @hide
4926      */
startIntentSenderFromChildFragment(Fragment child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options)4927     public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent,
4928             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4929             int extraFlags, @Nullable Bundle options)
4930             throws IntentSender.SendIntentException {
4931         startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent,
4932                 flagsMask, flagsValues, options);
4933     }
4934 
4935     /**
4936      * Call immediately after one of the flavors of {@link #startActivity(Intent)}
4937      * or {@link #finish} to specify an explicit transition animation to
4938      * perform next.
4939      *
4940      * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4941      * to using this with starting activities is to supply the desired animation
4942      * information through a {@link ActivityOptions} bundle to
4943      * {@link #startActivity(Intent, Bundle)} or a related function.  This allows
4944      * you to specify a custom animation even when starting an activity from
4945      * outside the context of the current top activity.
4946      *
4947      * @param enterAnim A resource ID of the animation resource to use for
4948      * the incoming activity.  Use 0 for no animation.
4949      * @param exitAnim A resource ID of the animation resource to use for
4950      * the outgoing activity.  Use 0 for no animation.
4951      */
overridePendingTransition(int enterAnim, int exitAnim)4952     public void overridePendingTransition(int enterAnim, int exitAnim) {
4953         try {
4954             ActivityManagerNative.getDefault().overridePendingTransition(
4955                     mToken, getPackageName(), enterAnim, exitAnim);
4956         } catch (RemoteException e) {
4957         }
4958     }
4959 
4960     /**
4961      * Call this to set the result that your activity will return to its
4962      * caller.
4963      *
4964      * @param resultCode The result code to propagate back to the originating
4965      *                   activity, often RESULT_CANCELED or RESULT_OK
4966      *
4967      * @see #RESULT_CANCELED
4968      * @see #RESULT_OK
4969      * @see #RESULT_FIRST_USER
4970      * @see #setResult(int, Intent)
4971      */
setResult(int resultCode)4972     public final void setResult(int resultCode) {
4973         synchronized (this) {
4974             mResultCode = resultCode;
4975             mResultData = null;
4976         }
4977     }
4978 
4979     /**
4980      * Call this to set the result that your activity will return to its
4981      * caller.
4982      *
4983      * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4984      * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4985      * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4986      * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set.  This will grant the
4987      * Activity receiving the result access to the specific URIs in the Intent.
4988      * Access will remain until the Activity has finished (it will remain across the hosting
4989      * process being killed and other temporary destruction) and will be added
4990      * to any existing set of URI permissions it already holds.
4991      *
4992      * @param resultCode The result code to propagate back to the originating
4993      *                   activity, often RESULT_CANCELED or RESULT_OK
4994      * @param data The data to propagate back to the originating activity.
4995      *
4996      * @see #RESULT_CANCELED
4997      * @see #RESULT_OK
4998      * @see #RESULT_FIRST_USER
4999      * @see #setResult(int)
5000      */
setResult(int resultCode, Intent data)5001     public final void setResult(int resultCode, Intent data) {
5002         synchronized (this) {
5003             mResultCode = resultCode;
5004             mResultData = data;
5005         }
5006     }
5007 
5008     /**
5009      * Return information about who launched this activity.  If the launching Intent
5010      * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
5011      * that will be returned as-is; otherwise, if known, an
5012      * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
5013      * package name that started the Intent will be returned.  This may return null if no
5014      * referrer can be identified -- it is neither explicitly specified, nor is it known which
5015      * application package was involved.
5016      *
5017      * <p>If called while inside the handling of {@link #onNewIntent}, this function will
5018      * return the referrer that submitted that new intent to the activity.  Otherwise, it
5019      * always returns the referrer of the original Intent.</p>
5020      *
5021      * <p>Note that this is <em>not</em> a security feature -- you can not trust the
5022      * referrer information, applications can spoof it.</p>
5023      */
5024     @Nullable
getReferrer()5025     public Uri getReferrer() {
5026         Intent intent = getIntent();
5027         try {
5028             Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
5029             if (referrer != null) {
5030                 return referrer;
5031             }
5032             String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
5033             if (referrerName != null) {
5034                 return Uri.parse(referrerName);
5035             }
5036         } catch (BadParcelableException e) {
5037             Log.w(TAG, "Cannot read referrer from intent;"
5038                     + " intent extras contain unknown custom Parcelable objects");
5039         }
5040         if (mReferrer != null) {
5041             return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
5042         }
5043         return null;
5044     }
5045 
5046     /**
5047      * Override to generate the desired referrer for the content currently being shown
5048      * by the app.  The default implementation returns null, meaning the referrer will simply
5049      * be the android-app: of the package name of this activity.  Return a non-null Uri to
5050      * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
5051      */
onProvideReferrer()5052     public Uri onProvideReferrer() {
5053         return null;
5054     }
5055 
5056     /**
5057      * Return the name of the package that invoked this activity.  This is who
5058      * the data in {@link #setResult setResult()} will be sent to.  You can
5059      * use this information to validate that the recipient is allowed to
5060      * receive the data.
5061      *
5062      * <p class="note">Note: if the calling activity is not expecting a result (that is it
5063      * did not use the {@link #startActivityForResult}
5064      * form that includes a request code), then the calling package will be
5065      * null.</p>
5066      *
5067      * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
5068      * the result from this method was unstable.  If the process hosting the calling
5069      * package was no longer running, it would return null instead of the proper package
5070      * name.  You can use {@link #getCallingActivity()} and retrieve the package name
5071      * from that instead.</p>
5072      *
5073      * @return The package of the activity that will receive your
5074      *         reply, or null if none.
5075      */
5076     @Nullable
getCallingPackage()5077     public String getCallingPackage() {
5078         try {
5079             return ActivityManagerNative.getDefault().getCallingPackage(mToken);
5080         } catch (RemoteException e) {
5081             return null;
5082         }
5083     }
5084 
5085     /**
5086      * Return the name of the activity that invoked this activity.  This is
5087      * who the data in {@link #setResult setResult()} will be sent to.  You
5088      * can use this information to validate that the recipient is allowed to
5089      * receive the data.
5090      *
5091      * <p class="note">Note: if the calling activity is not expecting a result (that is it
5092      * did not use the {@link #startActivityForResult}
5093      * form that includes a request code), then the calling package will be
5094      * null.
5095      *
5096      * @return The ComponentName of the activity that will receive your
5097      *         reply, or null if none.
5098      */
5099     @Nullable
getCallingActivity()5100     public ComponentName getCallingActivity() {
5101         try {
5102             return ActivityManagerNative.getDefault().getCallingActivity(mToken);
5103         } catch (RemoteException e) {
5104             return null;
5105         }
5106     }
5107 
5108     /**
5109      * Control whether this activity's main window is visible.  This is intended
5110      * only for the special case of an activity that is not going to show a
5111      * UI itself, but can't just finish prior to onResume() because it needs
5112      * to wait for a service binding or such.  Setting this to false allows
5113      * you to prevent your UI from being shown during that time.
5114      *
5115      * <p>The default value for this is taken from the
5116      * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
5117      */
setVisible(boolean visible)5118     public void setVisible(boolean visible) {
5119         if (mVisibleFromClient != visible) {
5120             mVisibleFromClient = visible;
5121             if (mVisibleFromServer) {
5122                 if (visible) makeVisible();
5123                 else mDecor.setVisibility(View.INVISIBLE);
5124             }
5125         }
5126     }
5127 
makeVisible()5128     void makeVisible() {
5129         if (!mWindowAdded) {
5130             ViewManager wm = getWindowManager();
5131             wm.addView(mDecor, getWindow().getAttributes());
5132             mWindowAdded = true;
5133         }
5134         mDecor.setVisibility(View.VISIBLE);
5135     }
5136 
5137     /**
5138      * Check to see whether this activity is in the process of finishing,
5139      * either because you called {@link #finish} on it or someone else
5140      * has requested that it finished.  This is often used in
5141      * {@link #onPause} to determine whether the activity is simply pausing or
5142      * completely finishing.
5143      *
5144      * @return If the activity is finishing, returns true; else returns false.
5145      *
5146      * @see #finish
5147      */
isFinishing()5148     public boolean isFinishing() {
5149         return mFinished;
5150     }
5151 
5152     /**
5153      * Returns true if the final {@link #onDestroy()} call has been made
5154      * on the Activity, so this instance is now dead.
5155      */
isDestroyed()5156     public boolean isDestroyed() {
5157         return mDestroyed;
5158     }
5159 
5160     /**
5161      * Check to see whether this activity is in the process of being destroyed in order to be
5162      * recreated with a new configuration. This is often used in
5163      * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
5164      * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
5165      *
5166      * @return If the activity is being torn down in order to be recreated with a new configuration,
5167      * returns true; else returns false.
5168      */
isChangingConfigurations()5169     public boolean isChangingConfigurations() {
5170         return mChangingConfigurations;
5171     }
5172 
5173     /**
5174      * Cause this Activity to be recreated with a new instance.  This results
5175      * in essentially the same flow as when the Activity is created due to
5176      * a configuration change -- the current instance will go through its
5177      * lifecycle to {@link #onDestroy} and a new instance then created after it.
5178      */
recreate()5179     public void recreate() {
5180         if (mParent != null) {
5181             throw new IllegalStateException("Can only be called on top-level activity");
5182         }
5183         if (Looper.myLooper() != mMainThread.getLooper()) {
5184             throw new IllegalStateException("Must be called from main thread");
5185         }
5186         mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false,
5187                 false /* preserveWindow */);
5188     }
5189 
5190     /**
5191      * Finishes the current activity and specifies whether to remove the task associated with this
5192      * activity.
5193      */
finish(int finishTask)5194     private void finish(int finishTask) {
5195         if (mParent == null) {
5196             int resultCode;
5197             Intent resultData;
5198             synchronized (this) {
5199                 resultCode = mResultCode;
5200                 resultData = mResultData;
5201             }
5202             if (false) Log.v(TAG, "Finishing self: token=" + mToken);
5203             try {
5204                 if (resultData != null) {
5205                     resultData.prepareToLeaveProcess(this);
5206                 }
5207                 if (ActivityManagerNative.getDefault()
5208                         .finishActivity(mToken, resultCode, resultData, finishTask)) {
5209                     mFinished = true;
5210                 }
5211             } catch (RemoteException e) {
5212                 // Empty
5213             }
5214         } else {
5215             mParent.finishFromChild(this);
5216         }
5217     }
5218 
5219     /**
5220      * Call this when your activity is done and should be closed.  The
5221      * ActivityResult is propagated back to whoever launched you via
5222      * onActivityResult().
5223      */
finish()5224     public void finish() {
5225         finish(DONT_FINISH_TASK_WITH_ACTIVITY);
5226     }
5227 
5228     /**
5229      * Finish this activity as well as all activities immediately below it
5230      * in the current task that have the same affinity.  This is typically
5231      * used when an application can be launched on to another task (such as
5232      * from an ACTION_VIEW of a content type it understands) and the user
5233      * has used the up navigation to switch out of the current task and in
5234      * to its own task.  In this case, if the user has navigated down into
5235      * any other activities of the second application, all of those should
5236      * be removed from the original task as part of the task switch.
5237      *
5238      * <p>Note that this finish does <em>not</em> allow you to deliver results
5239      * to the previous activity, and an exception will be thrown if you are trying
5240      * to do so.</p>
5241      */
finishAffinity()5242     public void finishAffinity() {
5243         if (mParent != null) {
5244             throw new IllegalStateException("Can not be called from an embedded activity");
5245         }
5246         if (mResultCode != RESULT_CANCELED || mResultData != null) {
5247             throw new IllegalStateException("Can not be called to deliver a result");
5248         }
5249         try {
5250             if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
5251                 mFinished = true;
5252             }
5253         } catch (RemoteException e) {
5254             // Empty
5255         }
5256     }
5257 
5258     /**
5259      * This is called when a child activity of this one calls its
5260      * {@link #finish} method.  The default implementation simply calls
5261      * finish() on this activity (the parent), finishing the entire group.
5262      *
5263      * @param child The activity making the call.
5264      *
5265      * @see #finish
5266      */
finishFromChild(Activity child)5267     public void finishFromChild(Activity child) {
5268         finish();
5269     }
5270 
5271     /**
5272      * Reverses the Activity Scene entry Transition and triggers the calling Activity
5273      * to reverse its exit Transition. When the exit Transition completes,
5274      * {@link #finish()} is called. If no entry Transition was used, finish() is called
5275      * immediately and the Activity exit Transition is run.
5276      * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
5277      */
finishAfterTransition()5278     public void finishAfterTransition() {
5279         if (!mActivityTransitionState.startExitBackTransition(this)) {
5280             finish();
5281         }
5282     }
5283 
5284     /**
5285      * Force finish another activity that you had previously started with
5286      * {@link #startActivityForResult}.
5287      *
5288      * @param requestCode The request code of the activity that you had
5289      *                    given to startActivityForResult().  If there are multiple
5290      *                    activities started with this request code, they
5291      *                    will all be finished.
5292      */
finishActivity(int requestCode)5293     public void finishActivity(int requestCode) {
5294         if (mParent == null) {
5295             try {
5296                 ActivityManagerNative.getDefault()
5297                     .finishSubActivity(mToken, mEmbeddedID, requestCode);
5298             } catch (RemoteException e) {
5299                 // Empty
5300             }
5301         } else {
5302             mParent.finishActivityFromChild(this, requestCode);
5303         }
5304     }
5305 
5306     /**
5307      * This is called when a child activity of this one calls its
5308      * finishActivity().
5309      *
5310      * @param child The activity making the call.
5311      * @param requestCode Request code that had been used to start the
5312      *                    activity.
5313      */
finishActivityFromChild(@onNull Activity child, int requestCode)5314     public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
5315         try {
5316             ActivityManagerNative.getDefault()
5317                 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
5318         } catch (RemoteException e) {
5319             // Empty
5320         }
5321     }
5322 
5323     /**
5324      * Call this when your activity is done and should be closed and the task should be completely
5325      * removed as a part of finishing the root activity of the task.
5326      */
finishAndRemoveTask()5327     public void finishAndRemoveTask() {
5328         finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
5329     }
5330 
5331     /**
5332      * Ask that the local app instance of this activity be released to free up its memory.
5333      * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5334      * a new instance of the activity will later be re-created if needed due to the user
5335      * navigating back to it.
5336      *
5337      * @return Returns true if the activity was in a state that it has started the process
5338      * of destroying its current instance; returns false if for any reason this could not
5339      * be done: it is currently visible to the user, it is already being destroyed, it is
5340      * being finished, it hasn't yet saved its state, etc.
5341      */
releaseInstance()5342     public boolean releaseInstance() {
5343         try {
5344             return ActivityManagerNative.getDefault().releaseActivityInstance(mToken);
5345         } catch (RemoteException e) {
5346             // Empty
5347         }
5348         return false;
5349     }
5350 
5351     /**
5352      * Called when an activity you launched exits, giving you the requestCode
5353      * you started it with, the resultCode it returned, and any additional
5354      * data from it.  The <var>resultCode</var> will be
5355      * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5356      * didn't return any result, or crashed during its operation.
5357      *
5358      * <p>You will receive this call immediately before onResume() when your
5359      * activity is re-starting.
5360      *
5361      * <p>This method is never invoked if your activity sets
5362      * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5363      * <code>true</code>.
5364      *
5365      * @param requestCode The integer request code originally supplied to
5366      *                    startActivityForResult(), allowing you to identify who this
5367      *                    result came from.
5368      * @param resultCode The integer result code returned by the child activity
5369      *                   through its setResult().
5370      * @param data An Intent, which can return result data to the caller
5371      *               (various data can be attached to Intent "extras").
5372      *
5373      * @see #startActivityForResult
5374      * @see #createPendingResult
5375      * @see #setResult(int)
5376      */
onActivityResult(int requestCode, int resultCode, Intent data)5377     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5378     }
5379 
5380     /**
5381      * Called when an activity you launched with an activity transition exposes this
5382      * Activity through a returning activity transition, giving you the resultCode
5383      * and any additional data from it. This method will only be called if the activity
5384      * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5385      * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5386      *
5387      * <p>The purpose of this function is to let the called Activity send a hint about
5388      * its state so that this underlying Activity can prepare to be exposed. A call to
5389      * this method does not guarantee that the called Activity has or will be exiting soon.
5390      * It only indicates that it will expose this Activity's Window and it has
5391      * some data to pass to prepare it.</p>
5392      *
5393      * @param resultCode The integer result code returned by the child activity
5394      *                   through its setResult().
5395      * @param data An Intent, which can return result data to the caller
5396      *               (various data can be attached to Intent "extras").
5397      */
onActivityReenter(int resultCode, Intent data)5398     public void onActivityReenter(int resultCode, Intent data) {
5399     }
5400 
5401     /**
5402      * Create a new PendingIntent object which you can hand to others
5403      * for them to use to send result data back to your
5404      * {@link #onActivityResult} callback.  The created object will be either
5405      * one-shot (becoming invalid after a result is sent back) or multiple
5406      * (allowing any number of results to be sent through it).
5407      *
5408      * @param requestCode Private request code for the sender that will be
5409      * associated with the result data when it is returned.  The sender can not
5410      * modify this value, allowing you to identify incoming results.
5411      * @param data Default data to supply in the result, which may be modified
5412      * by the sender.
5413      * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5414      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5415      * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5416      * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5417      * or any of the flags as supported by
5418      * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5419      * of the intent that can be supplied when the actual send happens.
5420      *
5421      * @return Returns an existing or new PendingIntent matching the given
5422      * parameters.  May return null only if
5423      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5424      * supplied.
5425      *
5426      * @see PendingIntent
5427      */
createPendingResult(int requestCode, @NonNull Intent data, @PendingIntent.Flags int flags)5428     public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5429             @PendingIntent.Flags int flags) {
5430         String packageName = getPackageName();
5431         try {
5432             data.prepareToLeaveProcess(this);
5433             IIntentSender target =
5434                 ActivityManagerNative.getDefault().getIntentSender(
5435                         ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5436                         mParent == null ? mToken : mParent.mToken,
5437                         mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5438                         UserHandle.myUserId());
5439             return target != null ? new PendingIntent(target) : null;
5440         } catch (RemoteException e) {
5441             // Empty
5442         }
5443         return null;
5444     }
5445 
5446     /**
5447      * Change the desired orientation of this activity.  If the activity
5448      * is currently in the foreground or otherwise impacting the screen
5449      * orientation, the screen will immediately be changed (possibly causing
5450      * the activity to be restarted). Otherwise, this will be used the next
5451      * time the activity is visible.
5452      *
5453      * @param requestedOrientation An orientation constant as used in
5454      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5455      */
setRequestedOrientation(@ctivityInfo.ScreenOrientation int requestedOrientation)5456     public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5457         if (mParent == null) {
5458             try {
5459                 ActivityManagerNative.getDefault().setRequestedOrientation(
5460                         mToken, requestedOrientation);
5461             } catch (RemoteException e) {
5462                 // Empty
5463             }
5464         } else {
5465             mParent.setRequestedOrientation(requestedOrientation);
5466         }
5467     }
5468 
5469     /**
5470      * Return the current requested orientation of the activity.  This will
5471      * either be the orientation requested in its component's manifest, or
5472      * the last requested orientation given to
5473      * {@link #setRequestedOrientation(int)}.
5474      *
5475      * @return Returns an orientation constant as used in
5476      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5477      */
5478     @ActivityInfo.ScreenOrientation
getRequestedOrientation()5479     public int getRequestedOrientation() {
5480         if (mParent == null) {
5481             try {
5482                 return ActivityManagerNative.getDefault()
5483                         .getRequestedOrientation(mToken);
5484             } catch (RemoteException e) {
5485                 // Empty
5486             }
5487         } else {
5488             return mParent.getRequestedOrientation();
5489         }
5490         return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5491     }
5492 
5493     /**
5494      * Return the identifier of the task this activity is in.  This identifier
5495      * will remain the same for the lifetime of the activity.
5496      *
5497      * @return Task identifier, an opaque integer.
5498      */
getTaskId()5499     public int getTaskId() {
5500         try {
5501             return ActivityManagerNative.getDefault()
5502                 .getTaskForActivity(mToken, false);
5503         } catch (RemoteException e) {
5504             return -1;
5505         }
5506     }
5507 
5508     /**
5509      * Return whether this activity is the root of a task.  The root is the
5510      * first activity in a task.
5511      *
5512      * @return True if this is the root activity, else false.
5513      */
isTaskRoot()5514     public boolean isTaskRoot() {
5515         try {
5516             return ActivityManagerNative.getDefault().getTaskForActivity(mToken, true) >= 0;
5517         } catch (RemoteException e) {
5518             return false;
5519         }
5520     }
5521 
5522     /**
5523      * Move the task containing this activity to the back of the activity
5524      * stack.  The activity's order within the task is unchanged.
5525      *
5526      * @param nonRoot If false then this only works if the activity is the root
5527      *                of a task; if true it will work for any activity in
5528      *                a task.
5529      *
5530      * @return If the task was moved (or it was already at the
5531      *         back) true is returned, else false.
5532      */
moveTaskToBack(boolean nonRoot)5533     public boolean moveTaskToBack(boolean nonRoot) {
5534         try {
5535             return ActivityManagerNative.getDefault().moveActivityTaskToBack(
5536                     mToken, nonRoot);
5537         } catch (RemoteException e) {
5538             // Empty
5539         }
5540         return false;
5541     }
5542 
5543     /**
5544      * Returns class name for this activity with the package prefix removed.
5545      * This is the default name used to read and write settings.
5546      *
5547      * @return The local class name.
5548      */
5549     @NonNull
getLocalClassName()5550     public String getLocalClassName() {
5551         final String pkg = getPackageName();
5552         final String cls = mComponent.getClassName();
5553         int packageLen = pkg.length();
5554         if (!cls.startsWith(pkg) || cls.length() <= packageLen
5555                 || cls.charAt(packageLen) != '.') {
5556             return cls;
5557         }
5558         return cls.substring(packageLen+1);
5559     }
5560 
5561     /**
5562      * Returns complete component name of this activity.
5563      *
5564      * @return Returns the complete component name for this activity
5565      */
getComponentName()5566     public ComponentName getComponentName()
5567     {
5568         return mComponent;
5569     }
5570 
5571     /**
5572      * Retrieve a {@link SharedPreferences} object for accessing preferences
5573      * that are private to this activity.  This simply calls the underlying
5574      * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5575      * class name as the preferences name.
5576      *
5577      * @param mode Operating mode.  Use {@link #MODE_PRIVATE} for the default
5578      *             operation.
5579      *
5580      * @return Returns the single SharedPreferences instance that can be used
5581      *         to retrieve and modify the preference values.
5582      */
getPreferences(int mode)5583     public SharedPreferences getPreferences(int mode) {
5584         return getSharedPreferences(getLocalClassName(), mode);
5585     }
5586 
ensureSearchManager()5587     private void ensureSearchManager() {
5588         if (mSearchManager != null) {
5589             return;
5590         }
5591 
5592         mSearchManager = new SearchManager(this, null);
5593     }
5594 
5595     @Override
getSystemService(@erviceName @onNull String name)5596     public Object getSystemService(@ServiceName @NonNull String name) {
5597         if (getBaseContext() == null) {
5598             throw new IllegalStateException(
5599                     "System services not available to Activities before onCreate()");
5600         }
5601 
5602         if (WINDOW_SERVICE.equals(name)) {
5603             return mWindowManager;
5604         } else if (SEARCH_SERVICE.equals(name)) {
5605             ensureSearchManager();
5606             return mSearchManager;
5607         }
5608         return super.getSystemService(name);
5609     }
5610 
5611     /**
5612      * Change the title associated with this activity.  If this is a
5613      * top-level activity, the title for its window will change.  If it
5614      * is an embedded activity, the parent can do whatever it wants
5615      * with it.
5616      */
setTitle(CharSequence title)5617     public void setTitle(CharSequence title) {
5618         mTitle = title;
5619         onTitleChanged(title, mTitleColor);
5620 
5621         if (mParent != null) {
5622             mParent.onChildTitleChanged(this, title);
5623         }
5624     }
5625 
5626     /**
5627      * Change the title associated with this activity.  If this is a
5628      * top-level activity, the title for its window will change.  If it
5629      * is an embedded activity, the parent can do whatever it wants
5630      * with it.
5631      */
setTitle(int titleId)5632     public void setTitle(int titleId) {
5633         setTitle(getText(titleId));
5634     }
5635 
5636     /**
5637      * Change the color of the title associated with this activity.
5638      * <p>
5639      * This method is deprecated starting in API Level 11 and replaced by action
5640      * bar styles. For information on styling the Action Bar, read the <a
5641      * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5642      * guide.
5643      *
5644      * @deprecated Use action bar styles instead.
5645      */
5646     @Deprecated
setTitleColor(int textColor)5647     public void setTitleColor(int textColor) {
5648         mTitleColor = textColor;
5649         onTitleChanged(mTitle, textColor);
5650     }
5651 
getTitle()5652     public final CharSequence getTitle() {
5653         return mTitle;
5654     }
5655 
getTitleColor()5656     public final int getTitleColor() {
5657         return mTitleColor;
5658     }
5659 
onTitleChanged(CharSequence title, int color)5660     protected void onTitleChanged(CharSequence title, int color) {
5661         if (mTitleReady) {
5662             final Window win = getWindow();
5663             if (win != null) {
5664                 win.setTitle(title);
5665                 if (color != 0) {
5666                     win.setTitleColor(color);
5667                 }
5668             }
5669             if (mActionBar != null) {
5670                 mActionBar.setWindowTitle(title);
5671             }
5672         }
5673     }
5674 
onChildTitleChanged(Activity childActivity, CharSequence title)5675     protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5676     }
5677 
5678     /**
5679      * Sets information describing the task with this activity for presentation inside the Recents
5680      * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5681      * are traversed in order from the topmost activity to the bottommost. The traversal continues
5682      * for each property until a suitable value is found. For each task the taskDescription will be
5683      * returned in {@link android.app.ActivityManager.TaskDescription}.
5684      *
5685      * @see ActivityManager#getRecentTasks
5686      * @see android.app.ActivityManager.TaskDescription
5687      *
5688      * @param taskDescription The TaskDescription properties that describe the task with this activity
5689      */
setTaskDescription(ActivityManager.TaskDescription taskDescription)5690     public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5691         if (mTaskDescription != taskDescription) {
5692             mTaskDescription.copyFrom(taskDescription);
5693             // Scale the icon down to something reasonable if it is provided
5694             if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5695                 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5696                 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
5697                         true);
5698                 mTaskDescription.setIcon(icon);
5699             }
5700         }
5701         try {
5702             ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription);
5703         } catch (RemoteException e) {
5704         }
5705     }
5706 
5707     /**
5708      * Sets the visibility of the progress bar in the title.
5709      * <p>
5710      * In order for the progress bar to be shown, the feature must be requested
5711      * via {@link #requestWindowFeature(int)}.
5712      *
5713      * @param visible Whether to show the progress bars in the title.
5714      * @deprecated No longer supported starting in API 21.
5715      */
5716     @Deprecated
setProgressBarVisibility(boolean visible)5717     public final void setProgressBarVisibility(boolean visible) {
5718         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
5719             Window.PROGRESS_VISIBILITY_OFF);
5720     }
5721 
5722     /**
5723      * Sets the visibility of the indeterminate progress bar in the title.
5724      * <p>
5725      * In order for the progress bar to be shown, the feature must be requested
5726      * via {@link #requestWindowFeature(int)}.
5727      *
5728      * @param visible Whether to show the progress bars in the title.
5729      * @deprecated No longer supported starting in API 21.
5730      */
5731     @Deprecated
setProgressBarIndeterminateVisibility(boolean visible)5732     public final void setProgressBarIndeterminateVisibility(boolean visible) {
5733         getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
5734                 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
5735     }
5736 
5737     /**
5738      * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
5739      * is always indeterminate).
5740      * <p>
5741      * In order for the progress bar to be shown, the feature must be requested
5742      * via {@link #requestWindowFeature(int)}.
5743      *
5744      * @param indeterminate Whether the horizontal progress bar should be indeterminate.
5745      * @deprecated No longer supported starting in API 21.
5746      */
5747     @Deprecated
setProgressBarIndeterminate(boolean indeterminate)5748     public final void setProgressBarIndeterminate(boolean indeterminate) {
5749         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5750                 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
5751                         : Window.PROGRESS_INDETERMINATE_OFF);
5752     }
5753 
5754     /**
5755      * Sets the progress for the progress bars in the title.
5756      * <p>
5757      * In order for the progress bar to be shown, the feature must be requested
5758      * via {@link #requestWindowFeature(int)}.
5759      *
5760      * @param progress The progress for the progress bar. Valid ranges are from
5761      *            0 to 10000 (both inclusive). If 10000 is given, the progress
5762      *            bar will be completely filled and will fade out.
5763      * @deprecated No longer supported starting in API 21.
5764      */
5765     @Deprecated
setProgress(int progress)5766     public final void setProgress(int progress) {
5767         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
5768     }
5769 
5770     /**
5771      * Sets the secondary progress for the progress bar in the title. This
5772      * progress is drawn between the primary progress (set via
5773      * {@link #setProgress(int)} and the background. It can be ideal for media
5774      * scenarios such as showing the buffering progress while the default
5775      * progress shows the play progress.
5776      * <p>
5777      * In order for the progress bar to be shown, the feature must be requested
5778      * via {@link #requestWindowFeature(int)}.
5779      *
5780      * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
5781      *            0 to 10000 (both inclusive).
5782      * @deprecated No longer supported starting in API 21.
5783      */
5784     @Deprecated
setSecondaryProgress(int secondaryProgress)5785     public final void setSecondaryProgress(int secondaryProgress) {
5786         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5787                 secondaryProgress + Window.PROGRESS_SECONDARY_START);
5788     }
5789 
5790     /**
5791      * Suggests an audio stream whose volume should be changed by the hardware
5792      * volume controls.
5793      * <p>
5794      * The suggested audio stream will be tied to the window of this Activity.
5795      * Volume requests which are received while the Activity is in the
5796      * foreground will affect this stream.
5797      * <p>
5798      * It is not guaranteed that the hardware volume controls will always change
5799      * this stream's volume (for example, if a call is in progress, its stream's
5800      * volume may be changed instead). To reset back to the default, use
5801      * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
5802      *
5803      * @param streamType The type of the audio stream whose volume should be
5804      *            changed by the hardware volume controls.
5805      */
setVolumeControlStream(int streamType)5806     public final void setVolumeControlStream(int streamType) {
5807         getWindow().setVolumeControlStream(streamType);
5808     }
5809 
5810     /**
5811      * Gets the suggested audio stream whose volume should be changed by the
5812      * hardware volume controls.
5813      *
5814      * @return The suggested audio stream type whose volume should be changed by
5815      *         the hardware volume controls.
5816      * @see #setVolumeControlStream(int)
5817      */
getVolumeControlStream()5818     public final int getVolumeControlStream() {
5819         return getWindow().getVolumeControlStream();
5820     }
5821 
5822     /**
5823      * Sets a {@link MediaController} to send media keys and volume changes to.
5824      * <p>
5825      * The controller will be tied to the window of this Activity. Media key and
5826      * volume events which are received while the Activity is in the foreground
5827      * will be forwarded to the controller and used to invoke transport controls
5828      * or adjust the volume. This may be used instead of or in addition to
5829      * {@link #setVolumeControlStream} to affect a specific session instead of a
5830      * specific stream.
5831      * <p>
5832      * It is not guaranteed that the hardware volume controls will always change
5833      * this session's volume (for example, if a call is in progress, its
5834      * stream's volume may be changed instead). To reset back to the default use
5835      * null as the controller.
5836      *
5837      * @param controller The controller for the session which should receive
5838      *            media keys and volume changes.
5839      */
setMediaController(MediaController controller)5840     public final void setMediaController(MediaController controller) {
5841         getWindow().setMediaController(controller);
5842     }
5843 
5844     /**
5845      * Gets the controller which should be receiving media key and volume events
5846      * while this activity is in the foreground.
5847      *
5848      * @return The controller which should receive events.
5849      * @see #setMediaController(android.media.session.MediaController)
5850      */
getMediaController()5851     public final MediaController getMediaController() {
5852         return getWindow().getMediaController();
5853     }
5854 
5855     /**
5856      * Runs the specified action on the UI thread. If the current thread is the UI
5857      * thread, then the action is executed immediately. If the current thread is
5858      * not the UI thread, the action is posted to the event queue of the UI thread.
5859      *
5860      * @param action the action to run on the UI thread
5861      */
runOnUiThread(Runnable action)5862     public final void runOnUiThread(Runnable action) {
5863         if (Thread.currentThread() != mUiThread) {
5864             mHandler.post(action);
5865         } else {
5866             action.run();
5867         }
5868     }
5869 
5870     /**
5871      * Standard implementation of
5872      * {@link android.view.LayoutInflater.Factory#onCreateView} used when
5873      * inflating with the LayoutInflater returned by {@link #getSystemService}.
5874      * This implementation does nothing and is for
5875      * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps.  Newer apps
5876      * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
5877      *
5878      * @see android.view.LayoutInflater#createView
5879      * @see android.view.Window#getLayoutInflater
5880      */
5881     @Nullable
onCreateView(String name, Context context, AttributeSet attrs)5882     public View onCreateView(String name, Context context, AttributeSet attrs) {
5883         return null;
5884     }
5885 
5886     /**
5887      * Standard implementation of
5888      * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
5889      * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
5890      * This implementation handles <fragment> tags to embed fragments inside
5891      * of the activity.
5892      *
5893      * @see android.view.LayoutInflater#createView
5894      * @see android.view.Window#getLayoutInflater
5895      */
onCreateView(View parent, String name, Context context, AttributeSet attrs)5896     public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
5897         if (!"fragment".equals(name)) {
5898             return onCreateView(name, context, attrs);
5899         }
5900 
5901         return mFragments.onCreateView(parent, name, context, attrs);
5902     }
5903 
5904     /**
5905      * Print the Activity's state into the given stream.  This gets invoked if
5906      * you run "adb shell dumpsys activity &lt;activity_component_name&gt;".
5907      *
5908      * @param prefix Desired prefix to prepend at each line of output.
5909      * @param fd The raw file descriptor that the dump is being sent to.
5910      * @param writer The PrintWriter to which you should dump your state.  This will be
5911      * closed for you after you return.
5912      * @param args additional arguments to the dump request.
5913      */
dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)5914     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5915         dumpInner(prefix, fd, writer, args);
5916     }
5917 
dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)5918     void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5919         writer.print(prefix); writer.print("Local Activity ");
5920                 writer.print(Integer.toHexString(System.identityHashCode(this)));
5921                 writer.println(" State:");
5922         String innerPrefix = prefix + "  ";
5923         writer.print(innerPrefix); writer.print("mResumed=");
5924                 writer.print(mResumed); writer.print(" mStopped=");
5925                 writer.print(mStopped); writer.print(" mFinished=");
5926                 writer.println(mFinished);
5927         writer.print(innerPrefix); writer.print("mChangingConfigurations=");
5928                 writer.println(mChangingConfigurations);
5929         writer.print(innerPrefix); writer.print("mCurrentConfig=");
5930                 writer.println(mCurrentConfig);
5931 
5932         mFragments.dumpLoaders(innerPrefix, fd, writer, args);
5933         mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
5934         if (mVoiceInteractor != null) {
5935             mVoiceInteractor.dump(innerPrefix, fd, writer, args);
5936         }
5937 
5938         if (getWindow() != null &&
5939                 getWindow().peekDecorView() != null &&
5940                 getWindow().peekDecorView().getViewRootImpl() != null) {
5941             getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
5942         }
5943 
5944         mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
5945     }
5946 
5947     /**
5948      * Bit indicating that this activity is "immersive" and should not be
5949      * interrupted by notifications if possible.
5950      *
5951      * This value is initially set by the manifest property
5952      * <code>android:immersive</code> but may be changed at runtime by
5953      * {@link #setImmersive}.
5954      *
5955      * @see #setImmersive(boolean)
5956      * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5957      */
isImmersive()5958     public boolean isImmersive() {
5959         try {
5960             return ActivityManagerNative.getDefault().isImmersive(mToken);
5961         } catch (RemoteException e) {
5962             return false;
5963         }
5964     }
5965 
5966     /**
5967      * Indication of whether this is the highest level activity in this task. Can be used to
5968      * determine whether an activity launched by this activity was placed in the same task or
5969      * another task.
5970      *
5971      * @return true if this is the topmost, non-finishing activity in its task.
5972      */
isTopOfTask()5973     private boolean isTopOfTask() {
5974         if (mToken == null || mWindow == null) {
5975             return false;
5976         }
5977         try {
5978             return ActivityManagerNative.getDefault().isTopOfTask(getActivityToken());
5979         } catch (RemoteException e) {
5980             return false;
5981         }
5982     }
5983 
5984     /**
5985      * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
5986      * fullscreen opaque Activity.
5987      * <p>
5988      * Call this whenever the background of a translucent Activity has changed to become opaque.
5989      * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
5990      * <p>
5991      * This call has no effect on non-translucent activities or on activities with the
5992      * {@link android.R.attr#windowIsFloating} attribute.
5993      *
5994      * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
5995      * ActivityOptions)
5996      * @see TranslucentConversionListener
5997      *
5998      * @hide
5999      */
6000     @SystemApi
convertFromTranslucent()6001     public void convertFromTranslucent() {
6002         try {
6003             mTranslucentCallback = null;
6004             if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
6005                 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
6006             }
6007         } catch (RemoteException e) {
6008             // pass
6009         }
6010     }
6011 
6012     /**
6013      * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
6014      * opaque to translucent following a call to {@link #convertFromTranslucent()}.
6015      * <p>
6016      * Calling this allows the Activity behind this one to be seen again. Once all such Activities
6017      * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
6018      * be called indicating that it is safe to make this activity translucent again. Until
6019      * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
6020      * behind the frontmost Activity will be indeterminate.
6021      * <p>
6022      * This call has no effect on non-translucent activities or on activities with the
6023      * {@link android.R.attr#windowIsFloating} attribute.
6024      *
6025      * @param callback the method to call when all visible Activities behind this one have been
6026      * drawn and it is safe to make this Activity translucent again.
6027      * @param options activity options delivered to the activity below this one. The options
6028      * are retrieved using {@link #getActivityOptions}.
6029      * @return <code>true</code> if Window was opaque and will become translucent or
6030      * <code>false</code> if window was translucent and no change needed to be made.
6031      *
6032      * @see #convertFromTranslucent()
6033      * @see TranslucentConversionListener
6034      *
6035      * @hide
6036      */
6037     @SystemApi
convertToTranslucent(TranslucentConversionListener callback, ActivityOptions options)6038     public boolean convertToTranslucent(TranslucentConversionListener callback,
6039             ActivityOptions options) {
6040         boolean drawComplete;
6041         try {
6042             mTranslucentCallback = callback;
6043             mChangeCanvasToTranslucent =
6044                     ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
6045             WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6046             drawComplete = true;
6047         } catch (RemoteException e) {
6048             // Make callback return as though it timed out.
6049             mChangeCanvasToTranslucent = false;
6050             drawComplete = false;
6051         }
6052         if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
6053             // Window is already translucent.
6054             mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6055         }
6056         return mChangeCanvasToTranslucent;
6057     }
6058 
6059     /** @hide */
onTranslucentConversionComplete(boolean drawComplete)6060     void onTranslucentConversionComplete(boolean drawComplete) {
6061         if (mTranslucentCallback != null) {
6062             mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6063             mTranslucentCallback = null;
6064         }
6065         if (mChangeCanvasToTranslucent) {
6066             WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6067         }
6068     }
6069 
6070     /** @hide */
onNewActivityOptions(ActivityOptions options)6071     public void onNewActivityOptions(ActivityOptions options) {
6072         mActivityTransitionState.setEnterActivityOptions(this, options);
6073         if (!mStopped) {
6074             mActivityTransitionState.enterReady(this);
6075         }
6076     }
6077 
6078     /**
6079      * Retrieve the ActivityOptions passed in from the launching activity or passed back
6080      * from an activity launched by this activity in its call to {@link
6081      * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
6082      *
6083      * @return The ActivityOptions passed to {@link #convertToTranslucent}.
6084      * @hide
6085      */
getActivityOptions()6086     ActivityOptions getActivityOptions() {
6087         try {
6088             return ActivityManagerNative.getDefault().getActivityOptions(mToken);
6089         } catch (RemoteException e) {
6090         }
6091         return null;
6092     }
6093 
6094     /**
6095      * Activities that want to remain visible behind a translucent activity above them must call
6096      * this method anytime between the start of {@link #onResume()} and the return from
6097      * {@link #onPause()}. If this call is successful then the activity will remain visible after
6098      * {@link #onPause()} is called, and is allowed to continue playing media in the background.
6099      *
6100      * <p>The actions of this call are reset each time that this activity is brought to the
6101      * front. That is, every time {@link #onResume()} is called the activity will be assumed
6102      * to not have requested visible behind. Therefore, if you want this activity to continue to
6103      * be visible in the background you must call this method again.
6104      *
6105      * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
6106      * for dialog and translucent activities.
6107      *
6108      * <p>Under all circumstances, the activity must stop playing and release resources prior to or
6109      * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
6110      *
6111      * <p>False will be returned any time this method is called between the return of onPause and
6112      *      the next call to onResume.
6113      *
6114      * @param visible true to notify the system that the activity wishes to be visible behind other
6115      *                translucent activities, false to indicate otherwise. Resources must be
6116      *                released when passing false to this method.
6117      * @return the resulting visibiity state. If true the activity will remain visible beyond
6118      *      {@link #onPause()} if the next activity is translucent or not fullscreen. If false
6119      *      then the activity may not count on being visible behind other translucent activities,
6120      *      and must stop any media playback and release resources.
6121      *      Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
6122      *      the return value must be checked.
6123      *
6124      * @see #onVisibleBehindCanceled()
6125      */
requestVisibleBehind(boolean visible)6126     public boolean requestVisibleBehind(boolean visible) {
6127         if (!mResumed) {
6128             // Do not permit paused or stopped activities to do this.
6129             visible = false;
6130         }
6131         try {
6132             mVisibleBehind = ActivityManagerNative.getDefault()
6133                     .requestVisibleBehind(mToken, visible) && visible;
6134         } catch (RemoteException e) {
6135             mVisibleBehind = false;
6136         }
6137         return mVisibleBehind;
6138     }
6139 
6140     /**
6141      * Called when a translucent activity over this activity is becoming opaque or another
6142      * activity is being launched. Activities that override this method must call
6143      * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
6144      *
6145      * <p>When this method is called the activity has 500 msec to release any resources it may be
6146      * using while visible in the background.
6147      * If the activity has not returned from this method in 500 msec the system will destroy
6148      * the activity and kill the process in order to recover the resources for another
6149      * process. Otherwise {@link #onStop()} will be called following return.
6150      *
6151      * @see #requestVisibleBehind(boolean)
6152      */
6153     @CallSuper
onVisibleBehindCanceled()6154     public void onVisibleBehindCanceled() {
6155         mCalled = true;
6156     }
6157 
6158     /**
6159      * Translucent activities may call this to determine if there is an activity below them that
6160      * is currently set to be visible in the background.
6161      *
6162      * @return true if an activity below is set to visible according to the most recent call to
6163      * {@link #requestVisibleBehind(boolean)}, false otherwise.
6164      *
6165      * @see #requestVisibleBehind(boolean)
6166      * @see #onVisibleBehindCanceled()
6167      * @see #onBackgroundVisibleBehindChanged(boolean)
6168      * @hide
6169      */
6170     @SystemApi
isBackgroundVisibleBehind()6171     public boolean isBackgroundVisibleBehind() {
6172         try {
6173             return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken);
6174         } catch (RemoteException e) {
6175         }
6176         return false;
6177     }
6178 
6179     /**
6180      * The topmost foreground activity will receive this call when the background visibility state
6181      * of the activity below it changes.
6182      *
6183      * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
6184      * due to a background activity finishing itself.
6185      *
6186      * @param visible true if a background activity is visible, false otherwise.
6187      *
6188      * @see #requestVisibleBehind(boolean)
6189      * @see #onVisibleBehindCanceled()
6190      * @hide
6191      */
6192     @SystemApi
onBackgroundVisibleBehindChanged(boolean visible)6193     public void onBackgroundVisibleBehindChanged(boolean visible) {
6194     }
6195 
6196     /**
6197      * Activities cannot draw during the period that their windows are animating in. In order
6198      * to know when it is safe to begin drawing they can override this method which will be
6199      * called when the entering animation has completed.
6200      */
onEnterAnimationComplete()6201     public void onEnterAnimationComplete() {
6202     }
6203 
6204     /**
6205      * @hide
6206      */
dispatchEnterAnimationComplete()6207     public void dispatchEnterAnimationComplete() {
6208         onEnterAnimationComplete();
6209         if (getWindow() != null && getWindow().getDecorView() != null) {
6210             getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
6211         }
6212     }
6213 
6214     /**
6215      * Adjust the current immersive mode setting.
6216      *
6217      * Note that changing this value will have no effect on the activity's
6218      * {@link android.content.pm.ActivityInfo} structure; that is, if
6219      * <code>android:immersive</code> is set to <code>true</code>
6220      * in the application's manifest entry for this activity, the {@link
6221      * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
6222      * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6223      * FLAG_IMMERSIVE} bit set.
6224      *
6225      * @see #isImmersive()
6226      * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6227      */
setImmersive(boolean i)6228     public void setImmersive(boolean i) {
6229         try {
6230             ActivityManagerNative.getDefault().setImmersive(mToken, i);
6231         } catch (RemoteException e) {
6232             // pass
6233         }
6234     }
6235 
6236     /**
6237      * Enable or disable virtual reality (VR) mode for this Activity.
6238      *
6239      * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
6240      * while this Activity has user focus.</p>
6241      *
6242      * <p>It is recommended that applications additionally declare
6243      * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
6244      * transitions when switching between VR activities.</p>
6245      *
6246      * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
6247      * VR mode will not be started.  Developers can handle this case as follows:</p>
6248      *
6249      * <pre>
6250      * String servicePackage = "com.whatever.app";
6251      * String serviceClass = "com.whatever.app.MyVrListenerService";
6252      *
6253      * // Name of the component of the VrListenerService to start.
6254      * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
6255      *
6256      * try {
6257      *    setVrModeEnabled(true, myComponentName);
6258      * } catch (PackageManager.NameNotFoundException e) {
6259      *        List&lt;ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
6260      *        boolean isInstalled = false;
6261      *        for (ApplicationInfo app : installed) {
6262      *            if (app.packageName.equals(servicePackage)) {
6263      *                isInstalled = true;
6264      *                break;
6265      *            }
6266      *        }
6267      *        if (isInstalled) {
6268      *            // Package is installed, but not enabled in Settings.  Let user enable it.
6269      *            startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
6270      *        } else {
6271      *            // Package is not installed.  Send an intent to download this.
6272      *            sentIntentToLaunchAppStore(servicePackage);
6273      *        }
6274      * }
6275      * </pre>
6276      *
6277      * @param enabled {@code true} to enable this mode.
6278      * @param requestedComponent the name of the component to use as a
6279      *        {@link android.service.vr.VrListenerService} while VR mode is enabled.
6280      *
6281      * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
6282      *    to run as a {@link android.service.vr.VrListenerService} is not installed, or has
6283      *    not been enabled in user settings.
6284      *
6285      * @see android.content.pm.PackageManager#FEATURE_VR_MODE
6286      * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
6287      * @see android.service.vr.VrListenerService
6288      * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
6289      * @see android.R.attr#enableVrMode
6290      */
setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)6291     public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
6292           throws PackageManager.NameNotFoundException {
6293         try {
6294             if (ActivityManagerNative.getDefault().setVrMode(mToken, enabled, requestedComponent)
6295                     != 0) {
6296                 throw new PackageManager.NameNotFoundException(
6297                         requestedComponent.flattenToString());
6298             }
6299         } catch (RemoteException e) {
6300             // pass
6301         }
6302     }
6303 
6304     /**
6305      * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
6306      *
6307      * @param callback Callback that will manage lifecycle events for this action mode
6308      * @return The ActionMode that was started, or null if it was canceled
6309      *
6310      * @see ActionMode
6311      */
6312     @Nullable
startActionMode(ActionMode.Callback callback)6313     public ActionMode startActionMode(ActionMode.Callback callback) {
6314         return mWindow.getDecorView().startActionMode(callback);
6315     }
6316 
6317     /**
6318      * Start an action mode of the given type.
6319      *
6320      * @param callback Callback that will manage lifecycle events for this action mode
6321      * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6322      * @return The ActionMode that was started, or null if it was canceled
6323      *
6324      * @see ActionMode
6325      */
6326     @Nullable
startActionMode(ActionMode.Callback callback, int type)6327     public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6328         return mWindow.getDecorView().startActionMode(callback, type);
6329     }
6330 
6331     /**
6332      * Give the Activity a chance to control the UI for an action mode requested
6333      * by the system.
6334      *
6335      * <p>Note: If you are looking for a notification callback that an action mode
6336      * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
6337      *
6338      * @param callback The callback that should control the new action mode
6339      * @return The new action mode, or <code>null</code> if the activity does not want to
6340      *         provide special handling for this action mode. (It will be handled by the system.)
6341      */
6342     @Nullable
6343     @Override
onWindowStartingActionMode(ActionMode.Callback callback)6344     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
6345         // Only Primary ActionModes are represented in the ActionBar.
6346         if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
6347             initWindowDecorActionBar();
6348             if (mActionBar != null) {
6349                 return mActionBar.startActionMode(callback);
6350             }
6351         }
6352         return null;
6353     }
6354 
6355     /**
6356      * {@inheritDoc}
6357      */
6358     @Nullable
6359     @Override
onWindowStartingActionMode(ActionMode.Callback callback, int type)6360     public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
6361         try {
6362             mActionModeTypeStarting = type;
6363             return onWindowStartingActionMode(callback);
6364         } finally {
6365             mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
6366         }
6367     }
6368 
6369     /**
6370      * Notifies the Activity that an action mode has been started.
6371      * Activity subclasses overriding this method should call the superclass implementation.
6372      *
6373      * @param mode The new action mode.
6374      */
6375     @CallSuper
6376     @Override
onActionModeStarted(ActionMode mode)6377     public void onActionModeStarted(ActionMode mode) {
6378     }
6379 
6380     /**
6381      * Notifies the activity that an action mode has finished.
6382      * Activity subclasses overriding this method should call the superclass implementation.
6383      *
6384      * @param mode The action mode that just finished.
6385      */
6386     @CallSuper
6387     @Override
onActionModeFinished(ActionMode mode)6388     public void onActionModeFinished(ActionMode mode) {
6389     }
6390 
6391     /**
6392      * Returns true if the app should recreate the task when navigating 'up' from this activity
6393      * by using targetIntent.
6394      *
6395      * <p>If this method returns false the app can trivially call
6396      * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
6397      * up navigation. If this method returns false, the app should synthesize a new task stack
6398      * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6399      *
6400      * @param targetIntent An intent representing the target destination for up navigation
6401      * @return true if navigating up should recreate a new task stack, false if the same task
6402      *         should be used for the destination
6403      */
shouldUpRecreateTask(Intent targetIntent)6404     public boolean shouldUpRecreateTask(Intent targetIntent) {
6405         try {
6406             PackageManager pm = getPackageManager();
6407             ComponentName cn = targetIntent.getComponent();
6408             if (cn == null) {
6409                 cn = targetIntent.resolveActivity(pm);
6410             }
6411             ActivityInfo info = pm.getActivityInfo(cn, 0);
6412             if (info.taskAffinity == null) {
6413                 return false;
6414             }
6415             return ActivityManagerNative.getDefault()
6416                     .shouldUpRecreateTask(mToken, info.taskAffinity);
6417         } catch (RemoteException e) {
6418             return false;
6419         } catch (NameNotFoundException e) {
6420             return false;
6421         }
6422     }
6423 
6424     /**
6425      * Navigate from this activity to the activity specified by upIntent, finishing this activity
6426      * in the process. If the activity indicated by upIntent already exists in the task's history,
6427      * this activity and all others before the indicated activity in the history stack will be
6428      * finished.
6429      *
6430      * <p>If the indicated activity does not appear in the history stack, this will finish
6431      * each activity in this task until the root activity of the task is reached, resulting in
6432      * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6433      * when an activity may be reached by a path not passing through a canonical parent
6434      * activity.</p>
6435      *
6436      * <p>This method should be used when performing up navigation from within the same task
6437      * as the destination. If up navigation should cross tasks in some cases, see
6438      * {@link #shouldUpRecreateTask(Intent)}.</p>
6439      *
6440      * @param upIntent An intent representing the target destination for up navigation
6441      *
6442      * @return true if up navigation successfully reached the activity indicated by upIntent and
6443      *         upIntent was delivered to it. false if an instance of the indicated activity could
6444      *         not be found and this activity was simply finished normally.
6445      */
navigateUpTo(Intent upIntent)6446     public boolean navigateUpTo(Intent upIntent) {
6447         if (mParent == null) {
6448             ComponentName destInfo = upIntent.getComponent();
6449             if (destInfo == null) {
6450                 destInfo = upIntent.resolveActivity(getPackageManager());
6451                 if (destInfo == null) {
6452                     return false;
6453                 }
6454                 upIntent = new Intent(upIntent);
6455                 upIntent.setComponent(destInfo);
6456             }
6457             int resultCode;
6458             Intent resultData;
6459             synchronized (this) {
6460                 resultCode = mResultCode;
6461                 resultData = mResultData;
6462             }
6463             if (resultData != null) {
6464                 resultData.prepareToLeaveProcess(this);
6465             }
6466             try {
6467                 upIntent.prepareToLeaveProcess(this);
6468                 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
6469                         resultCode, resultData);
6470             } catch (RemoteException e) {
6471                 return false;
6472             }
6473         } else {
6474             return mParent.navigateUpToFromChild(this, upIntent);
6475         }
6476     }
6477 
6478     /**
6479      * This is called when a child activity of this one calls its
6480      * {@link #navigateUpTo} method.  The default implementation simply calls
6481      * navigateUpTo(upIntent) on this activity (the parent).
6482      *
6483      * @param child The activity making the call.
6484      * @param upIntent An intent representing the target destination for up navigation
6485      *
6486      * @return true if up navigation successfully reached the activity indicated by upIntent and
6487      *         upIntent was delivered to it. false if an instance of the indicated activity could
6488      *         not be found and this activity was simply finished normally.
6489      */
navigateUpToFromChild(Activity child, Intent upIntent)6490     public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6491         return navigateUpTo(upIntent);
6492     }
6493 
6494     /**
6495      * Obtain an {@link Intent} that will launch an explicit target activity specified by
6496      * this activity's logical parent. The logical parent is named in the application's manifest
6497      * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6498      * Activity subclasses may override this method to modify the Intent returned by
6499      * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6500      * the parent intent entirely.
6501      *
6502      * @return a new Intent targeting the defined parent of this activity or null if
6503      *         there is no valid parent.
6504      */
6505     @Nullable
getParentActivityIntent()6506     public Intent getParentActivityIntent() {
6507         final String parentName = mActivityInfo.parentActivityName;
6508         if (TextUtils.isEmpty(parentName)) {
6509             return null;
6510         }
6511 
6512         // If the parent itself has no parent, generate a main activity intent.
6513         final ComponentName target = new ComponentName(this, parentName);
6514         try {
6515             final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6516             final String parentActivity = parentInfo.parentActivityName;
6517             final Intent parentIntent = parentActivity == null
6518                     ? Intent.makeMainActivity(target)
6519                     : new Intent().setComponent(target);
6520             return parentIntent;
6521         } catch (NameNotFoundException e) {
6522             Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6523                     "' in manifest");
6524             return null;
6525         }
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>launched</i> Activity. This requires
6532      * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6533      *
6534      * @param callback Used to manipulate shared element transitions on the launched Activity.
6535      */
setEnterSharedElementCallback(SharedElementCallback callback)6536     public void setEnterSharedElementCallback(SharedElementCallback callback) {
6537         if (callback == null) {
6538             callback = SharedElementCallback.NULL_CALLBACK;
6539         }
6540         mEnterTransitionListener = callback;
6541     }
6542 
6543     /**
6544      * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6545      * android.view.View, String)} was used to start an Activity, <var>callback</var>
6546      * will be called to handle shared elements on the <i>launching</i> Activity. Most
6547      * calls will only come when returning from the started Activity.
6548      * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6549      *
6550      * @param callback Used to manipulate shared element transitions on the launching Activity.
6551      */
setExitSharedElementCallback(SharedElementCallback callback)6552     public void setExitSharedElementCallback(SharedElementCallback callback) {
6553         if (callback == null) {
6554             callback = SharedElementCallback.NULL_CALLBACK;
6555         }
6556         mExitTransitionListener = callback;
6557     }
6558 
6559     /**
6560      * Postpone the entering activity transition when Activity was started with
6561      * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6562      * android.util.Pair[])}.
6563      * <p>This method gives the Activity the ability to delay starting the entering and
6564      * shared element transitions until all data is loaded. Until then, the Activity won't
6565      * draw into its window, leaving the window transparent. This may also cause the
6566      * returning animation to be delayed until data is ready. This method should be
6567      * called in {@link #onCreate(android.os.Bundle)} or in
6568      * {@link #onActivityReenter(int, android.content.Intent)}.
6569      * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6570      * start the transitions. If the Activity did not use
6571      * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6572      * android.util.Pair[])}, then this method does nothing.</p>
6573      */
postponeEnterTransition()6574     public void postponeEnterTransition() {
6575         mActivityTransitionState.postponeEnterTransition();
6576     }
6577 
6578     /**
6579      * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6580      * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6581      * to have your Activity start drawing.
6582      */
startPostponedEnterTransition()6583     public void startPostponedEnterTransition() {
6584         mActivityTransitionState.startPostponedEnterTransition();
6585     }
6586 
6587     /**
6588      * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
6589      * access permissions for content URIs associated with the {@link DragEvent}.
6590      * @param event Drag event
6591      * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
6592      * Null if no content URIs are associated with the event or if permissions could not be granted.
6593      */
requestDragAndDropPermissions(DragEvent event)6594     public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
6595         DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
6596         if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
6597             return dragAndDropPermissions;
6598         }
6599         return null;
6600     }
6601 
6602     // ------------------ Internal API ------------------
6603 
setParent(Activity parent)6604     final void setParent(Activity parent) {
6605         mParent = parent;
6606     }
6607 
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)6608     final void attach(Context context, ActivityThread aThread,
6609             Instrumentation instr, IBinder token, int ident,
6610             Application application, Intent intent, ActivityInfo info,
6611             CharSequence title, Activity parent, String id,
6612             NonConfigurationInstances lastNonConfigurationInstances,
6613             Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6614             Window window) {
6615         attachBaseContext(context);
6616 
6617         mFragments.attachHost(null /*parent*/);
6618 
6619         mWindow = new PhoneWindow(this, window);
6620         mWindow.setWindowControllerCallback(this);
6621         mWindow.setCallback(this);
6622         mWindow.setOnWindowDismissedCallback(this);
6623         mWindow.getLayoutInflater().setPrivateFactory(this);
6624         if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6625             mWindow.setSoftInputMode(info.softInputMode);
6626         }
6627         if (info.uiOptions != 0) {
6628             mWindow.setUiOptions(info.uiOptions);
6629         }
6630         mUiThread = Thread.currentThread();
6631 
6632         mMainThread = aThread;
6633         mInstrumentation = instr;
6634         mToken = token;
6635         mIdent = ident;
6636         mApplication = application;
6637         mIntent = intent;
6638         mReferrer = referrer;
6639         mComponent = intent.getComponent();
6640         mActivityInfo = info;
6641         mTitle = title;
6642         mParent = parent;
6643         mEmbeddedID = id;
6644         mLastNonConfigurationInstances = lastNonConfigurationInstances;
6645         if (voiceInteractor != null) {
6646             if (lastNonConfigurationInstances != null) {
6647                 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6648             } else {
6649                 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6650                         Looper.myLooper());
6651             }
6652         }
6653 
6654         mWindow.setWindowManager(
6655                 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6656                 mToken, mComponent.flattenToString(),
6657                 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6658         if (mParent != null) {
6659             mWindow.setContainer(mParent.getWindow());
6660         }
6661         mWindowManager = mWindow.getWindowManager();
6662         mCurrentConfig = config;
6663     }
6664 
6665     /** @hide */
getActivityToken()6666     public final IBinder getActivityToken() {
6667         return mParent != null ? mParent.getActivityToken() : mToken;
6668     }
6669 
performCreateCommon()6670     final void performCreateCommon() {
6671         mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6672                 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6673         mFragments.dispatchActivityCreated();
6674         mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6675     }
6676 
performCreate(Bundle icicle)6677     final void performCreate(Bundle icicle) {
6678         restoreHasCurrentPermissionRequest(icicle);
6679         onCreate(icicle);
6680         mActivityTransitionState.readState(icicle);
6681         performCreateCommon();
6682     }
6683 
performCreate(Bundle icicle, PersistableBundle persistentState)6684     final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6685         restoreHasCurrentPermissionRequest(icicle);
6686         onCreate(icicle, persistentState);
6687         mActivityTransitionState.readState(icicle);
6688         performCreateCommon();
6689     }
6690 
performStart()6691     final void performStart() {
6692         mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6693         mFragments.noteStateNotSaved();
6694         mCalled = false;
6695         mFragments.execPendingActions();
6696         mInstrumentation.callActivityOnStart(this);
6697         if (!mCalled) {
6698             throw new SuperNotCalledException(
6699                 "Activity " + mComponent.toShortString() +
6700                 " did not call through to super.onStart()");
6701         }
6702         mFragments.dispatchStart();
6703         mFragments.reportLoaderStart();
6704 
6705         // This property is set for all builds except final release
6706         boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
6707         boolean isAppDebuggable =
6708                 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
6709 
6710         if (isAppDebuggable || isDlwarningEnabled) {
6711             String dlwarning = getDlWarning();
6712             if (dlwarning != null) {
6713                 String appName = getApplicationInfo().loadLabel(getPackageManager())
6714                         .toString();
6715                 String warning = "Detected problems with app native libraries\n" +
6716                                  "(please consult log for detail):\n" + dlwarning;
6717                 if (isAppDebuggable) {
6718                       new AlertDialog.Builder(this).
6719                           setTitle(appName).
6720                           setMessage(warning).
6721                           setPositiveButton(android.R.string.ok, null).
6722                           setCancelable(false).
6723                           show();
6724                 } else {
6725                     Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
6726                 }
6727             }
6728         }
6729 
6730         mActivityTransitionState.enterReady(this);
6731     }
6732 
performRestart()6733     final void performRestart() {
6734         mFragments.noteStateNotSaved();
6735 
6736         if (mToken != null && mParent == null) {
6737             // No need to check mStopped, the roots will check if they were actually stopped.
6738             WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
6739         }
6740 
6741         if (mStopped) {
6742             mStopped = false;
6743 
6744             synchronized (mManagedCursors) {
6745                 final int N = mManagedCursors.size();
6746                 for (int i=0; i<N; i++) {
6747                     ManagedCursor mc = mManagedCursors.get(i);
6748                     if (mc.mReleased || mc.mUpdated) {
6749                         if (!mc.mCursor.requery()) {
6750                             if (getApplicationInfo().targetSdkVersion
6751                                     >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
6752                                 throw new IllegalStateException(
6753                                         "trying to requery an already closed cursor  "
6754                                         + mc.mCursor);
6755                             }
6756                         }
6757                         mc.mReleased = false;
6758                         mc.mUpdated = false;
6759                     }
6760                 }
6761             }
6762 
6763             mCalled = false;
6764             mInstrumentation.callActivityOnRestart(this);
6765             if (!mCalled) {
6766                 throw new SuperNotCalledException(
6767                     "Activity " + mComponent.toShortString() +
6768                     " did not call through to super.onRestart()");
6769             }
6770             performStart();
6771         }
6772     }
6773 
performResume()6774     final void performResume() {
6775         performRestart();
6776 
6777         mFragments.execPendingActions();
6778 
6779         mLastNonConfigurationInstances = null;
6780 
6781         mCalled = false;
6782         // mResumed is set by the instrumentation
6783         mInstrumentation.callActivityOnResume(this);
6784         if (!mCalled) {
6785             throw new SuperNotCalledException(
6786                 "Activity " + mComponent.toShortString() +
6787                 " did not call through to super.onResume()");
6788         }
6789 
6790         // invisible activities must be finished before onResume() completes
6791         if (!mVisibleFromClient && !mFinished) {
6792             Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
6793             if (getApplicationInfo().targetSdkVersion
6794                     > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
6795                 throw new IllegalStateException(
6796                         "Activity " + mComponent.toShortString() +
6797                         " did not call finish() prior to onResume() completing");
6798             }
6799         }
6800 
6801         // Now really resume, and install the current status bar and menu.
6802         mCalled = false;
6803 
6804         mFragments.dispatchResume();
6805         mFragments.execPendingActions();
6806 
6807         onPostResume();
6808         if (!mCalled) {
6809             throw new SuperNotCalledException(
6810                 "Activity " + mComponent.toShortString() +
6811                 " did not call through to super.onPostResume()");
6812         }
6813     }
6814 
performPause()6815     final void performPause() {
6816         mDoReportFullyDrawn = false;
6817         mFragments.dispatchPause();
6818         mCalled = false;
6819         onPause();
6820         mResumed = false;
6821         if (!mCalled && getApplicationInfo().targetSdkVersion
6822                 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
6823             throw new SuperNotCalledException(
6824                     "Activity " + mComponent.toShortString() +
6825                     " did not call through to super.onPause()");
6826         }
6827         mResumed = false;
6828     }
6829 
performUserLeaving()6830     final void performUserLeaving() {
6831         onUserInteraction();
6832         onUserLeaveHint();
6833     }
6834 
performStop(boolean preserveWindow)6835     final void performStop(boolean preserveWindow) {
6836         mDoReportFullyDrawn = false;
6837         mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
6838 
6839         if (!mStopped) {
6840             if (mWindow != null) {
6841                 mWindow.closeAllPanels();
6842             }
6843 
6844             // If we're preserving the window, don't setStoppedState to true, since we
6845             // need the window started immediately again. Stopping the window will
6846             // destroys hardware resources and causes flicker.
6847             if (!preserveWindow && mToken != null && mParent == null) {
6848                 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
6849             }
6850 
6851             mFragments.dispatchStop();
6852 
6853             mCalled = false;
6854             mInstrumentation.callActivityOnStop(this);
6855             if (!mCalled) {
6856                 throw new SuperNotCalledException(
6857                     "Activity " + mComponent.toShortString() +
6858                     " did not call through to super.onStop()");
6859             }
6860 
6861             synchronized (mManagedCursors) {
6862                 final int N = mManagedCursors.size();
6863                 for (int i=0; i<N; i++) {
6864                     ManagedCursor mc = mManagedCursors.get(i);
6865                     if (!mc.mReleased) {
6866                         mc.mCursor.deactivate();
6867                         mc.mReleased = true;
6868                     }
6869                 }
6870             }
6871 
6872             mStopped = true;
6873         }
6874         mResumed = false;
6875     }
6876 
performDestroy()6877     final void performDestroy() {
6878         mDestroyed = true;
6879         mWindow.destroy();
6880         mFragments.dispatchDestroy();
6881         onDestroy();
6882         mFragments.doLoaderDestroy();
6883         if (mVoiceInteractor != null) {
6884             mVoiceInteractor.detachActivity();
6885         }
6886     }
6887 
dispatchMultiWindowModeChanged(boolean isInMultiWindowMode)6888     final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) {
6889         if (DEBUG_LIFECYCLE) Slog.v(TAG,
6890                 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode);
6891         mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode);
6892         if (mWindow != null) {
6893             mWindow.onMultiWindowModeChanged();
6894         }
6895         onMultiWindowModeChanged(isInMultiWindowMode);
6896     }
6897 
dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode)6898     final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
6899         if (DEBUG_LIFECYCLE) Slog.v(TAG,
6900                 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode);
6901         mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode);
6902         onPictureInPictureModeChanged(isInPictureInPictureMode);
6903     }
6904 
6905     /**
6906      * @hide
6907      */
isResumed()6908     public final boolean isResumed() {
6909         return mResumed;
6910     }
6911 
storeHasCurrentPermissionRequest(Bundle bundle)6912     private void storeHasCurrentPermissionRequest(Bundle bundle) {
6913         if (bundle != null && mHasCurrentPermissionsRequest) {
6914             bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
6915         }
6916     }
6917 
restoreHasCurrentPermissionRequest(Bundle bundle)6918     private void restoreHasCurrentPermissionRequest(Bundle bundle) {
6919         if (bundle != null) {
6920             mHasCurrentPermissionsRequest = bundle.getBoolean(
6921                     HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
6922         }
6923     }
6924 
dispatchActivityResult(String who, int requestCode, int resultCode, Intent data)6925     void dispatchActivityResult(String who, int requestCode,
6926         int resultCode, Intent data) {
6927         if (false) Log.v(
6928             TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
6929             + ", resCode=" + resultCode + ", data=" + data);
6930         mFragments.noteStateNotSaved();
6931         if (who == null) {
6932             onActivityResult(requestCode, resultCode, data);
6933         } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
6934             who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
6935             if (TextUtils.isEmpty(who)) {
6936                 dispatchRequestPermissionsResult(requestCode, data);
6937             } else {
6938                 Fragment frag = mFragments.findFragmentByWho(who);
6939                 if (frag != null) {
6940                     dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
6941                 }
6942             }
6943         } else if (who.startsWith("@android:view:")) {
6944             ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
6945                     getActivityToken());
6946             for (ViewRootImpl viewRoot : views) {
6947                 if (viewRoot.getView() != null
6948                         && viewRoot.getView().dispatchActivityResult(
6949                                 who, requestCode, resultCode, data)) {
6950                     return;
6951                 }
6952             }
6953         } else {
6954             Fragment frag = mFragments.findFragmentByWho(who);
6955             if (frag != null) {
6956                 frag.onActivityResult(requestCode, resultCode, data);
6957             }
6958         }
6959     }
6960 
6961     /**
6962      * Request to put this Activity in a mode where the user is locked to the
6963      * current task.
6964      *
6965      * This will prevent the user from launching other apps, going to settings, or reaching the
6966      * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
6967      * values permit launching while locked.
6968      *
6969      * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
6970      * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
6971      * Lock Task mode. The user will not be able to exit this mode until
6972      * {@link Activity#stopLockTask()} is called.
6973      *
6974      * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
6975      * then the system will prompt the user with a dialog requesting permission to enter
6976      * this mode.  When entered through this method the user can exit at any time through
6977      * an action described by the request dialog.  Calling stopLockTask will also exit the
6978      * mode.
6979      *
6980      * @see android.R.attr#lockTaskMode
6981      */
startLockTask()6982     public void startLockTask() {
6983         try {
6984             ActivityManagerNative.getDefault().startLockTaskMode(mToken);
6985         } catch (RemoteException e) {
6986         }
6987     }
6988 
6989     /**
6990      * Allow the user to switch away from the current task.
6991      *
6992      * Called to end the mode started by {@link Activity#startLockTask}. This
6993      * can only be called by activities that have successfully called
6994      * startLockTask previously.
6995      *
6996      * This will allow the user to exit this app and move onto other activities.
6997      * <p>Note: This method should only be called when the activity is user-facing. That is,
6998      * between onResume() and onPause().
6999      * <p>Note: If there are other tasks below this one that are also locked then calling this
7000      * method will immediately finish this task and resume the previous locked one, remaining in
7001      * lockTask mode.
7002      *
7003      * @see android.R.attr#lockTaskMode
7004      * @see ActivityManager#getLockTaskModeState()
7005      */
stopLockTask()7006     public void stopLockTask() {
7007         try {
7008             ActivityManagerNative.getDefault().stopLockTaskMode();
7009         } catch (RemoteException e) {
7010         }
7011     }
7012 
7013     /**
7014      * Shows the user the system defined message for telling the user how to exit
7015      * lock task mode. The task containing this activity must be in lock task mode at the time
7016      * of this call for the message to be displayed.
7017      */
showLockTaskEscapeMessage()7018     public void showLockTaskEscapeMessage() {
7019         try {
7020             ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken);
7021         } catch (RemoteException e) {
7022         }
7023     }
7024 
7025     /**
7026      * Check whether the caption on freeform windows is displayed directly on the content.
7027      *
7028      * @return True if caption is displayed on content, false if it pushes the content down.
7029      *
7030      * @see {@link #setOverlayWithDecorCaptionEnabled(boolean)}
7031      *
7032      * @hide
7033      */
isOverlayWithDecorCaptionEnabled()7034     public boolean isOverlayWithDecorCaptionEnabled() {
7035         return mWindow.isOverlayWithDecorCaptionEnabled();
7036     }
7037 
7038     /**
7039      * Set whether the caption should displayed directly on the content rather than push it down.
7040      *
7041      * This affects only freeform windows since they display the caption and only the main
7042      * window of the activity. The caption is used to drag the window around and also shows
7043      * maximize and close action buttons.
7044      *
7045      * @hide
7046      */
setOverlayWithDecorCaptionEnabled(boolean enabled)7047     public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
7048         mWindow.setOverlayWithDecorCaptionEnabled(enabled);
7049     }
7050 
7051     /**
7052      * Interface for informing a translucent {@link Activity} once all visible activities below it
7053      * have completed drawing. This is necessary only after an {@link Activity} has been made
7054      * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
7055      * translucent again following a call to {@link
7056      * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7057      * ActivityOptions)}
7058      *
7059      * @hide
7060      */
7061     @SystemApi
7062     public interface TranslucentConversionListener {
7063         /**
7064          * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
7065          * below the top one have been redrawn. Following this callback it is safe to make the top
7066          * Activity translucent because the underlying Activity has been drawn.
7067          *
7068          * @param drawComplete True if the background Activity has drawn itself. False if a timeout
7069          * occurred waiting for the Activity to complete drawing.
7070          *
7071          * @see Activity#convertFromTranslucent()
7072          * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
7073          */
onTranslucentConversionComplete(boolean drawComplete)7074         public void onTranslucentConversionComplete(boolean drawComplete);
7075     }
7076 
dispatchRequestPermissionsResult(int requestCode, Intent data)7077     private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
7078         mHasCurrentPermissionsRequest = false;
7079         // If the package installer crashed we may have not data - best effort.
7080         String[] permissions = (data != null) ? data.getStringArrayExtra(
7081                 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7082         final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7083                 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7084         onRequestPermissionsResult(requestCode, permissions, grantResults);
7085     }
7086 
dispatchRequestPermissionsResultToFragment(int requestCode, Intent data, Fragment fragment)7087     private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
7088             Fragment fragment) {
7089         // If the package installer crashed we may have not data - best effort.
7090         String[] permissions = (data != null) ? data.getStringArrayExtra(
7091                 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7092         final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7093                 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7094         fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
7095     }
7096 
7097     class HostCallbacks extends FragmentHostCallback<Activity> {
HostCallbacks()7098         public HostCallbacks() {
7099             super(Activity.this /*activity*/);
7100         }
7101 
7102         @Override
onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)7103         public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
7104             Activity.this.dump(prefix, fd, writer, args);
7105         }
7106 
7107         @Override
onShouldSaveFragmentState(Fragment fragment)7108         public boolean onShouldSaveFragmentState(Fragment fragment) {
7109             return !isFinishing();
7110         }
7111 
7112         @Override
onGetLayoutInflater()7113         public LayoutInflater onGetLayoutInflater() {
7114             final LayoutInflater result = Activity.this.getLayoutInflater();
7115             if (onUseFragmentManagerInflaterFactory()) {
7116                 return result.cloneInContext(Activity.this);
7117             }
7118             return result;
7119         }
7120 
7121         @Override
onUseFragmentManagerInflaterFactory()7122         public boolean onUseFragmentManagerInflaterFactory() {
7123             // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
7124             return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
7125         }
7126 
7127         @Override
onGetHost()7128         public Activity onGetHost() {
7129             return Activity.this;
7130         }
7131 
7132         @Override
onInvalidateOptionsMenu()7133         public void onInvalidateOptionsMenu() {
7134             Activity.this.invalidateOptionsMenu();
7135         }
7136 
7137         @Override
onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)7138         public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
7139                 Bundle options) {
7140             Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
7141         }
7142 
7143         @Override
onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)7144         public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
7145                 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
7146                 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
7147             if (mParent == null) {
7148                 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
7149                         flagsMask, flagsValues, options);
7150             } else if (options != null) {
7151                 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode,
7152                         fillInIntent, flagsMask, flagsValues, extraFlags, options);
7153             }
7154         }
7155 
7156         @Override
onRequestPermissionsFromFragment(Fragment fragment, String[] permissions, int requestCode)7157         public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
7158                 int requestCode) {
7159             String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
7160             Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
7161             startActivityForResult(who, intent, requestCode, null);
7162         }
7163 
7164         @Override
onHasWindowAnimations()7165         public boolean onHasWindowAnimations() {
7166             return getWindow() != null;
7167         }
7168 
7169         @Override
onGetWindowAnimations()7170         public int onGetWindowAnimations() {
7171             final Window w = getWindow();
7172             return (w == null) ? 0 : w.getAttributes().windowAnimations;
7173         }
7174 
7175         @Override
onAttachFragment(Fragment fragment)7176         public void onAttachFragment(Fragment fragment) {
7177             Activity.this.onAttachFragment(fragment);
7178         }
7179 
7180         @Nullable
7181         @Override
onFindViewById(int id)7182         public View onFindViewById(int id) {
7183             return Activity.this.findViewById(id);
7184         }
7185 
7186         @Override
onHasView()7187         public boolean onHasView() {
7188             final Window w = getWindow();
7189             return (w != null && w.peekDecorView() != null);
7190         }
7191     }
7192 }
7193