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