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