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