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