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