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