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