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