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