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