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