OSDN Git Service

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