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