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