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