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