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