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