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