• 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 com.android.internal.policy.PolicyManager;
20 
21 import android.content.ComponentCallbacks;
22 import android.content.ComponentName;
23 import android.content.ContentResolver;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IIntentSender;
27 import android.content.IntentSender;
28 import android.content.SharedPreferences;
29 import android.content.pm.ActivityInfo;
30 import android.content.res.Configuration;
31 import android.content.res.Resources;
32 import android.database.Cursor;
33 import android.graphics.Bitmap;
34 import android.graphics.Canvas;
35 import android.graphics.drawable.Drawable;
36 import android.media.AudioManager;
37 import android.net.Uri;
38 import android.os.Build;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.os.RemoteException;
43 import android.text.Selection;
44 import android.text.SpannableStringBuilder;
45 import android.text.TextUtils;
46 import android.text.method.TextKeyListener;
47 import android.util.AttributeSet;
48 import android.util.Config;
49 import android.util.EventLog;
50 import android.util.Log;
51 import android.util.SparseArray;
52 import android.view.ContextMenu;
53 import android.view.ContextThemeWrapper;
54 import android.view.KeyEvent;
55 import android.view.LayoutInflater;
56 import android.view.Menu;
57 import android.view.MenuInflater;
58 import android.view.MenuItem;
59 import android.view.MotionEvent;
60 import android.view.View;
61 import android.view.ViewGroup;
62 import android.view.ViewManager;
63 import android.view.Window;
64 import android.view.WindowManager;
65 import android.view.ContextMenu.ContextMenuInfo;
66 import android.view.View.OnCreateContextMenuListener;
67 import android.view.ViewGroup.LayoutParams;
68 import android.view.accessibility.AccessibilityEvent;
69 import android.widget.AdapterView;
70 
71 import java.util.ArrayList;
72 import java.util.HashMap;
73 
74 /**
75  * An activity is a single, focused thing that the user can do.  Almost all
76  * activities interact with the user, so the Activity class takes care of
77  * creating a window for you in which you can place your UI with
78  * {@link #setContentView}.  While activities are often presented to the user
79  * as full-screen windows, they can also be used in other ways: as floating
80  * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
81  * or embedded inside of another activity (using {@link ActivityGroup}).
82  *
83  * There are two methods almost all subclasses of Activity will implement:
84  *
85  * <ul>
86  *     <li> {@link #onCreate} is where you initialize your activity.  Most
87  *     importantly, here you will usually call {@link #setContentView(int)}
88  *     with a layout resource defining your UI, and using {@link #findViewById}
89  *     to retrieve the widgets in that UI that you need to interact with
90  *     programmatically.
91  *
92  *     <li> {@link #onPause} is where you deal with the user leaving your
93  *     activity.  Most importantly, any changes made by the user should at this
94  *     point be committed (usually to the
95  *     {@link android.content.ContentProvider} holding the data).
96  * </ul>
97  *
98  * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
99  * activity classes must have a corresponding
100  * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
101  * declaration in their package's <code>AndroidManifest.xml</code>.</p>
102  *
103  * <p>The Activity class is an important part of an application's overall lifecycle,
104  * and the way activities are launched and put together is a fundamental
105  * part of the platform's application model. For a detailed perspective on the structure of
106  * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
107  * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
108  *
109  * <p>Topics covered here:
110  * <ol>
111  * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
112  * <li><a href="#ConfigurationChanges">Configuration Changes</a>
113  * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
114  * <li><a href="#SavingPersistentState">Saving Persistent State</a>
115  * <li><a href="#Permissions">Permissions</a>
116  * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
117  * </ol>
118  *
119  * <a name="ActivityLifecycle"></a>
120  * <h3>Activity Lifecycle</h3>
121  *
122  * <p>Activities in the system are managed as an <em>activity stack</em>.
123  * When a new activity is started, it is placed on the top of the stack
124  * and becomes the running activity -- the previous activity always remains
125  * below it in the stack, and will not come to the foreground again until
126  * the new activity exits.</p>
127  *
128  * <p>An activity has essentially four states:</p>
129  * <ul>
130  *     <li> If an activity in the foreground of the screen (at the top of
131  *         the stack),
132  *         it is <em>active</em> or  <em>running</em>. </li>
133  *     <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
134  *         or transparent activity has focus on top of your activity), it
135  *         is <em>paused</em>. A paused activity is completely alive (it
136  *         maintains all state and member information and remains attached to
137  *         the window manager), but can be killed by the system in extreme
138  *         low memory situations.
139  *     <li>If an activity is completely obscured by another activity,
140  *         it is <em>stopped</em>. It still retains all state and member information,
141  *         however, it is no longer visible to the user so its window is hidden
142  *         and it will often be killed by the system when memory is needed
143  *         elsewhere.</li>
144  *     <li>If an activity is paused or stopped, the system can drop the activity
145  *         from memory by either asking it to finish, or simply killing its
146  *         process.  When it is displayed again to the user, it must be
147  *         completely restarted and restored to its previous state.</li>
148  * </ul>
149  *
150  * <p>The following diagram shows the important state paths of an Activity.
151  * The square rectangles represent callback methods you can implement to
152  * perform operations when the Activity moves between states.  The colored
153  * ovals are major states the Activity can be in.</p>
154  *
155  * <p><img src="../../../images/activity_lifecycle.png"
156  *      alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
157  *
158  * <p>There are three key loops you may be interested in monitoring within your
159  * activity:
160  *
161  * <ul>
162  * <li>The <b>entire lifetime</b> of an activity happens between the first call
163  * to {@link android.app.Activity#onCreate} through to a single final call
164  * to {@link android.app.Activity#onDestroy}.  An activity will do all setup
165  * of "global" state in onCreate(), and release all remaining resources in
166  * onDestroy().  For example, if it has a thread running in the background
167  * to download data from the network, it may create that thread in onCreate()
168  * and then stop the thread in onDestroy().
169  *
170  * <li>The <b>visible lifetime</b> of an activity happens between a call to
171  * {@link android.app.Activity#onStart} until a corresponding call to
172  * {@link android.app.Activity#onStop}.  During this time the user can see the
173  * activity on-screen, though it may not be in the foreground and interacting
174  * with the user.  Between these two methods you can maintain resources that
175  * are needed to show the activity to the user.  For example, you can register
176  * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
177  * that impact your UI, and unregister it in onStop() when the user an no
178  * longer see what you are displaying.  The onStart() and onStop() methods
179  * can be called multiple times, as the activity becomes visible and hidden
180  * to the user.
181  *
182  * <li>The <b>foreground lifetime</b> of an activity happens between a call to
183  * {@link android.app.Activity#onResume} until a corresponding call to
184  * {@link android.app.Activity#onPause}.  During this time the activity is
185  * in front of all other activities and interacting with the user.  An activity
186  * can frequently go between the resumed and paused states -- for example when
187  * the device goes to sleep, when an activity result is delivered, when a new
188  * intent is delivered -- so the code in these methods should be fairly
189  * lightweight.
190  * </ul>
191  *
192  * <p>The entire lifecycle of an activity is defined by the following
193  * Activity methods.  All of these are hooks that you can override
194  * to do appropriate work when the activity changes state.  All
195  * activities will implement {@link android.app.Activity#onCreate}
196  * to do their initial setup; many will also implement
197  * {@link android.app.Activity#onPause} to commit changes to data and
198  * otherwise prepare to stop interacting with the user.  You should always
199  * call up to your superclass when implementing these methods.</p>
200  *
201  * </p>
202  * <pre class="prettyprint">
203  * public class Activity extends ApplicationContext {
204  *     protected void onCreate(Bundle savedInstanceState);
205  *
206  *     protected void onStart();
207  *
208  *     protected void onRestart();
209  *
210  *     protected void onResume();
211  *
212  *     protected void onPause();
213  *
214  *     protected void onStop();
215  *
216  *     protected void onDestroy();
217  * }
218  * </pre>
219  *
220  * <p>In general the movement through an activity's lifecycle looks like
221  * this:</p>
222  *
223  * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
224  *     <colgroup align="left" span="3" />
225  *     <colgroup align="left" />
226  *     <colgroup align="center" />
227  *     <colgroup align="center" />
228  *
229  *     <thead>
230  *     <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
231  *     </thead>
232  *
233  *     <tbody>
234  *     <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
235  *         <td>Called when the activity is first created.
236  *             This is where you should do all of your normal static set up:
237  *             create views, bind data to lists, etc.  This method also
238  *             provides you with a Bundle containing the activity's previously
239  *             frozen state, if there was one.
240  *             <p>Always followed by <code>onStart()</code>.</td>
241  *         <td align="center">No</td>
242  *         <td align="center"><code>onStart()</code></td>
243  *     </tr>
244  *
245  *     <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
246  *         <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
247  *         <td>Called after your activity has been stopped, prior to it being
248  *             started again.
249  *             <p>Always followed by <code>onStart()</code></td>
250  *         <td align="center">No</td>
251  *         <td align="center"><code>onStart()</code></td>
252  *     </tr>
253  *
254  *     <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
255  *         <td>Called when the activity is becoming visible to the user.
256  *             <p>Followed by <code>onResume()</code> if the activity comes
257  *             to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
258  *         <td align="center">No</td>
259  *         <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
260  *     </tr>
261  *
262  *     <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
263  *         <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
264  *         <td>Called when the activity will start
265  *             interacting with the user.  At this point your activity is at
266  *             the top of the activity stack, with user input going to it.
267  *             <p>Always followed by <code>onPause()</code>.</td>
268  *         <td align="center">No</td>
269  *         <td align="center"><code>onPause()</code></td>
270  *     </tr>
271  *
272  *     <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
273  *         <td>Called when the system is about to start resuming a previous
274  *             activity.  This is typically used to commit unsaved changes to
275  *             persistent data, stop animations and other things that may be consuming
276  *             CPU, etc.  Implementations of this method must be very quick because
277  *             the next activity will not be resumed until this method returns.
278  *             <p>Followed by either <code>onResume()</code> if the activity
279  *             returns back to the front, or <code>onStop()</code> if it becomes
280  *             invisible to the user.</td>
281  *         <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
282  *         <td align="center"><code>onResume()</code> or<br>
283  *                 <code>onStop()</code></td>
284  *     </tr>
285  *
286  *     <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
287  *         <td>Called when the activity is no longer visible to the user, because
288  *             another activity has been resumed and is covering this one.  This
289  *             may happen either because a new activity is being started, an existing
290  *             one is being brought in front of this one, or this one is being
291  *             destroyed.
292  *             <p>Followed by either <code>onRestart()</code> if
293  *             this activity is coming back to interact with the user, or
294  *             <code>onDestroy()</code> if this activity is going away.</td>
295  *         <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
296  *         <td align="center"><code>onRestart()</code> or<br>
297  *                 <code>onDestroy()</code></td>
298  *     </tr>
299  *
300  *     <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
301  *         <td>The final call you receive before your
302  *             activity is destroyed.  This can happen either because the
303  *             activity is finishing (someone called {@link Activity#finish} on
304  *             it, or because the system is temporarily destroying this
305  *             instance of the activity to save space.  You can distinguish
306  *             between these two scenarios with the {@link
307  *             Activity#isFinishing} method.</td>
308  *         <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
309  *         <td align="center"><em>nothing</em></td>
310  *     </tr>
311  *     </tbody>
312  * </table>
313  *
314  * <p>Note the "Killable" column in the above table -- for those methods that
315  * are marked as being killable, after that method returns the process hosting the
316  * activity may killed by the system <em>at any time</em> without another line
317  * of its code being executed.  Because of this, you should use the
318  * {@link #onPause} method to write any persistent data (such as user edits)
319  * to storage.  In addition, the method
320  * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
321  * in such a background state, allowing you to save away any dynamic instance
322  * state in your activity into the given Bundle, to be later received in
323  * {@link #onCreate} if the activity needs to be re-created.
324  * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
325  * section for more information on how the lifecycle of a process is tied
326  * to the activities it is hosting.  Note that it is important to save
327  * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
328  * because the later is not part of the lifecycle callbacks, so will not
329  * be called in every situation as described in its documentation.</p>
330  *
331  * <p>For those methods that are not marked as being killable, the activity's
332  * process will not be killed by the system starting from the time the method
333  * is called and continuing after it returns.  Thus an activity is in the killable
334  * state, for example, between after <code>onPause()</code> to the start of
335  * <code>onResume()</code>.</p>
336  *
337  * <a name="ConfigurationChanges"></a>
338  * <h3>Configuration Changes</h3>
339  *
340  * <p>If the configuration of the device (as defined by the
341  * {@link Configuration Resources.Configuration} class) changes,
342  * then anything displaying a user interface will need to update to match that
343  * configuration.  Because Activity is the primary mechanism for interacting
344  * with the user, it includes special support for handling configuration
345  * changes.</p>
346  *
347  * <p>Unless you specify otherwise, a configuration change (such as a change
348  * in screen orientation, language, input devices, etc) will cause your
349  * current activity to be <em>destroyed</em>, going through the normal activity
350  * lifecycle process of {@link #onPause},
351  * {@link #onStop}, and {@link #onDestroy} as appropriate.  If the activity
352  * had been in the foreground or visible to the user, once {@link #onDestroy} is
353  * called in that instance then a new instance of the activity will be
354  * created, with whatever savedInstanceState the previous instance had generated
355  * from {@link #onSaveInstanceState}.</p>
356  *
357  * <p>This is done because any application resource,
358  * including layout files, can change based on any configuration value.  Thus
359  * the only safe way to handle a configuration change is to re-retrieve all
360  * resources, including layouts, drawables, and strings.  Because activities
361  * must already know how to save their state and re-create themselves from
362  * that state, this is a convenient way to have an activity restart itself
363  * with a new configuration.</p>
364  *
365  * <p>In some special cases, you may want to bypass restarting of your
366  * activity based on one or more types of configuration changes.  This is
367  * done with the {@link android.R.attr#configChanges android:configChanges}
368  * attribute in its manifest.  For any types of configuration changes you say
369  * that you handle there, you will receive a call to your current activity's
370  * {@link #onConfigurationChanged} method instead of being restarted.  If
371  * a configuration change involves any that you do not handle, however, the
372  * activity will still be restarted and {@link #onConfigurationChanged}
373  * will not be called.</p>
374  *
375  * <a name="StartingActivities"></a>
376  * <h3>Starting Activities and Getting Results</h3>
377  *
378  * <p>The {@link android.app.Activity#startActivity}
379  * method is used to start a
380  * new activity, which will be placed at the top of the activity stack.  It
381  * takes a single argument, an {@link android.content.Intent Intent},
382  * which describes the activity
383  * to be executed.</p>
384  *
385  * <p>Sometimes you want to get a result back from an activity when it
386  * ends.  For example, you may start an activity that lets the user pick
387  * a person in a list of contacts; when it ends, it returns the person
388  * that was selected.  To do this, you call the
389  * {@link android.app.Activity#startActivityForResult(Intent, int)}
390  * version with a second integer parameter identifying the call.  The result
391  * will come back through your {@link android.app.Activity#onActivityResult}
392  * method.</p>
393  *
394  * <p>When an activity exits, it can call
395  * {@link android.app.Activity#setResult(int)}
396  * to return data back to its parent.  It must always supply a result code,
397  * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
398  * custom values starting at RESULT_FIRST_USER.  In addition, it can optionally
399  * return back an Intent containing any additional data it wants.  All of this
400  * information appears back on the
401  * parent's <code>Activity.onActivityResult()</code>, along with the integer
402  * identifier it originally supplied.</p>
403  *
404  * <p>If a child activity fails for any reason (such as crashing), the parent
405  * activity will receive a result with the code RESULT_CANCELED.</p>
406  *
407  * <pre class="prettyprint">
408  * public class MyActivity extends Activity {
409  *     ...
410  *
411  *     static final int PICK_CONTACT_REQUEST = 0;
412  *
413  *     protected boolean onKeyDown(int keyCode, KeyEvent event) {
414  *         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
415  *             // When the user center presses, let them pick a contact.
416  *             startActivityForResult(
417  *                 new Intent(Intent.ACTION_PICK,
418  *                 new Uri("content://contacts")),
419  *                 PICK_CONTACT_REQUEST);
420  *            return true;
421  *         }
422  *         return false;
423  *     }
424  *
425  *     protected void onActivityResult(int requestCode, int resultCode,
426  *             Intent data) {
427  *         if (requestCode == PICK_CONTACT_REQUEST) {
428  *             if (resultCode == RESULT_OK) {
429  *                 // A contact was picked.  Here we will just display it
430  *                 // to the user.
431  *                 startActivity(new Intent(Intent.ACTION_VIEW, data));
432  *             }
433  *         }
434  *     }
435  * }
436  * </pre>
437  *
438  * <a name="SavingPersistentState"></a>
439  * <h3>Saving Persistent State</h3>
440  *
441  * <p>There are generally two kinds of persistent state than an activity
442  * will deal with: shared document-like data (typically stored in a SQLite
443  * database using a {@linkplain android.content.ContentProvider content provider})
444  * and internal state such as user preferences.</p>
445  *
446  * <p>For content provider data, we suggest that activities use a
447  * "edit in place" user model.  That is, any edits a user makes are effectively
448  * made immediately without requiring an additional confirmation step.
449  * Supporting this model is generally a simple matter of following two rules:</p>
450  *
451  * <ul>
452  *     <li> <p>When creating a new document, the backing database entry or file for
453  *             it is created immediately.  For example, if the user chooses to write
454  *             a new e-mail, a new entry for that e-mail is created as soon as they
455  *             start entering data, so that if they go to any other activity after
456  *             that point this e-mail will now appear in the list of drafts.</p>
457  *     <li> <p>When an activity's <code>onPause()</code> method is called, it should
458  *             commit to the backing content provider or file any changes the user
459  *             has made.  This ensures that those changes will be seen by any other
460  *             activity that is about to run.  You will probably want to commit
461  *             your data even more aggressively at key times during your
462  *             activity's lifecycle: for example before starting a new
463  *             activity, before finishing your own activity, when the user
464  *             switches between input fields, etc.</p>
465  * </ul>
466  *
467  * <p>This model is designed to prevent data loss when a user is navigating
468  * between activities, and allows the system to safely kill an activity (because
469  * system resources are needed somewhere else) at any time after it has been
470  * paused.  Note this implies
471  * that the user pressing BACK from your activity does <em>not</em>
472  * mean "cancel" -- it means to leave the activity with its current contents
473  * saved away.  Cancelling edits in an activity must be provided through
474  * some other mechanism, such as an explicit "revert" or "undo" option.</p>
475  *
476  * <p>See the {@linkplain android.content.ContentProvider content package} for
477  * more information about content providers.  These are a key aspect of how
478  * different activities invoke and propagate data between themselves.</p>
479  *
480  * <p>The Activity class also provides an API for managing internal persistent state
481  * associated with an activity.  This can be used, for example, to remember
482  * the user's preferred initial display in a calendar (day view or week view)
483  * or the user's default home page in a web browser.</p>
484  *
485  * <p>Activity persistent state is managed
486  * with the method {@link #getPreferences},
487  * allowing you to retrieve and
488  * modify a set of name/value pairs associated with the activity.  To use
489  * preferences that are shared across multiple application components
490  * (activities, receivers, services, providers), you can use the underlying
491  * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
492  * to retrieve a preferences
493  * object stored under a specific name.
494  * (Note that it is not possible to share settings data across application
495  * packages -- for that you will need a content provider.)</p>
496  *
497  * <p>Here is an excerpt from a calendar activity that stores the user's
498  * preferred view mode in its persistent settings:</p>
499  *
500  * <pre class="prettyprint">
501  * public class CalendarActivity extends Activity {
502  *     ...
503  *
504  *     static final int DAY_VIEW_MODE = 0;
505  *     static final int WEEK_VIEW_MODE = 1;
506  *
507  *     private SharedPreferences mPrefs;
508  *     private int mCurViewMode;
509  *
510  *     protected void onCreate(Bundle savedInstanceState) {
511  *         super.onCreate(savedInstanceState);
512  *
513  *         SharedPreferences mPrefs = getSharedPreferences();
514  *         mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
515  *     }
516  *
517  *     protected void onPause() {
518  *         super.onPause();
519  *
520  *         SharedPreferences.Editor ed = mPrefs.edit();
521  *         ed.putInt("view_mode", mCurViewMode);
522  *         ed.commit();
523  *     }
524  * }
525  * </pre>
526  *
527  * <a name="Permissions"></a>
528  * <h3>Permissions</h3>
529  *
530  * <p>The ability to start a particular Activity can be enforced when it is
531  * declared in its
532  * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
533  * tag.  By doing so, other applications will need to declare a corresponding
534  * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
535  * element in their own manifest to be able to start that activity.
536  *
537  * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
538  * document for more information on permissions and security in general.
539  *
540  * <a name="ProcessLifecycle"></a>
541  * <h3>Process Lifecycle</h3>
542  *
543  * <p>The Android system attempts to keep application process around for as
544  * long as possible, but eventually will need to remove old processes when
545  * memory runs low.  As described in <a href="#ActivityLifecycle">Activity
546  * Lifecycle</a>, the decision about which process to remove is intimately
547  * tied to the state of the user's interaction with it.  In general, there
548  * are four states a process can be in based on the activities running in it,
549  * listed here in order of importance.  The system will kill less important
550  * processes (the last ones) before it resorts to killing more important
551  * processes (the first ones).
552  *
553  * <ol>
554  * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
555  * that the user is currently interacting with) is considered the most important.
556  * Its process will only be killed as a last resort, if it uses more memory
557  * than is available on the device.  Generally at this point the device has
558  * reached a memory paging state, so this is required in order to keep the user
559  * interface responsive.
560  * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
561  * but not in the foreground, such as one sitting behind a foreground dialog)
562  * is considered extremely important and will not be killed unless that is
563  * required to keep the foreground activity running.
564  * <li> <p>A <b>background activity</b> (an activity that is not visible to
565  * the user and has been paused) is no longer critical, so the system may
566  * safely kill its process to reclaim memory for other foreground or
567  * visible processes.  If its process needs to be killed, when the user navigates
568  * back to the activity (making it visible on the screen again), its
569  * {@link #onCreate} method will be called with the savedInstanceState it had previously
570  * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
571  * state as the user last left it.
572  * <li> <p>An <b>empty process</b> is one hosting no activities or other
573  * application components (such as {@link Service} or
574  * {@link android.content.BroadcastReceiver} classes).  These are killed very
575  * quickly by the system as memory becomes low.  For this reason, any
576  * background operation you do outside of an activity must be executed in the
577  * context of an activity BroadcastReceiver or Service to ensure that the system
578  * knows it needs to keep your process around.
579  * </ol>
580  *
581  * <p>Sometimes an Activity may need to do a long-running operation that exists
582  * independently of the activity lifecycle itself.  An example may be a camera
583  * application that allows you to upload a picture to a web site.  The upload
584  * may take a long time, and the application should allow the user to leave
585  * the application will it is executing.  To accomplish this, your Activity
586  * should start a {@link Service} in which the upload takes place.  This allows
587  * the system to properly prioritize your process (considering it to be more
588  * important than other non-visible applications) for the duration of the
589  * upload, independent of whether the original activity is paused, stopped,
590  * or finished.
591  */
592 public class Activity extends ContextThemeWrapper
593         implements LayoutInflater.Factory,
594         Window.Callback, KeyEvent.Callback,
595         OnCreateContextMenuListener, ComponentCallbacks {
596     private static final String TAG = "Activity";
597 
598     /** Standard activity result: operation canceled. */
599     public static final int RESULT_CANCELED    = 0;
600     /** Standard activity result: operation succeeded. */
601     public static final int RESULT_OK           = -1;
602     /** Start of user-defined activity results. */
603     public static final int RESULT_FIRST_USER   = 1;
604 
605     private static long sInstanceCount = 0;
606 
607     private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
608     private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
609     private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
610     private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
611 
612     private SparseArray<Dialog> mManagedDialogs;
613 
614     // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
615     private Instrumentation mInstrumentation;
616     private IBinder mToken;
617     private int mIdent;
618     /*package*/ String mEmbeddedID;
619     private Application mApplication;
620     /*package*/ Intent mIntent;
621     private ComponentName mComponent;
622     /*package*/ ActivityInfo mActivityInfo;
623     /*package*/ ActivityThread mMainThread;
624     /*package*/ Object mLastNonConfigurationInstance;
625     /*package*/ HashMap<String,Object> mLastNonConfigurationChildInstances;
626     Activity mParent;
627     boolean mCalled;
628     private boolean mResumed;
629     private boolean mStopped;
630     boolean mFinished;
631     boolean mStartedActivity;
632     /*package*/ int mConfigChangeFlags;
633     /*package*/ Configuration mCurrentConfig;
634     private SearchManager mSearchManager;
635 
636     private Window mWindow;
637 
638     private WindowManager mWindowManager;
639     /*package*/ View mDecor = null;
640     /*package*/ boolean mWindowAdded = false;
641     /*package*/ boolean mVisibleFromServer = false;
642     /*package*/ boolean mVisibleFromClient = true;
643 
644     private CharSequence mTitle;
645     private int mTitleColor = 0;
646 
647     private static final class ManagedCursor {
ManagedCursor(Cursor cursor)648         ManagedCursor(Cursor cursor) {
649             mCursor = cursor;
650             mReleased = false;
651             mUpdated = false;
652         }
653 
654         private final Cursor mCursor;
655         private boolean mReleased;
656         private boolean mUpdated;
657     }
658     private final ArrayList<ManagedCursor> mManagedCursors =
659         new ArrayList<ManagedCursor>();
660 
661     // protected by synchronized (this)
662     int mResultCode = RESULT_CANCELED;
663     Intent mResultData = null;
664 
665     private boolean mTitleReady = false;
666 
667     private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
668     private SpannableStringBuilder mDefaultKeySsb = null;
669 
670     protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
671 
672     private Thread mUiThread;
673     private final Handler mHandler = new Handler();
674 
Activity()675     public Activity() {
676         ++sInstanceCount;
677     }
678 
679 
680     @Override
finalize()681     protected void finalize() throws Throwable {
682         super.finalize();
683         --sInstanceCount;
684     }
685 
getInstanceCount()686     public static long getInstanceCount() {
687         return sInstanceCount;
688     }
689 
690     /** Return the intent that started this activity. */
getIntent()691     public Intent getIntent() {
692         return mIntent;
693     }
694 
695     /**
696      * Change the intent returned by {@link #getIntent}.  This holds a
697      * reference to the given intent; it does not copy it.  Often used in
698      * conjunction with {@link #onNewIntent}.
699      *
700      * @param newIntent The new Intent object to return from getIntent
701      *
702      * @see #getIntent
703      * @see #onNewIntent
704      */
setIntent(Intent newIntent)705     public void setIntent(Intent newIntent) {
706         mIntent = newIntent;
707     }
708 
709     /** Return the application that owns this activity. */
getApplication()710     public final Application getApplication() {
711         return mApplication;
712     }
713 
714     /** Is this activity embedded inside of another activity? */
isChild()715     public final boolean isChild() {
716         return mParent != null;
717     }
718 
719     /** Return the parent activity if this view is an embedded child. */
getParent()720     public final Activity getParent() {
721         return mParent;
722     }
723 
724     /** Retrieve the window manager for showing custom windows. */
getWindowManager()725     public WindowManager getWindowManager() {
726         return mWindowManager;
727     }
728 
729     /**
730      * Retrieve the current {@link android.view.Window} for the activity.
731      * This can be used to directly access parts of the Window API that
732      * are not available through Activity/Screen.
733      *
734      * @return Window The current window, or null if the activity is not
735      *         visual.
736      */
getWindow()737     public Window getWindow() {
738         return mWindow;
739     }
740 
741     /**
742      * Calls {@link android.view.Window#getCurrentFocus} on the
743      * Window of this Activity to return the currently focused view.
744      *
745      * @return View The current View with focus or null.
746      *
747      * @see #getWindow
748      * @see android.view.Window#getCurrentFocus
749      */
getCurrentFocus()750     public View getCurrentFocus() {
751         return mWindow != null ? mWindow.getCurrentFocus() : null;
752     }
753 
754     @Override
getWallpaperDesiredMinimumWidth()755     public int getWallpaperDesiredMinimumWidth() {
756         int width = super.getWallpaperDesiredMinimumWidth();
757         return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
758     }
759 
760     @Override
getWallpaperDesiredMinimumHeight()761     public int getWallpaperDesiredMinimumHeight() {
762         int height = super.getWallpaperDesiredMinimumHeight();
763         return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
764     }
765 
766     /**
767      * Called when the activity is starting.  This is where most initialization
768      * should go: calling {@link #setContentView(int)} to inflate the
769      * activity's UI, using {@link #findViewById} to programmatically interact
770      * with widgets in the UI, calling
771      * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
772      * cursors for data being displayed, etc.
773      *
774      * <p>You can call {@link #finish} from within this function, in
775      * which case onDestroy() will be immediately called without any of the rest
776      * of the activity lifecycle ({@link #onStart}, {@link #onResume},
777      * {@link #onPause}, etc) executing.
778      *
779      * <p><em>Derived classes must call through to the super class's
780      * implementation of this method.  If they do not, an exception will be
781      * thrown.</em></p>
782      *
783      * @param savedInstanceState If the activity is being re-initialized after
784      *     previously being shut down then this Bundle contains the data it most
785      *     recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>
786      *
787      * @see #onStart
788      * @see #onSaveInstanceState
789      * @see #onRestoreInstanceState
790      * @see #onPostCreate
791      */
onCreate(Bundle savedInstanceState)792     protected void onCreate(Bundle savedInstanceState) {
793         mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
794                 com.android.internal.R.styleable.Window_windowNoDisplay, false);
795         mCalled = true;
796     }
797 
798     /**
799      * The hook for {@link ActivityThread} to restore the state of this activity.
800      *
801      * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
802      * {@link #restoreManagedDialogs(android.os.Bundle)}.
803      *
804      * @param savedInstanceState contains the saved state
805      */
performRestoreInstanceState(Bundle savedInstanceState)806     final void performRestoreInstanceState(Bundle savedInstanceState) {
807         onRestoreInstanceState(savedInstanceState);
808         restoreManagedDialogs(savedInstanceState);
809     }
810 
811     /**
812      * This method is called after {@link #onStart} when the activity is
813      * being re-initialized from a previously saved state, given here in
814      * <var>state</var>.  Most implementations will simply use {@link #onCreate}
815      * to restore their state, but it is sometimes convenient to do it here
816      * after all of the initialization has been done or to allow subclasses to
817      * decide whether to use your default implementation.  The default
818      * implementation of this method performs a restore of any view state that
819      * had previously been frozen by {@link #onSaveInstanceState}.
820      *
821      * <p>This method is called between {@link #onStart} and
822      * {@link #onPostCreate}.
823      *
824      * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
825      *
826      * @see #onCreate
827      * @see #onPostCreate
828      * @see #onResume
829      * @see #onSaveInstanceState
830      */
onRestoreInstanceState(Bundle savedInstanceState)831     protected void onRestoreInstanceState(Bundle savedInstanceState) {
832         if (mWindow != null) {
833             Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
834             if (windowState != null) {
835                 mWindow.restoreHierarchyState(windowState);
836             }
837         }
838     }
839 
840     /**
841      * Restore the state of any saved managed dialogs.
842      *
843      * @param savedInstanceState The bundle to restore from.
844      */
restoreManagedDialogs(Bundle savedInstanceState)845     private void restoreManagedDialogs(Bundle savedInstanceState) {
846         final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
847         if (b == null) {
848             return;
849         }
850 
851         final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
852         final int numDialogs = ids.length;
853         mManagedDialogs = new SparseArray<Dialog>(numDialogs);
854         for (int i = 0; i < numDialogs; i++) {
855             final Integer dialogId = ids[i];
856             Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
857             if (dialogState != null) {
858                 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
859                 // so tell createDialog() not to do it, otherwise we get an exception
860                 final Dialog dialog = createDialog(dialogId, dialogState);
861                 mManagedDialogs.put(dialogId, dialog);
862                 onPrepareDialog(dialogId, dialog);
863                 dialog.onRestoreInstanceState(dialogState);
864             }
865         }
866     }
867 
createDialog(Integer dialogId, Bundle state)868     private Dialog createDialog(Integer dialogId, Bundle state) {
869         final Dialog dialog = onCreateDialog(dialogId);
870         if (dialog == null) {
871             throw new IllegalArgumentException("Activity#onCreateDialog did "
872                     + "not create a dialog for id " + dialogId);
873         }
874         dialog.dispatchOnCreate(state);
875         return dialog;
876     }
877 
savedDialogKeyFor(int key)878     private String savedDialogKeyFor(int key) {
879         return SAVED_DIALOG_KEY_PREFIX + key;
880     }
881 
882 
883     /**
884      * Called when activity start-up is complete (after {@link #onStart}
885      * and {@link #onRestoreInstanceState} have been called).  Applications will
886      * generally not implement this method; it is intended for system
887      * classes to do final initialization after application code has run.
888      *
889      * <p><em>Derived classes must call through to the super class's
890      * implementation of this method.  If they do not, an exception will be
891      * thrown.</em></p>
892      *
893      * @param savedInstanceState If the activity is being re-initialized after
894      *     previously being shut down then this Bundle contains the data it most
895      *     recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>
896      * @see #onCreate
897      */
onPostCreate(Bundle savedInstanceState)898     protected void onPostCreate(Bundle savedInstanceState) {
899         if (!isChild()) {
900             mTitleReady = true;
901             onTitleChanged(getTitle(), getTitleColor());
902         }
903         mCalled = true;
904     }
905 
906     /**
907      * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
908      * the activity had been stopped, but is now again being displayed to the
909 	 * user.  It will be followed by {@link #onResume}.
910      *
911      * <p><em>Derived classes must call through to the super class's
912      * implementation of this method.  If they do not, an exception will be
913      * thrown.</em></p>
914      *
915      * @see #onCreate
916      * @see #onStop
917      * @see #onResume
918      */
onStart()919     protected void onStart() {
920         mCalled = true;
921     }
922 
923     /**
924      * Called after {@link #onStop} when the current activity is being
925      * re-displayed to the user (the user has navigated back to it).  It will
926      * be followed by {@link #onStart} and then {@link #onResume}.
927      *
928      * <p>For activities that are using raw {@link Cursor} objects (instead of
929      * creating them through
930      * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
931      * this is usually the place
932      * where the cursor should be requeried (because you had deactivated it in
933      * {@link #onStop}.
934      *
935      * <p><em>Derived classes must call through to the super class's
936      * implementation of this method.  If they do not, an exception will be
937      * thrown.</em></p>
938      *
939      * @see #onStop
940      * @see #onStart
941      * @see #onResume
942      */
onRestart()943     protected void onRestart() {
944         mCalled = true;
945     }
946 
947     /**
948      * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
949      * {@link #onPause}, for your activity to start interacting with the user.
950      * This is a good place to begin animations, open exclusive-access devices
951      * (such as the camera), etc.
952      *
953      * <p>Keep in mind that onResume is not the best indicator that your activity
954      * is visible to the user; a system window such as the keyguard may be in
955      * front.  Use {@link #onWindowFocusChanged} to know for certain that your
956      * activity is visible to the user (for example, to resume a game).
957      *
958      * <p><em>Derived classes must call through to the super class's
959      * implementation of this method.  If they do not, an exception will be
960      * thrown.</em></p>
961      *
962      * @see #onRestoreInstanceState
963      * @see #onRestart
964      * @see #onPostResume
965      * @see #onPause
966      */
onResume()967     protected void onResume() {
968         mCalled = true;
969     }
970 
971     /**
972      * Called when activity resume is complete (after {@link #onResume} has
973      * been called). Applications will generally not implement this method;
974      * it is intended for system classes to do final setup after application
975      * resume code has run.
976      *
977      * <p><em>Derived classes must call through to the super class's
978      * implementation of this method.  If they do not, an exception will be
979      * thrown.</em></p>
980      *
981      * @see #onResume
982      */
onPostResume()983     protected void onPostResume() {
984         final Window win = getWindow();
985         if (win != null) win.makeActive();
986         mCalled = true;
987     }
988 
989     /**
990      * This is called for activities that set launchMode to "singleTop" in
991      * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
992      * flag when calling {@link #startActivity}.  In either case, when the
993      * activity is re-launched while at the top of the activity stack instead
994      * of a new instance of the activity being started, onNewIntent() will be
995      * called on the existing instance with the Intent that was used to
996      * re-launch it.
997      *
998      * <p>An activity will always be paused before receiving a new intent, so
999      * you can count on {@link #onResume} being called after this method.
1000      *
1001      * <p>Note that {@link #getIntent} still returns the original Intent.  You
1002      * can use {@link #setIntent} to update it to this new Intent.
1003      *
1004      * @param intent The new intent that was started for the activity.
1005      *
1006      * @see #getIntent
1007      * @see #setIntent
1008      * @see #onResume
1009      */
onNewIntent(Intent intent)1010     protected void onNewIntent(Intent intent) {
1011     }
1012 
1013     /**
1014      * The hook for {@link ActivityThread} to save the state of this activity.
1015      *
1016      * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1017      * and {@link #saveManagedDialogs(android.os.Bundle)}.
1018      *
1019      * @param outState The bundle to save the state to.
1020      */
performSaveInstanceState(Bundle outState)1021     final void performSaveInstanceState(Bundle outState) {
1022         onSaveInstanceState(outState);
1023         saveManagedDialogs(outState);
1024     }
1025 
1026     /**
1027      * Called to retrieve per-instance state from an activity before being killed
1028      * so that the state can be restored in {@link #onCreate} or
1029      * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1030      * will be passed to both).
1031      *
1032      * <p>This method is called before an activity may be killed so that when it
1033      * comes back some time in the future it can restore its state.  For example,
1034      * if activity B is launched in front of activity A, and at some point activity
1035      * A is killed to reclaim resources, activity A will have a chance to save the
1036      * current state of its user interface via this method so that when the user
1037      * returns to activity A, the state of the user interface can be restored
1038      * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1039      *
1040      * <p>Do not confuse this method with activity lifecycle callbacks such as
1041      * {@link #onPause}, which is always called when an activity is being placed
1042      * in the background or on its way to destruction, or {@link #onStop} which
1043      * is called before destruction.  One example of when {@link #onPause} and
1044      * {@link #onStop} is called and not this method is when a user navigates back
1045      * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1046      * on B because that particular instance will never be restored, so the
1047      * system avoids calling it.  An example when {@link #onPause} is called and
1048      * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1049      * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1050      * killed during the lifetime of B since the state of the user interface of
1051      * A will stay intact.
1052      *
1053      * <p>The default implementation takes care of most of the UI per-instance
1054      * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1055      * view in the hierarchy that has an id, and by saving the id of the currently
1056      * focused view (all of which is restored by the default implementation of
1057      * {@link #onRestoreInstanceState}).  If you override this method to save additional
1058      * information not captured by each individual view, you will likely want to
1059      * call through to the default implementation, otherwise be prepared to save
1060      * all of the state of each view yourself.
1061      *
1062      * <p>If called, this method will occur before {@link #onStop}.  There are
1063      * no guarantees about whether it will occur before or after {@link #onPause}.
1064      *
1065      * @param outState Bundle in which to place your saved state.
1066      *
1067      * @see #onCreate
1068      * @see #onRestoreInstanceState
1069      * @see #onPause
1070      */
onSaveInstanceState(Bundle outState)1071     protected void onSaveInstanceState(Bundle outState) {
1072         outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1073     }
1074 
1075     /**
1076      * Save the state of any managed dialogs.
1077      *
1078      * @param outState place to store the saved state.
1079      */
saveManagedDialogs(Bundle outState)1080     private void saveManagedDialogs(Bundle outState) {
1081         if (mManagedDialogs == null) {
1082             return;
1083         }
1084 
1085         final int numDialogs = mManagedDialogs.size();
1086         if (numDialogs == 0) {
1087             return;
1088         }
1089 
1090         Bundle dialogState = new Bundle();
1091 
1092         int[] ids = new int[mManagedDialogs.size()];
1093 
1094         // save each dialog's bundle, gather the ids
1095         for (int i = 0; i < numDialogs; i++) {
1096             final int key = mManagedDialogs.keyAt(i);
1097             ids[i] = key;
1098             final Dialog dialog = mManagedDialogs.valueAt(i);
1099             dialogState.putBundle(savedDialogKeyFor(key), dialog.onSaveInstanceState());
1100         }
1101 
1102         dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1103         outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1104     }
1105 
1106 
1107     /**
1108      * Called as part of the activity lifecycle when an activity is going into
1109      * the background, but has not (yet) been killed.  The counterpart to
1110      * {@link #onResume}.
1111      *
1112      * <p>When activity B is launched in front of activity A, this callback will
1113      * be invoked on A.  B will not be created until A's {@link #onPause} returns,
1114      * so be sure to not do anything lengthy here.
1115      *
1116      * <p>This callback is mostly used for saving any persistent state the
1117      * activity is editing, to present a "edit in place" model to the user and
1118      * making sure nothing is lost if there are not enough resources to start
1119      * the new activity without first killing this one.  This is also a good
1120      * place to do things like stop animations and other things that consume a
1121      * noticeable mount of CPU in order to make the switch to the next activity
1122      * as fast as possible, or to close resources that are exclusive access
1123      * such as the camera.
1124      *
1125      * <p>In situations where the system needs more memory it may kill paused
1126      * processes to reclaim resources.  Because of this, you should be sure
1127      * that all of your state is saved by the time you return from
1128      * this function.  In general {@link #onSaveInstanceState} is used to save
1129      * per-instance state in the activity and this method is used to store
1130      * global persistent data (in content providers, files, etc.)
1131      *
1132      * <p>After receiving this call you will usually receive a following call
1133      * to {@link #onStop} (after the next activity has been resumed and
1134      * displayed), however in some cases there will be a direct call back to
1135      * {@link #onResume} without going through the stopped state.
1136      *
1137      * <p><em>Derived classes must call through to the super class's
1138      * implementation of this method.  If they do not, an exception will be
1139      * thrown.</em></p>
1140      *
1141      * @see #onResume
1142      * @see #onSaveInstanceState
1143      * @see #onStop
1144      */
onPause()1145     protected void onPause() {
1146         mCalled = true;
1147     }
1148 
1149     /**
1150      * Called as part of the activity lifecycle when an activity is about to go
1151      * into the background as the result of user choice.  For example, when the
1152      * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1153      * when an incoming phone call causes the in-call Activity to be automatically
1154      * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1155      * the activity being interrupted.  In cases when it is invoked, this method
1156      * is called right before the activity's {@link #onPause} callback.
1157      *
1158      * <p>This callback and {@link #onUserInteraction} are intended to help
1159      * activities manage status bar notifications intelligently; specifically,
1160      * for helping activities determine the proper time to cancel a notfication.
1161      *
1162      * @see #onUserInteraction()
1163      */
onUserLeaveHint()1164     protected void onUserLeaveHint() {
1165     }
1166 
1167     /**
1168      * Generate a new thumbnail for this activity.  This method is called before
1169      * pausing the activity, and should draw into <var>outBitmap</var> the
1170      * imagery for the desired thumbnail in the dimensions of that bitmap.  It
1171      * can use the given <var>canvas</var>, which is configured to draw into the
1172      * bitmap, for rendering if desired.
1173      *
1174      * <p>The default implementation renders the Screen's current view
1175      * hierarchy into the canvas to generate a thumbnail.
1176      *
1177      * <p>If you return false, the bitmap will be filled with a default
1178      * thumbnail.
1179      *
1180      * @param outBitmap The bitmap to contain the thumbnail.
1181      * @param canvas Can be used to render into the bitmap.
1182      *
1183      * @return Return true if you have drawn into the bitmap; otherwise after
1184      *         you return it will be filled with a default thumbnail.
1185      *
1186      * @see #onCreateDescription
1187      * @see #onSaveInstanceState
1188      * @see #onPause
1189      */
onCreateThumbnail(Bitmap outBitmap, Canvas canvas)1190     public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1191         final View view = mDecor;
1192         if (view == null) {
1193             return false;
1194         }
1195 
1196         final int vw = view.getWidth();
1197         final int vh = view.getHeight();
1198         final int dw = outBitmap.getWidth();
1199         final int dh = outBitmap.getHeight();
1200 
1201         canvas.save();
1202         canvas.scale(((float)dw)/vw, ((float)dh)/vh);
1203         view.draw(canvas);
1204         canvas.restore();
1205 
1206         return true;
1207     }
1208 
1209     /**
1210      * Generate a new description for this activity.  This method is called
1211      * before pausing the activity and can, if desired, return some textual
1212      * description of its current state to be displayed to the user.
1213      *
1214      * <p>The default implementation returns null, which will cause you to
1215      * inherit the description from the previous activity.  If all activities
1216      * return null, generally the label of the top activity will be used as the
1217      * description.
1218      *
1219      * @return A description of what the user is doing.  It should be short and
1220      *         sweet (only a few words).
1221      *
1222      * @see #onCreateThumbnail
1223      * @see #onSaveInstanceState
1224      * @see #onPause
1225      */
onCreateDescription()1226     public CharSequence onCreateDescription() {
1227         return null;
1228     }
1229 
1230     /**
1231      * Called when you are no longer visible to the user.  You will next
1232      * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1233      * depending on later user activity.
1234      *
1235      * <p>Note that this method may never be called, in low memory situations
1236      * where the system does not have enough memory to keep your activity's
1237      * process running after its {@link #onPause} method is called.
1238      *
1239      * <p><em>Derived classes must call through to the super class's
1240      * implementation of this method.  If they do not, an exception will be
1241      * thrown.</em></p>
1242      *
1243      * @see #onRestart
1244      * @see #onResume
1245      * @see #onSaveInstanceState
1246      * @see #onDestroy
1247      */
onStop()1248     protected void onStop() {
1249         mCalled = true;
1250     }
1251 
1252     /**
1253      * Perform any final cleanup before an activity is destroyed.  This can
1254      * happen either because the activity is finishing (someone called
1255      * {@link #finish} on it, or because the system is temporarily destroying
1256      * this instance of the activity to save space.  You can distinguish
1257      * between these two scenarios with the {@link #isFinishing} method.
1258      *
1259      * <p><em>Note: do not count on this method being called as a place for
1260      * saving data! For example, if an activity is editing data in a content
1261      * provider, those edits should be committed in either {@link #onPause} or
1262      * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1263      * free resources like threads that are associated with an activity, so
1264      * that a destroyed activity does not leave such things around while the
1265      * rest of its application is still running.  There are situations where
1266      * the system will simply kill the activity's hosting process without
1267      * calling this method (or any others) in it, so it should not be used to
1268      * do things that are intended to remain around after the process goes
1269      * away.
1270      *
1271      * <p><em>Derived classes must call through to the super class's
1272      * implementation of this method.  If they do not, an exception will be
1273      * thrown.</em></p>
1274      *
1275      * @see #onPause
1276      * @see #onStop
1277      * @see #finish
1278      * @see #isFinishing
1279      */
onDestroy()1280     protected void onDestroy() {
1281         mCalled = true;
1282 
1283         // dismiss any dialogs we are managing.
1284         if (mManagedDialogs != null) {
1285 
1286             final int numDialogs = mManagedDialogs.size();
1287             for (int i = 0; i < numDialogs; i++) {
1288                 final Dialog dialog = mManagedDialogs.valueAt(i);
1289                 if (dialog.isShowing()) {
1290                     dialog.dismiss();
1291                 }
1292             }
1293         }
1294 
1295         // close any cursors we are managing.
1296         int numCursors = mManagedCursors.size();
1297         for (int i = 0; i < numCursors; i++) {
1298             ManagedCursor c = mManagedCursors.get(i);
1299             if (c != null) {
1300                 c.mCursor.close();
1301             }
1302         }
1303     }
1304 
1305     /**
1306      * Called by the system when the device configuration changes while your
1307      * activity is running.  Note that this will <em>only</em> be called if
1308      * you have selected configurations you would like to handle with the
1309      * {@link android.R.attr#configChanges} attribute in your manifest.  If
1310      * any configuration change occurs that is not selected to be reported
1311      * by that attribute, then instead of reporting it the system will stop
1312      * and restart the activity (to have it launched with the new
1313      * configuration).
1314      *
1315      * <p>At the time that this function has been called, your Resources
1316      * object will have been updated to return resource values matching the
1317      * new configuration.
1318      *
1319      * @param newConfig The new device configuration.
1320      */
onConfigurationChanged(Configuration newConfig)1321     public void onConfigurationChanged(Configuration newConfig) {
1322         mCalled = true;
1323 
1324         if (mWindow != null) {
1325             // Pass the configuration changed event to the window
1326             mWindow.onConfigurationChanged(newConfig);
1327         }
1328     }
1329 
1330     /**
1331      * If this activity is being destroyed because it can not handle a
1332      * configuration parameter being changed (and thus its
1333      * {@link #onConfigurationChanged(Configuration)} method is
1334      * <em>not</em> being called), then you can use this method to discover
1335      * the set of changes that have occurred while in the process of being
1336      * destroyed.  Note that there is no guarantee that these will be
1337      * accurate (other changes could have happened at any time), so you should
1338      * only use this as an optimization hint.
1339      *
1340      * @return Returns a bit field of the configuration parameters that are
1341      * changing, as defined by the {@link android.content.res.Configuration}
1342      * class.
1343      */
getChangingConfigurations()1344     public int getChangingConfigurations() {
1345         return mConfigChangeFlags;
1346     }
1347 
1348     /**
1349      * Retrieve the non-configuration instance data that was previously
1350      * returned by {@link #onRetainNonConfigurationInstance()}.  This will
1351      * be available from the initial {@link #onCreate} and
1352      * {@link #onStart} calls to the new instance, allowing you to extract
1353      * any useful dynamic state from the previous instance.
1354      *
1355      * <p>Note that the data you retrieve here should <em>only</em> be used
1356      * as an optimization for handling configuration changes.  You should always
1357      * be able to handle getting a null pointer back, and an activity must
1358      * still be able to restore itself to its previous state (through the
1359      * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1360      * function returns null.
1361      *
1362      * @return Returns the object previously returned by
1363      * {@link #onRetainNonConfigurationInstance()}.
1364      */
getLastNonConfigurationInstance()1365     public Object getLastNonConfigurationInstance() {
1366         return mLastNonConfigurationInstance;
1367     }
1368 
1369     /**
1370      * Called by the system, as part of destroying an
1371      * activity due to a configuration change, when it is known that a new
1372      * instance will immediately be created for the new configuration.  You
1373      * can return any object you like here, including the activity instance
1374      * itself, which can later be retrieved by calling
1375      * {@link #getLastNonConfigurationInstance()} in the new activity
1376      * instance.
1377      *
1378      * <p>This function is called purely as an optimization, and you must
1379      * not rely on it being called.  When it is called, a number of guarantees
1380      * will be made to help optimize configuration switching:
1381      * <ul>
1382      * <li> The function will be called between {@link #onStop} and
1383      * {@link #onDestroy}.
1384      * <li> A new instance of the activity will <em>always</em> be immediately
1385      * created after this one's {@link #onDestroy()} is called.
1386      * <li> The object you return here will <em>always</em> be available from
1387      * the {@link #getLastNonConfigurationInstance()} method of the following
1388      * activity instance as described there.
1389      * </ul>
1390      *
1391      * <p>These guarantees are designed so that an activity can use this API
1392      * to propagate extensive state from the old to new activity instance, from
1393      * loaded bitmaps, to network connections, to evenly actively running
1394      * threads.  Note that you should <em>not</em> propagate any data that
1395      * may change based on the configuration, including any data loaded from
1396      * resources such as strings, layouts, or drawables.
1397      *
1398      * @return Return any Object holding the desired state to propagate to the
1399      * next activity instance.
1400      */
onRetainNonConfigurationInstance()1401     public Object onRetainNonConfigurationInstance() {
1402         return null;
1403     }
1404 
1405     /**
1406      * Retrieve the non-configuration instance data that was previously
1407      * returned by {@link #onRetainNonConfigurationChildInstances()}.  This will
1408      * be available from the initial {@link #onCreate} and
1409      * {@link #onStart} calls to the new instance, allowing you to extract
1410      * any useful dynamic state from the previous instance.
1411      *
1412      * <p>Note that the data you retrieve here should <em>only</em> be used
1413      * as an optimization for handling configuration changes.  You should always
1414      * be able to handle getting a null pointer back, and an activity must
1415      * still be able to restore itself to its previous state (through the
1416      * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1417      * function returns null.
1418      *
1419      * @return Returns the object previously returned by
1420      * {@link #onRetainNonConfigurationChildInstances()}
1421      */
getLastNonConfigurationChildInstances()1422     HashMap<String,Object> getLastNonConfigurationChildInstances() {
1423         return mLastNonConfigurationChildInstances;
1424     }
1425 
1426     /**
1427      * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1428      * it should return either a mapping from  child activity id strings to arbitrary objects,
1429      * or null.  This method is intended to be used by Activity framework subclasses that control a
1430      * set of child activities, such as ActivityGroup.  The same guarantees and restrictions apply
1431      * as for {@link #onRetainNonConfigurationInstance()}.  The default implementation returns null.
1432      */
onRetainNonConfigurationChildInstances()1433     HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1434         return null;
1435     }
1436 
onLowMemory()1437     public void onLowMemory() {
1438         mCalled = true;
1439     }
1440 
1441     /**
1442      * Wrapper around
1443      * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1444      * that gives the resulting {@link Cursor} to call
1445      * {@link #startManagingCursor} so that the activity will manage its
1446      * lifecycle for you.
1447      *
1448      * @param uri The URI of the content provider to query.
1449      * @param projection List of columns to return.
1450      * @param selection SQL WHERE clause.
1451      * @param sortOrder SQL ORDER BY clause.
1452      *
1453      * @return The Cursor that was returned by query().
1454      *
1455      * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1456      * @see #startManagingCursor
1457      * @hide
1458      */
managedQuery(Uri uri, String[] projection, String selection, String sortOrder)1459     public final Cursor managedQuery(Uri uri,
1460                                      String[] projection,
1461                                      String selection,
1462                                      String sortOrder)
1463     {
1464         Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1465         if (c != null) {
1466             startManagingCursor(c);
1467         }
1468         return c;
1469     }
1470 
1471     /**
1472      * Wrapper around
1473      * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1474      * that gives the resulting {@link Cursor} to call
1475      * {@link #startManagingCursor} so that the activity will manage its
1476      * lifecycle for you.
1477      *
1478      * @param uri The URI of the content provider to query.
1479      * @param projection List of columns to return.
1480      * @param selection SQL WHERE clause.
1481      * @param selectionArgs The arguments to selection, if any ?s are pesent
1482      * @param sortOrder SQL ORDER BY clause.
1483      *
1484      * @return The Cursor that was returned by query().
1485      *
1486      * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1487      * @see #startManagingCursor
1488      */
managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)1489     public final Cursor managedQuery(Uri uri,
1490                                      String[] projection,
1491                                      String selection,
1492                                      String[] selectionArgs,
1493                                      String sortOrder)
1494     {
1495         Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1496         if (c != null) {
1497             startManagingCursor(c);
1498         }
1499         return c;
1500     }
1501 
1502     /**
1503      * Wrapper around {@link Cursor#commitUpdates()} that takes care of noting
1504      * that the Cursor needs to be requeried.  You can call this method in
1505      * {@link #onPause} or {@link #onStop} to have the system call
1506      * {@link Cursor#requery} for you if the activity is later resumed.  This
1507      * allows you to avoid determing when to do the requery yourself (which is
1508      * required for the Cursor to see any data changes that were committed with
1509      * it).
1510      *
1511      * @param c The Cursor whose changes are to be committed.
1512      *
1513      * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1514      * @see #startManagingCursor
1515      * @see Cursor#commitUpdates()
1516      * @see Cursor#requery
1517      * @hide
1518      */
1519     @Deprecated
managedCommitUpdates(Cursor c)1520     public void managedCommitUpdates(Cursor c) {
1521         synchronized (mManagedCursors) {
1522             final int N = mManagedCursors.size();
1523             for (int i=0; i<N; i++) {
1524                 ManagedCursor mc = mManagedCursors.get(i);
1525                 if (mc.mCursor == c) {
1526                     c.commitUpdates();
1527                     mc.mUpdated = true;
1528                     return;
1529                 }
1530             }
1531             throw new RuntimeException(
1532                 "Cursor " + c + " is not currently managed");
1533         }
1534     }
1535 
1536     /**
1537      * This method allows the activity to take care of managing the given
1538      * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1539      * That is, when the activity is stopped it will automatically call
1540      * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1541      * it will call {@link Cursor#requery} for you.  When the activity is
1542      * destroyed, all managed Cursors will be closed automatically.
1543      *
1544      * @param c The Cursor to be managed.
1545      *
1546      * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1547      * @see #stopManagingCursor
1548      */
startManagingCursor(Cursor c)1549     public void startManagingCursor(Cursor c) {
1550         synchronized (mManagedCursors) {
1551             mManagedCursors.add(new ManagedCursor(c));
1552         }
1553     }
1554 
1555     /**
1556      * Given a Cursor that was previously given to
1557      * {@link #startManagingCursor}, stop the activity's management of that
1558      * cursor.
1559      *
1560      * @param c The Cursor that was being managed.
1561      *
1562      * @see #startManagingCursor
1563      */
stopManagingCursor(Cursor c)1564     public void stopManagingCursor(Cursor c) {
1565         synchronized (mManagedCursors) {
1566             final int N = mManagedCursors.size();
1567             for (int i=0; i<N; i++) {
1568                 ManagedCursor mc = mManagedCursors.get(i);
1569                 if (mc.mCursor == c) {
1570                     mManagedCursors.remove(i);
1571                     break;
1572                 }
1573             }
1574         }
1575     }
1576 
1577     /**
1578      * Control whether this activity is required to be persistent.  By default
1579      * activities are not persistent; setting this to true will prevent the
1580      * system from stopping this activity or its process when running low on
1581      * resources.
1582      *
1583      * <p><em>You should avoid using this method</em>, it has severe negative
1584      * consequences on how well the system can manage its resources.  A better
1585      * approach is to implement an application service that you control with
1586      * {@link Context#startService} and {@link Context#stopService}.
1587      *
1588      * @param isPersistent Control whether the current activity must be
1589      *                     persistent, true if so, false for the normal
1590      *                     behavior.
1591      */
setPersistent(boolean isPersistent)1592     public void setPersistent(boolean isPersistent) {
1593         if (mParent == null) {
1594             try {
1595                 ActivityManagerNative.getDefault()
1596                     .setPersistent(mToken, isPersistent);
1597             } catch (RemoteException e) {
1598                 // Empty
1599             }
1600         } else {
1601             throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1602         }
1603     }
1604 
1605     /**
1606      * Finds a view that was identified by the id attribute from the XML that
1607      * was processed in {@link #onCreate}.
1608      *
1609      * @return The view if found or null otherwise.
1610      */
findViewById(int id)1611     public View findViewById(int id) {
1612         return getWindow().findViewById(id);
1613     }
1614 
1615     /**
1616      * Set the activity content from a layout resource.  The resource will be
1617      * inflated, adding all top-level views to the activity.
1618      *
1619      * @param layoutResID Resource ID to be inflated.
1620      */
setContentView(int layoutResID)1621     public void setContentView(int layoutResID) {
1622         getWindow().setContentView(layoutResID);
1623     }
1624 
1625     /**
1626      * Set the activity content to an explicit view.  This view is placed
1627      * directly into the activity's view hierarchy.  It can itself be a complex
1628      * view hierarhcy.
1629      *
1630      * @param view The desired content to display.
1631      */
setContentView(View view)1632     public void setContentView(View view) {
1633         getWindow().setContentView(view);
1634     }
1635 
1636     /**
1637      * Set the activity content to an explicit view.  This view is placed
1638      * directly into the activity's view hierarchy.  It can itself be a complex
1639      * view hierarhcy.
1640      *
1641      * @param view The desired content to display.
1642      * @param params Layout parameters for the view.
1643      */
setContentView(View view, ViewGroup.LayoutParams params)1644     public void setContentView(View view, ViewGroup.LayoutParams params) {
1645         getWindow().setContentView(view, params);
1646     }
1647 
1648     /**
1649      * Add an additional content view to the activity.  Added after any existing
1650      * ones in the activity -- existing views are NOT removed.
1651      *
1652      * @param view The desired content to display.
1653      * @param params Layout parameters for the view.
1654      */
addContentView(View view, ViewGroup.LayoutParams params)1655     public void addContentView(View view, ViewGroup.LayoutParams params) {
1656         getWindow().addContentView(view, params);
1657     }
1658 
1659     /**
1660      * Use with {@link #setDefaultKeyMode} to turn off default handling of
1661      * keys.
1662      *
1663      * @see #setDefaultKeyMode
1664      */
1665     static public final int DEFAULT_KEYS_DISABLE = 0;
1666     /**
1667      * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1668      * key handling.
1669      *
1670      * @see #setDefaultKeyMode
1671      */
1672     static public final int DEFAULT_KEYS_DIALER = 1;
1673     /**
1674      * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1675      * default key handling.
1676      *
1677      * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1678      *
1679      * @see #setDefaultKeyMode
1680      */
1681     static public final int DEFAULT_KEYS_SHORTCUT = 2;
1682     /**
1683      * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1684      * will start an application-defined search.  (If the application or activity does not
1685      * actually define a search, the the keys will be ignored.)
1686      *
1687      * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1688      *
1689      * @see #setDefaultKeyMode
1690      */
1691     static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1692 
1693     /**
1694      * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1695      * will start a global search (typically web search, but some platforms may define alternate
1696      * methods for global search)
1697      *
1698      * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1699      *
1700      * @see #setDefaultKeyMode
1701      */
1702     static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1703 
1704     /**
1705      * Select the default key handling for this activity.  This controls what
1706      * will happen to key events that are not otherwise handled.  The default
1707      * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1708      * floor. Other modes allow you to launch the dialer
1709      * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1710      * menu without requiring the menu key be held down
1711      * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1712      * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1713      *
1714      * <p>Note that the mode selected here does not impact the default
1715      * handling of system keys, such as the "back" and "menu" keys, and your
1716      * activity and its views always get a first chance to receive and handle
1717      * all application keys.
1718      *
1719      * @param mode The desired default key mode constant.
1720      *
1721      * @see #DEFAULT_KEYS_DISABLE
1722      * @see #DEFAULT_KEYS_DIALER
1723      * @see #DEFAULT_KEYS_SHORTCUT
1724      * @see #DEFAULT_KEYS_SEARCH_LOCAL
1725      * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1726      * @see #onKeyDown
1727      */
setDefaultKeyMode(int mode)1728     public final void setDefaultKeyMode(int mode) {
1729         mDefaultKeyMode = mode;
1730 
1731         // Some modes use a SpannableStringBuilder to track & dispatch input events
1732         // This list must remain in sync with the switch in onKeyDown()
1733         switch (mode) {
1734         case DEFAULT_KEYS_DISABLE:
1735         case DEFAULT_KEYS_SHORTCUT:
1736             mDefaultKeySsb = null;      // not used in these modes
1737             break;
1738         case DEFAULT_KEYS_DIALER:
1739         case DEFAULT_KEYS_SEARCH_LOCAL:
1740         case DEFAULT_KEYS_SEARCH_GLOBAL:
1741             mDefaultKeySsb = new SpannableStringBuilder();
1742             Selection.setSelection(mDefaultKeySsb,0);
1743             break;
1744         default:
1745             throw new IllegalArgumentException();
1746         }
1747     }
1748 
1749     /**
1750      * Called when a key was pressed down and not handled by any of the views
1751      * inside of the activity. So, for example, key presses while the cursor
1752      * is inside a TextView will not trigger the event (unless it is a navigation
1753      * to another object) because TextView handles its own key presses.
1754      *
1755      * <p>If the focused view didn't want this event, this method is called.
1756      *
1757      * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1758      * by calling {@link #onBackPressed()}, though the behavior varies based
1759      * on the application compatibility mode: for
1760      * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1761      * it will set up the dispatch to call {@link #onKeyUp} where the action
1762      * will be performed; for earlier applications, it will perform the
1763      * action immediately in on-down, as those versions of the platform
1764      * behaved.
1765      *
1766      * <p>Other additional default key handling may be performed
1767      * if configured with {@link #setDefaultKeyMode}.
1768      *
1769      * @return Return <code>true</code> to prevent this event from being propagated
1770      * further, or <code>false</code> to indicate that you have not handled
1771      * this event and it should continue to be propagated.
1772      * @see #onKeyUp
1773      * @see android.view.KeyEvent
1774      */
onKeyDown(int keyCode, KeyEvent event)1775     public boolean onKeyDown(int keyCode, KeyEvent event)  {
1776         if (keyCode == KeyEvent.KEYCODE_BACK) {
1777             if (getApplicationInfo().targetSdkVersion
1778                     >= Build.VERSION_CODES.ECLAIR) {
1779                 event.startTracking();
1780             } else {
1781                 onBackPressed();
1782             }
1783             return true;
1784         }
1785 
1786         if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1787             return false;
1788         } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
1789             if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1790                     keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1791                 return true;
1792             }
1793             return false;
1794         } else {
1795             // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1796             boolean clearSpannable = false;
1797             boolean handled;
1798             if ((event.getRepeatCount() != 0) || event.isSystem()) {
1799                 clearSpannable = true;
1800                 handled = false;
1801             } else {
1802                 handled = TextKeyListener.getInstance().onKeyDown(
1803                         null, mDefaultKeySsb, keyCode, event);
1804                 if (handled && mDefaultKeySsb.length() > 0) {
1805                     // something useable has been typed - dispatch it now.
1806 
1807                     final String str = mDefaultKeySsb.toString();
1808                     clearSpannable = true;
1809 
1810                     switch (mDefaultKeyMode) {
1811                     case DEFAULT_KEYS_DIALER:
1812                         Intent intent = new Intent(Intent.ACTION_DIAL,  Uri.parse("tel:" + str));
1813                         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1814                         startActivity(intent);
1815                         break;
1816                     case DEFAULT_KEYS_SEARCH_LOCAL:
1817                         startSearch(str, false, null, false);
1818                         break;
1819                     case DEFAULT_KEYS_SEARCH_GLOBAL:
1820                         startSearch(str, false, null, true);
1821                         break;
1822                     }
1823                 }
1824             }
1825             if (clearSpannable) {
1826                 mDefaultKeySsb.clear();
1827                 mDefaultKeySsb.clearSpans();
1828                 Selection.setSelection(mDefaultKeySsb,0);
1829             }
1830             return handled;
1831         }
1832     }
1833 
1834     /**
1835      * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
1836      * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
1837      * the event).
1838      */
onKeyLongPress(int keyCode, KeyEvent event)1839     public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1840         return false;
1841     }
1842 
1843     /**
1844      * Called when a key was released and not handled by any of the views
1845      * inside of the activity. So, for example, key presses while the cursor
1846      * is inside a TextView will not trigger the event (unless it is a navigation
1847      * to another object) because TextView handles its own key presses.
1848      *
1849      * <p>The default implementation handles KEYCODE_BACK to stop the activity
1850      * and go back.
1851      *
1852      * @return Return <code>true</code> to prevent this event from being propagated
1853      * further, or <code>false</code> to indicate that you have not handled
1854      * this event and it should continue to be propagated.
1855      * @see #onKeyDown
1856      * @see KeyEvent
1857      */
onKeyUp(int keyCode, KeyEvent event)1858     public boolean onKeyUp(int keyCode, KeyEvent event) {
1859         if (getApplicationInfo().targetSdkVersion
1860                 >= Build.VERSION_CODES.ECLAIR) {
1861             if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
1862                     && !event.isCanceled()) {
1863                 onBackPressed();
1864                 return true;
1865             }
1866         }
1867         return false;
1868     }
1869 
1870     /**
1871      * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
1872      * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
1873      * the event).
1874      */
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)1875     public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
1876         return false;
1877     }
1878 
1879     /**
1880      * Called when the activity has detected the user's press of the back
1881      * key.  The default implementation simply finishes the current activity,
1882      * but you can override this to do whatever you want.
1883      */
onBackPressed()1884     public void onBackPressed() {
1885         finish();
1886     }
1887 
1888     /**
1889      * Called when a touch screen event was not handled by any of the views
1890      * under it.  This is most useful to process touch events that happen
1891      * outside of your window bounds, where there is no view to receive it.
1892      *
1893      * @param event The touch screen event being processed.
1894      *
1895      * @return Return true if you have consumed the event, false if you haven't.
1896      * The default implementation always returns false.
1897      */
onTouchEvent(MotionEvent event)1898     public boolean onTouchEvent(MotionEvent event) {
1899         return false;
1900     }
1901 
1902     /**
1903      * Called when the trackball was moved and not handled by any of the
1904      * views inside of the activity.  So, for example, if the trackball moves
1905      * while focus is on a button, you will receive a call here because
1906      * buttons do not normally do anything with trackball events.  The call
1907      * here happens <em>before</em> trackball movements are converted to
1908      * DPAD key events, which then get sent back to the view hierarchy, and
1909      * will be processed at the point for things like focus navigation.
1910      *
1911      * @param event The trackball event being processed.
1912      *
1913      * @return Return true if you have consumed the event, false if you haven't.
1914      * The default implementation always returns false.
1915      */
onTrackballEvent(MotionEvent event)1916     public boolean onTrackballEvent(MotionEvent event) {
1917         return false;
1918     }
1919 
1920     /**
1921      * Called whenever a key, touch, or trackball event is dispatched to the
1922      * activity.  Implement this method if you wish to know that the user has
1923      * interacted with the device in some way while your activity is running.
1924      * This callback and {@link #onUserLeaveHint} are intended to help
1925      * activities manage status bar notifications intelligently; specifically,
1926      * for helping activities determine the proper time to cancel a notfication.
1927      *
1928      * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
1929      * be accompanied by calls to {@link #onUserInteraction}.  This
1930      * ensures that your activity will be told of relevant user activity such
1931      * as pulling down the notification pane and touching an item there.
1932      *
1933      * <p>Note that this callback will be invoked for the touch down action
1934      * that begins a touch gesture, but may not be invoked for the touch-moved
1935      * and touch-up actions that follow.
1936      *
1937      * @see #onUserLeaveHint()
1938      */
onUserInteraction()1939     public void onUserInteraction() {
1940     }
1941 
onWindowAttributesChanged(WindowManager.LayoutParams params)1942     public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
1943         // Update window manager if: we have a view, that view is
1944         // attached to its parent (which will be a RootView), and
1945         // this activity is not embedded.
1946         if (mParent == null) {
1947             View decor = mDecor;
1948             if (decor != null && decor.getParent() != null) {
1949                 getWindowManager().updateViewLayout(decor, params);
1950             }
1951         }
1952     }
1953 
onContentChanged()1954     public void onContentChanged() {
1955     }
1956 
1957     /**
1958      * Called when the current {@link Window} of the activity gains or loses
1959      * focus.  This is the best indicator of whether this activity is visible
1960      * to the user.  The default implementation clears the key tracking
1961      * state, so should always be called.
1962      *
1963      * <p>Note that this provides information about global focus state, which
1964      * is managed independently of activity lifecycles.  As such, while focus
1965      * changes will generally have some relation to lifecycle changes (an
1966      * activity that is stopped will not generally get window focus), you
1967      * should not rely on any particular order between the callbacks here and
1968      * those in the other lifecycle methods such as {@link #onResume}.
1969      *
1970      * <p>As a general rule, however, a resumed activity will have window
1971      * focus...  unless it has displayed other dialogs or popups that take
1972      * input focus, in which case the activity itself will not have focus
1973      * when the other windows have it.  Likewise, the system may display
1974      * system-level windows (such as the status bar notification panel or
1975      * a system alert) which will temporarily take window input focus without
1976      * pausing the foreground activity.
1977      *
1978      * @param hasFocus Whether the window of this activity has focus.
1979      *
1980      * @see #hasWindowFocus()
1981      * @see #onResume
1982      * @see View#onWindowFocusChanged(boolean)
1983      */
onWindowFocusChanged(boolean hasFocus)1984     public void onWindowFocusChanged(boolean hasFocus) {
1985     }
1986 
1987     /**
1988      * Called when the main window associated with the activity has been
1989      * attached to the window manager.
1990      * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
1991      * for more information.
1992      * @see View#onAttachedToWindow
1993      */
onAttachedToWindow()1994     public void onAttachedToWindow() {
1995     }
1996 
1997     /**
1998      * Called when the main window associated with the activity has been
1999      * detached from the window manager.
2000      * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2001      * for more information.
2002      * @see View#onDetachedFromWindow
2003      */
onDetachedFromWindow()2004     public void onDetachedFromWindow() {
2005     }
2006 
2007     /**
2008      * Returns true if this activity's <em>main</em> window currently has window focus.
2009      * Note that this is not the same as the view itself having focus.
2010      *
2011      * @return True if this activity's main window currently has window focus.
2012      *
2013      * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2014      */
hasWindowFocus()2015     public boolean hasWindowFocus() {
2016         Window w = getWindow();
2017         if (w != null) {
2018             View d = w.getDecorView();
2019             if (d != null) {
2020                 return d.hasWindowFocus();
2021             }
2022         }
2023         return false;
2024     }
2025 
2026     /**
2027      * Called to process key events.  You can override this to intercept all
2028      * key events before they are dispatched to the window.  Be sure to call
2029      * this implementation for key events that should be handled normally.
2030      *
2031      * @param event The key event.
2032      *
2033      * @return boolean Return true if this event was consumed.
2034      */
dispatchKeyEvent(KeyEvent event)2035     public boolean dispatchKeyEvent(KeyEvent event) {
2036         onUserInteraction();
2037         Window win = getWindow();
2038         if (win.superDispatchKeyEvent(event)) {
2039             return true;
2040         }
2041         View decor = mDecor;
2042         if (decor == null) decor = win.getDecorView();
2043         return event.dispatch(this, decor != null
2044                 ? decor.getKeyDispatcherState() : null, this);
2045     }
2046 
2047     /**
2048      * Called to process touch screen events.  You can override this to
2049      * intercept all touch screen events before they are dispatched to the
2050      * window.  Be sure to call this implementation for touch screen events
2051      * that should be handled normally.
2052      *
2053      * @param ev The touch screen event.
2054      *
2055      * @return boolean Return true if this event was consumed.
2056      */
dispatchTouchEvent(MotionEvent ev)2057     public boolean dispatchTouchEvent(MotionEvent ev) {
2058         if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2059             onUserInteraction();
2060         }
2061         if (getWindow().superDispatchTouchEvent(ev)) {
2062             return true;
2063         }
2064         return onTouchEvent(ev);
2065     }
2066 
2067     /**
2068      * Called to process trackball events.  You can override this to
2069      * intercept all trackball events before they are dispatched to the
2070      * window.  Be sure to call this implementation for trackball events
2071      * that should be handled normally.
2072      *
2073      * @param ev The trackball event.
2074      *
2075      * @return boolean Return true if this event was consumed.
2076      */
dispatchTrackballEvent(MotionEvent ev)2077     public boolean dispatchTrackballEvent(MotionEvent ev) {
2078         onUserInteraction();
2079         if (getWindow().superDispatchTrackballEvent(ev)) {
2080             return true;
2081         }
2082         return onTrackballEvent(ev);
2083     }
2084 
dispatchPopulateAccessibilityEvent(AccessibilityEvent event)2085     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2086         event.setClassName(getClass().getName());
2087         event.setPackageName(getPackageName());
2088 
2089         LayoutParams params = getWindow().getAttributes();
2090         boolean isFullScreen = (params.width == LayoutParams.FILL_PARENT) &&
2091             (params.height == LayoutParams.FILL_PARENT);
2092         event.setFullScreen(isFullScreen);
2093 
2094         CharSequence title = getTitle();
2095         if (!TextUtils.isEmpty(title)) {
2096            event.getText().add(title);
2097         }
2098 
2099         return true;
2100     }
2101 
2102     /**
2103      * Default implementation of
2104      * {@link android.view.Window.Callback#onCreatePanelView}
2105      * for activities. This
2106      * simply returns null so that all panel sub-windows will have the default
2107      * menu behavior.
2108      */
onCreatePanelView(int featureId)2109     public View onCreatePanelView(int featureId) {
2110         return null;
2111     }
2112 
2113     /**
2114      * Default implementation of
2115      * {@link android.view.Window.Callback#onCreatePanelMenu}
2116      * for activities.  This calls through to the new
2117      * {@link #onCreateOptionsMenu} method for the
2118      * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2119      * so that subclasses of Activity don't need to deal with feature codes.
2120      */
onCreatePanelMenu(int featureId, Menu menu)2121     public boolean onCreatePanelMenu(int featureId, Menu menu) {
2122         if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2123             return onCreateOptionsMenu(menu);
2124         }
2125         return false;
2126     }
2127 
2128     /**
2129      * Default implementation of
2130      * {@link android.view.Window.Callback#onPreparePanel}
2131      * for activities.  This
2132      * calls through to the new {@link #onPrepareOptionsMenu} method for the
2133      * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2134      * panel, so that subclasses of
2135      * Activity don't need to deal with feature codes.
2136      */
onPreparePanel(int featureId, View view, Menu menu)2137     public boolean onPreparePanel(int featureId, View view, Menu menu) {
2138         if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2139             boolean goforit = onPrepareOptionsMenu(menu);
2140             return goforit && menu.hasVisibleItems();
2141         }
2142         return true;
2143     }
2144 
2145     /**
2146      * {@inheritDoc}
2147      *
2148      * @return The default implementation returns true.
2149      */
onMenuOpened(int featureId, Menu menu)2150     public boolean onMenuOpened(int featureId, Menu menu) {
2151         return true;
2152     }
2153 
2154     /**
2155      * Default implementation of
2156      * {@link android.view.Window.Callback#onMenuItemSelected}
2157      * for activities.  This calls through to the new
2158      * {@link #onOptionsItemSelected} method for the
2159      * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2160      * panel, so that subclasses of
2161      * Activity don't need to deal with feature codes.
2162      */
onMenuItemSelected(int featureId, MenuItem item)2163     public boolean onMenuItemSelected(int featureId, MenuItem item) {
2164         switch (featureId) {
2165             case Window.FEATURE_OPTIONS_PANEL:
2166                 // Put event logging here so it gets called even if subclass
2167                 // doesn't call through to superclass's implmeentation of each
2168                 // of these methods below
2169                 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
2170                 return onOptionsItemSelected(item);
2171 
2172             case Window.FEATURE_CONTEXT_MENU:
2173                 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
2174                 return onContextItemSelected(item);
2175 
2176             default:
2177                 return false;
2178         }
2179     }
2180 
2181     /**
2182      * Default implementation of
2183      * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2184      * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2185      * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2186      * so that subclasses of Activity don't need to deal with feature codes.
2187      * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2188      * {@link #onContextMenuClosed(Menu)} will be called.
2189      */
onPanelClosed(int featureId, Menu menu)2190     public void onPanelClosed(int featureId, Menu menu) {
2191         switch (featureId) {
2192             case Window.FEATURE_OPTIONS_PANEL:
2193                 onOptionsMenuClosed(menu);
2194                 break;
2195 
2196             case Window.FEATURE_CONTEXT_MENU:
2197                 onContextMenuClosed(menu);
2198                 break;
2199         }
2200     }
2201 
2202     /**
2203      * Initialize the contents of the Activity's standard options menu.  You
2204      * should place your menu items in to <var>menu</var>.
2205      *
2206      * <p>This is only called once, the first time the options menu is
2207      * displayed.  To update the menu every time it is displayed, see
2208      * {@link #onPrepareOptionsMenu}.
2209      *
2210      * <p>The default implementation populates the menu with standard system
2211      * menu items.  These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2212      * they will be correctly ordered with application-defined menu items.
2213      * Deriving classes should always call through to the base implementation.
2214      *
2215      * <p>You can safely hold on to <var>menu</var> (and any items created
2216      * from it), making modifications to it as desired, until the next
2217      * time onCreateOptionsMenu() is called.
2218      *
2219      * <p>When you add items to the menu, you can implement the Activity's
2220      * {@link #onOptionsItemSelected} method to handle them there.
2221      *
2222      * @param menu The options menu in which you place your items.
2223      *
2224      * @return You must return true for the menu to be displayed;
2225      *         if you return false it will not be shown.
2226      *
2227      * @see #onPrepareOptionsMenu
2228      * @see #onOptionsItemSelected
2229      */
onCreateOptionsMenu(Menu menu)2230     public boolean onCreateOptionsMenu(Menu menu) {
2231         if (mParent != null) {
2232             return mParent.onCreateOptionsMenu(menu);
2233         }
2234         return true;
2235     }
2236 
2237     /**
2238      * Prepare the Screen's standard options menu to be displayed.  This is
2239      * called right before the menu is shown, every time it is shown.  You can
2240      * use this method to efficiently enable/disable items or otherwise
2241      * dynamically modify the contents.
2242      *
2243      * <p>The default implementation updates the system menu items based on the
2244      * activity's state.  Deriving classes should always call through to the
2245      * base class implementation.
2246      *
2247      * @param menu The options menu as last shown or first initialized by
2248      *             onCreateOptionsMenu().
2249      *
2250      * @return You must return true for the menu to be displayed;
2251      *         if you return false it will not be shown.
2252      *
2253      * @see #onCreateOptionsMenu
2254      */
onPrepareOptionsMenu(Menu menu)2255     public boolean onPrepareOptionsMenu(Menu menu) {
2256         if (mParent != null) {
2257             return mParent.onPrepareOptionsMenu(menu);
2258         }
2259         return true;
2260     }
2261 
2262     /**
2263      * This hook is called whenever an item in your options menu is selected.
2264      * The default implementation simply returns false to have the normal
2265      * processing happen (calling the item's Runnable or sending a message to
2266      * its Handler as appropriate).  You can use this method for any items
2267      * for which you would like to do processing without those other
2268      * facilities.
2269      *
2270      * <p>Derived classes should call through to the base class for it to
2271      * perform the default menu handling.
2272      *
2273      * @param item The menu item that was selected.
2274      *
2275      * @return boolean Return false to allow normal menu processing to
2276      *         proceed, true to consume it here.
2277      *
2278      * @see #onCreateOptionsMenu
2279      */
onOptionsItemSelected(MenuItem item)2280     public boolean onOptionsItemSelected(MenuItem item) {
2281         if (mParent != null) {
2282             return mParent.onOptionsItemSelected(item);
2283         }
2284         return false;
2285     }
2286 
2287     /**
2288      * This hook is called whenever the options menu is being closed (either by the user canceling
2289      * the menu with the back/menu button, or when an item is selected).
2290      *
2291      * @param menu The options menu as last shown or first initialized by
2292      *             onCreateOptionsMenu().
2293      */
onOptionsMenuClosed(Menu menu)2294     public void onOptionsMenuClosed(Menu menu) {
2295         if (mParent != null) {
2296             mParent.onOptionsMenuClosed(menu);
2297         }
2298     }
2299 
2300     /**
2301      * Programmatically opens the options menu. If the options menu is already
2302      * open, this method does nothing.
2303      */
openOptionsMenu()2304     public void openOptionsMenu() {
2305         mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2306     }
2307 
2308     /**
2309      * Progammatically closes the options menu. If the options menu is already
2310      * closed, this method does nothing.
2311      */
closeOptionsMenu()2312     public void closeOptionsMenu() {
2313         mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2314     }
2315 
2316     /**
2317      * Called when a context menu for the {@code view} is about to be shown.
2318      * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2319      * time the context menu is about to be shown and should be populated for
2320      * the view (or item inside the view for {@link AdapterView} subclasses,
2321      * this can be found in the {@code menuInfo})).
2322      * <p>
2323      * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2324      * item has been selected.
2325      * <p>
2326      * It is not safe to hold onto the context menu after this method returns.
2327      * {@inheritDoc}
2328      */
onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)2329     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2330     }
2331 
2332     /**
2333      * Registers a context menu to be shown for the given view (multiple views
2334      * can show the context menu). This method will set the
2335      * {@link OnCreateContextMenuListener} on the view to this activity, so
2336      * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2337      * called when it is time to show the context menu.
2338      *
2339      * @see #unregisterForContextMenu(View)
2340      * @param view The view that should show a context menu.
2341      */
registerForContextMenu(View view)2342     public void registerForContextMenu(View view) {
2343         view.setOnCreateContextMenuListener(this);
2344     }
2345 
2346     /**
2347      * Prevents a context menu to be shown for the given view. This method will remove the
2348      * {@link OnCreateContextMenuListener} on the view.
2349      *
2350      * @see #registerForContextMenu(View)
2351      * @param view The view that should stop showing a context menu.
2352      */
unregisterForContextMenu(View view)2353     public void unregisterForContextMenu(View view) {
2354         view.setOnCreateContextMenuListener(null);
2355     }
2356 
2357     /**
2358      * Programmatically opens the context menu for a particular {@code view}.
2359      * The {@code view} should have been added via
2360      * {@link #registerForContextMenu(View)}.
2361      *
2362      * @param view The view to show the context menu for.
2363      */
openContextMenu(View view)2364     public void openContextMenu(View view) {
2365         view.showContextMenu();
2366     }
2367 
2368     /**
2369      * Programmatically closes the most recently opened context menu, if showing.
2370      */
closeContextMenu()2371     public void closeContextMenu() {
2372         mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2373     }
2374 
2375     /**
2376      * This hook is called whenever an item in a context menu is selected. The
2377      * default implementation simply returns false to have the normal processing
2378      * happen (calling the item's Runnable or sending a message to its Handler
2379      * as appropriate). You can use this method for any items for which you
2380      * would like to do processing without those other facilities.
2381      * <p>
2382      * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2383      * View that added this menu item.
2384      * <p>
2385      * Derived classes should call through to the base class for it to perform
2386      * the default menu handling.
2387      *
2388      * @param item The context menu item that was selected.
2389      * @return boolean Return false to allow normal context menu processing to
2390      *         proceed, true to consume it here.
2391      */
onContextItemSelected(MenuItem item)2392     public boolean onContextItemSelected(MenuItem item) {
2393         if (mParent != null) {
2394             return mParent.onContextItemSelected(item);
2395         }
2396         return false;
2397     }
2398 
2399     /**
2400      * This hook is called whenever the context menu is being closed (either by
2401      * the user canceling the menu with the back/menu button, or when an item is
2402      * selected).
2403      *
2404      * @param menu The context menu that is being closed.
2405      */
onContextMenuClosed(Menu menu)2406     public void onContextMenuClosed(Menu menu) {
2407         if (mParent != null) {
2408             mParent.onContextMenuClosed(menu);
2409         }
2410     }
2411 
2412     /**
2413      * Callback for creating dialogs that are managed (saved and restored) for you
2414      * by the activity.
2415      *
2416      * If you use {@link #showDialog(int)}, the activity will call through to
2417      * this method the first time, and hang onto it thereafter.  Any dialog
2418      * that is created by this method will automatically be saved and restored
2419      * for you, including whether it is showing.
2420      *
2421      * If you would like the activity to manage the saving and restoring dialogs
2422      * for you, you should override this method and handle any ids that are
2423      * passed to {@link #showDialog}.
2424      *
2425      * If you would like an opportunity to prepare your dialog before it is shown,
2426      * override {@link #onPrepareDialog(int, Dialog)}.
2427      *
2428      * @param id The id of the dialog.
2429      * @return The dialog
2430      *
2431      * @see #onPrepareDialog(int, Dialog)
2432      * @see #showDialog(int)
2433      * @see #dismissDialog(int)
2434      * @see #removeDialog(int)
2435      */
onCreateDialog(int id)2436     protected Dialog onCreateDialog(int id) {
2437         return null;
2438     }
2439 
2440     /**
2441      * Provides an opportunity to prepare a managed dialog before it is being
2442      * shown.
2443      * <p>
2444      * Override this if you need to update a managed dialog based on the state
2445      * of the application each time it is shown. For example, a time picker
2446      * dialog might want to be updated with the current time. You should call
2447      * through to the superclass's implementation. The default implementation
2448      * will set this Activity as the owner activity on the Dialog.
2449      *
2450      * @param id The id of the managed dialog.
2451      * @param dialog The dialog.
2452      * @see #onCreateDialog(int)
2453      * @see #showDialog(int)
2454      * @see #dismissDialog(int)
2455      * @see #removeDialog(int)
2456      */
onPrepareDialog(int id, Dialog dialog)2457     protected void onPrepareDialog(int id, Dialog dialog) {
2458         dialog.setOwnerActivity(this);
2459     }
2460 
2461     /**
2462      * Show a dialog managed by this activity.  A call to {@link #onCreateDialog(int)}
2463      * will be made with the same id the first time this is called for a given
2464      * id.  From thereafter, the dialog will be automatically saved and restored.
2465      *
2466      * Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog)} will
2467      * be made to provide an opportunity to do any timely preparation.
2468      *
2469      * @param id The id of the managed dialog.
2470      *
2471      * @see Dialog
2472      * @see #onCreateDialog(int)
2473      * @see #onPrepareDialog(int, Dialog)
2474      * @see #dismissDialog(int)
2475      * @see #removeDialog(int)
2476      */
showDialog(int id)2477     public final void showDialog(int id) {
2478         if (mManagedDialogs == null) {
2479             mManagedDialogs = new SparseArray<Dialog>();
2480         }
2481         Dialog dialog = mManagedDialogs.get(id);
2482         if (dialog == null) {
2483             dialog = createDialog(id, null);
2484             mManagedDialogs.put(id, dialog);
2485         }
2486 
2487         onPrepareDialog(id, dialog);
2488         dialog.show();
2489     }
2490 
2491     /**
2492      * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2493      *
2494      * @param id The id of the managed dialog.
2495      *
2496      * @throws IllegalArgumentException if the id was not previously shown via
2497      *   {@link #showDialog(int)}.
2498      *
2499      * @see #onCreateDialog(int)
2500      * @see #onPrepareDialog(int, Dialog)
2501      * @see #showDialog(int)
2502      * @see #removeDialog(int)
2503      */
dismissDialog(int id)2504     public final void dismissDialog(int id) {
2505         if (mManagedDialogs == null) {
2506             throw missingDialog(id);
2507 
2508         }
2509         final Dialog dialog = mManagedDialogs.get(id);
2510         if (dialog == null) {
2511             throw missingDialog(id);
2512         }
2513         dialog.dismiss();
2514     }
2515 
2516     /**
2517      * Creates an exception to throw if a user passed in a dialog id that is
2518      * unexpected.
2519      */
missingDialog(int id)2520     private IllegalArgumentException missingDialog(int id) {
2521         return new IllegalArgumentException("no dialog with id " + id + " was ever "
2522                 + "shown via Activity#showDialog");
2523     }
2524 
2525     /**
2526      * Removes any internal references to a dialog managed by this Activity.
2527      * If the dialog is showing, it will dismiss it as part of the clean up.
2528      *
2529      * This can be useful if you know that you will never show a dialog again and
2530      * want to avoid the overhead of saving and restoring it in the future.
2531      *
2532      * @param id The id of the managed dialog.
2533      *
2534      * @see #onCreateDialog(int)
2535      * @see #onPrepareDialog(int, Dialog)
2536      * @see #showDialog(int)
2537      * @see #dismissDialog(int)
2538      */
removeDialog(int id)2539     public final void removeDialog(int id) {
2540 
2541         if (mManagedDialogs == null) {
2542             return;
2543         }
2544 
2545         final Dialog dialog = mManagedDialogs.get(id);
2546         if (dialog == null) {
2547             return;
2548         }
2549 
2550         dialog.dismiss();
2551         mManagedDialogs.remove(id);
2552     }
2553 
2554     /**
2555      * This hook is called when the user signals the desire to start a search.
2556      *
2557      * <p>You can use this function as a simple way to launch the search UI, in response to a
2558      * menu item, search button, or other widgets within your activity. Unless overidden,
2559      * calling this function is the same as calling
2560      * {@link #startSearch startSearch(null, false, null, false)}, which launches
2561      * search for the current activity as specified in its manifest, see {@link SearchManager}.
2562      *
2563      * <p>You can override this function to force global search, e.g. in response to a dedicated
2564      * search key, or to block search entirely (by simply returning false).
2565      *
2566      * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2567      *         The default implementation always returns {@code true}.
2568      *
2569      * @see android.app.SearchManager
2570      */
onSearchRequested()2571     public boolean onSearchRequested() {
2572         startSearch(null, false, null, false);
2573         return true;
2574     }
2575 
2576     /**
2577      * This hook is called to launch the search UI.
2578      *
2579      * <p>It is typically called from onSearchRequested(), either directly from
2580      * Activity.onSearchRequested() or from an overridden version in any given
2581      * Activity.  If your goal is simply to activate search, it is preferred to call
2582      * onSearchRequested(), which may have been overriden elsewhere in your Activity.  If your goal
2583      * is to inject specific data such as context data, it is preferred to <i>override</i>
2584      * onSearchRequested(), so that any callers to it will benefit from the override.
2585      *
2586      * @param initialQuery Any non-null non-empty string will be inserted as
2587      * pre-entered text in the search query box.
2588      * @param selectInitialQuery If true, the intial query will be preselected, which means that
2589      * any further typing will replace it.  This is useful for cases where an entire pre-formed
2590      * query is being inserted.  If false, the selection point will be placed at the end of the
2591      * inserted query.  This is useful when the inserted query is text that the user entered,
2592      * and the user would expect to be able to keep typing.  <i>This parameter is only meaningful
2593      * if initialQuery is a non-empty string.</i>
2594      * @param appSearchData An application can insert application-specific
2595      * context here, in order to improve quality or specificity of its own
2596      * searches.  This data will be returned with SEARCH intent(s).  Null if
2597      * no extra data is required.
2598      * @param globalSearch If false, this will only launch the search that has been specifically
2599      * defined by the application (which is usually defined as a local search).  If no default
2600      * search is defined in the current application or activity, global search will be launched.
2601      * If true, this will always launch a platform-global (e.g. web-based) search instead.
2602      *
2603      * @see android.app.SearchManager
2604      * @see #onSearchRequested
2605      */
startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch)2606     public void startSearch(String initialQuery, boolean selectInitialQuery,
2607             Bundle appSearchData, boolean globalSearch) {
2608         ensureSearchManager();
2609         mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
2610                         appSearchData, globalSearch);
2611     }
2612 
2613     /**
2614      * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2615      * the search dialog.  Made available for testing purposes.
2616      *
2617      * @param query The query to trigger.  If empty, the request will be ignored.
2618      * @param appSearchData An application can insert application-specific
2619      * context here, in order to improve quality or specificity of its own
2620      * searches.  This data will be returned with SEARCH intent(s).  Null if
2621      * no extra data is required.
2622      */
triggerSearch(String query, Bundle appSearchData)2623     public void triggerSearch(String query, Bundle appSearchData) {
2624         ensureSearchManager();
2625         mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
2626     }
2627 
2628     /**
2629      * Request that key events come to this activity. Use this if your
2630      * activity has no views with focus, but the activity still wants
2631      * a chance to process key events.
2632      *
2633      * @see android.view.Window#takeKeyEvents
2634      */
takeKeyEvents(boolean get)2635     public void takeKeyEvents(boolean get) {
2636         getWindow().takeKeyEvents(get);
2637     }
2638 
2639     /**
2640      * Enable extended window features.  This is a convenience for calling
2641      * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2642      *
2643      * @param featureId The desired feature as defined in
2644      *                  {@link android.view.Window}.
2645      * @return Returns true if the requested feature is supported and now
2646      *         enabled.
2647      *
2648      * @see android.view.Window#requestFeature
2649      */
requestWindowFeature(int featureId)2650     public final boolean requestWindowFeature(int featureId) {
2651         return getWindow().requestFeature(featureId);
2652     }
2653 
2654     /**
2655      * Convenience for calling
2656      * {@link android.view.Window#setFeatureDrawableResource}.
2657      */
setFeatureDrawableResource(int featureId, int resId)2658     public final void setFeatureDrawableResource(int featureId, int resId) {
2659         getWindow().setFeatureDrawableResource(featureId, resId);
2660     }
2661 
2662     /**
2663      * Convenience for calling
2664      * {@link android.view.Window#setFeatureDrawableUri}.
2665      */
setFeatureDrawableUri(int featureId, Uri uri)2666     public final void setFeatureDrawableUri(int featureId, Uri uri) {
2667         getWindow().setFeatureDrawableUri(featureId, uri);
2668     }
2669 
2670     /**
2671      * Convenience for calling
2672      * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2673      */
setFeatureDrawable(int featureId, Drawable drawable)2674     public final void setFeatureDrawable(int featureId, Drawable drawable) {
2675         getWindow().setFeatureDrawable(featureId, drawable);
2676     }
2677 
2678     /**
2679      * Convenience for calling
2680      * {@link android.view.Window#setFeatureDrawableAlpha}.
2681      */
setFeatureDrawableAlpha(int featureId, int alpha)2682     public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2683         getWindow().setFeatureDrawableAlpha(featureId, alpha);
2684     }
2685 
2686     /**
2687      * Convenience for calling
2688      * {@link android.view.Window#getLayoutInflater}.
2689      */
getLayoutInflater()2690     public LayoutInflater getLayoutInflater() {
2691         return getWindow().getLayoutInflater();
2692     }
2693 
2694     /**
2695      * Returns a {@link MenuInflater} with this context.
2696      */
getMenuInflater()2697     public MenuInflater getMenuInflater() {
2698         return new MenuInflater(this);
2699     }
2700 
2701     @Override
onApplyThemeResource(Resources.Theme theme, int resid, boolean first)2702     protected void onApplyThemeResource(Resources.Theme theme, int resid,
2703             boolean first) {
2704         if (mParent == null) {
2705             super.onApplyThemeResource(theme, resid, first);
2706         } else {
2707             try {
2708                 theme.setTo(mParent.getTheme());
2709             } catch (Exception e) {
2710                 // Empty
2711             }
2712             theme.applyStyle(resid, false);
2713         }
2714     }
2715 
2716     /**
2717      * Launch an activity for which you would like a result when it finished.
2718      * When this activity exits, your
2719      * onActivityResult() method will be called with the given requestCode.
2720      * Using a negative requestCode is the same as calling
2721      * {@link #startActivity} (the activity is not launched as a sub-activity).
2722      *
2723      * <p>Note that this method should only be used with Intent protocols
2724      * that are defined to return a result.  In other protocols (such as
2725      * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
2726      * not get the result when you expect.  For example, if the activity you
2727      * are launching uses the singleTask launch mode, it will not run in your
2728      * task and thus you will immediately receive a cancel result.
2729      *
2730      * <p>As a special case, if you call startActivityForResult() with a requestCode
2731      * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
2732      * activity, then your window will not be displayed until a result is
2733      * returned back from the started activity.  This is to avoid visible
2734      * flickering when redirecting to another activity.
2735      *
2736      * <p>This method throws {@link android.content.ActivityNotFoundException}
2737      * if there was no Activity found to run the given Intent.
2738      *
2739      * @param intent The intent to start.
2740      * @param requestCode If >= 0, this code will be returned in
2741      *                    onActivityResult() when the activity exits.
2742      *
2743      * @throws android.content.ActivityNotFoundException
2744      *
2745      * @see #startActivity
2746      */
startActivityForResult(Intent intent, int requestCode)2747     public void startActivityForResult(Intent intent, int requestCode) {
2748         if (mParent == null) {
2749             Instrumentation.ActivityResult ar =
2750                 mInstrumentation.execStartActivity(
2751                     this, mMainThread.getApplicationThread(), mToken, this,
2752                     intent, requestCode);
2753             if (ar != null) {
2754                 mMainThread.sendActivityResult(
2755                     mToken, mEmbeddedID, requestCode, ar.getResultCode(),
2756                     ar.getResultData());
2757             }
2758             if (requestCode >= 0) {
2759                 // If this start is requesting a result, we can avoid making
2760                 // the activity visible until the result is received.  Setting
2761                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2762                 // activity hidden during this time, to avoid flickering.
2763                 // This can only be done when a result is requested because
2764                 // that guarantees we will get information back when the
2765                 // activity is finished, no matter what happens to it.
2766                 mStartedActivity = true;
2767             }
2768         } else {
2769             mParent.startActivityFromChild(this, intent, requestCode);
2770         }
2771     }
2772 
2773     /**
2774      * Like {@link #startActivityForResult(Intent, int)}, but allowing you
2775      * to use a IntentSender to describe the activity to be started.  If
2776      * the IntentSender is for an activity, that activity will be started
2777      * as if you had called the regular {@link #startActivityForResult(Intent, int)}
2778      * here; otherwise, its associated action will be executed (such as
2779      * sending a broadcast) as if you had called
2780      * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
2781      *
2782      * @param intent The IntentSender to launch.
2783      * @param requestCode If >= 0, this code will be returned in
2784      *                    onActivityResult() when the activity exits.
2785      * @param fillInIntent If non-null, this will be provided as the
2786      * intent parameter to {@link IntentSender#sendIntent}.
2787      * @param flagsMask Intent flags in the original IntentSender that you
2788      * would like to change.
2789      * @param flagsValues Desired values for any bits set in
2790      * <var>flagsMask</var>
2791      * @param extraFlags Always set to 0.
2792      */
startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)2793     public void startIntentSenderForResult(IntentSender intent, int requestCode,
2794             Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2795             throws IntentSender.SendIntentException {
2796         if (mParent == null) {
2797             startIntentSenderForResultInner(intent, requestCode, fillInIntent,
2798                     flagsMask, flagsValues, this);
2799         } else {
2800             mParent.startIntentSenderFromChild(this, intent, requestCode,
2801                     fillInIntent, flagsMask, flagsValues, extraFlags);
2802         }
2803     }
2804 
startIntentSenderForResultInner(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)2805     private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
2806             Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
2807             throws IntentSender.SendIntentException {
2808         try {
2809             String resolvedType = null;
2810             if (fillInIntent != null) {
2811                 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
2812             }
2813             int result = ActivityManagerNative.getDefault()
2814                 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
2815                         fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
2816                         requestCode, flagsMask, flagsValues);
2817             if (result == IActivityManager.START_CANCELED) {
2818                 throw new IntentSender.SendIntentException();
2819             }
2820             Instrumentation.checkStartActivityResult(result, null);
2821         } catch (RemoteException e) {
2822         }
2823         if (requestCode >= 0) {
2824             // If this start is requesting a result, we can avoid making
2825             // the activity visible until the result is received.  Setting
2826             // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2827             // activity hidden during this time, to avoid flickering.
2828             // This can only be done when a result is requested because
2829             // that guarantees we will get information back when the
2830             // activity is finished, no matter what happens to it.
2831             mStartedActivity = true;
2832         }
2833     }
2834 
2835     /**
2836      * Launch a new activity.  You will not receive any information about when
2837      * the activity exits.  This implementation overrides the base version,
2838      * providing information about
2839      * the activity performing the launch.  Because of this additional
2840      * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
2841      * required; if not specified, the new activity will be added to the
2842      * task of the caller.
2843      *
2844      * <p>This method throws {@link android.content.ActivityNotFoundException}
2845      * if there was no Activity found to run the given Intent.
2846      *
2847      * @param intent The intent to start.
2848      *
2849      * @throws android.content.ActivityNotFoundException
2850      *
2851      * @see #startActivityForResult
2852      */
2853     @Override
startActivity(Intent intent)2854     public void startActivity(Intent intent) {
2855         startActivityForResult(intent, -1);
2856     }
2857 
2858     /**
2859      * Like {@link #startActivity(Intent)}, but taking a IntentSender
2860      * to start; see
2861      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
2862      * for more information.
2863      *
2864      * @param intent The IntentSender to launch.
2865      * @param fillInIntent If non-null, this will be provided as the
2866      * intent parameter to {@link IntentSender#sendIntent}.
2867      * @param flagsMask Intent flags in the original IntentSender that you
2868      * would like to change.
2869      * @param flagsValues Desired values for any bits set in
2870      * <var>flagsMask</var>
2871      * @param extraFlags Always set to 0.
2872      */
startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)2873     public void startIntentSender(IntentSender intent,
2874             Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2875             throws IntentSender.SendIntentException {
2876         startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
2877                 flagsValues, extraFlags);
2878     }
2879 
2880     /**
2881      * A special variation to launch an activity only if a new activity
2882      * instance is needed to handle the given Intent.  In other words, this is
2883      * just like {@link #startActivityForResult(Intent, int)} except: if you are
2884      * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
2885      * singleTask or singleTop
2886      * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
2887      * and the activity
2888      * that handles <var>intent</var> is the same as your currently running
2889      * activity, then a new instance is not needed.  In this case, instead of
2890      * the normal behavior of calling {@link #onNewIntent} this function will
2891      * return and you can handle the Intent yourself.
2892      *
2893      * <p>This function can only be called from a top-level activity; if it is
2894      * called from a child activity, a runtime exception will be thrown.
2895      *
2896      * @param intent The intent to start.
2897      * @param requestCode If >= 0, this code will be returned in
2898      *         onActivityResult() when the activity exits, as described in
2899      *         {@link #startActivityForResult}.
2900      *
2901      * @return If a new activity was launched then true is returned; otherwise
2902      *         false is returned and you must handle the Intent yourself.
2903      *
2904      * @see #startActivity
2905      * @see #startActivityForResult
2906      */
startActivityIfNeeded(Intent intent, int requestCode)2907     public boolean startActivityIfNeeded(Intent intent, int requestCode) {
2908         if (mParent == null) {
2909             int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
2910             try {
2911                 result = ActivityManagerNative.getDefault()
2912                     .startActivity(mMainThread.getApplicationThread(),
2913                             intent, intent.resolveTypeIfNeeded(
2914                                     getContentResolver()),
2915                             null, 0,
2916                             mToken, mEmbeddedID, requestCode, true, false);
2917             } catch (RemoteException e) {
2918                 // Empty
2919             }
2920 
2921             Instrumentation.checkStartActivityResult(result, intent);
2922 
2923             if (requestCode >= 0) {
2924                 // If this start is requesting a result, we can avoid making
2925                 // the activity visible until the result is received.  Setting
2926                 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2927                 // activity hidden during this time, to avoid flickering.
2928                 // This can only be done when a result is requested because
2929                 // that guarantees we will get information back when the
2930                 // activity is finished, no matter what happens to it.
2931                 mStartedActivity = true;
2932             }
2933             return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
2934         }
2935 
2936         throw new UnsupportedOperationException(
2937             "startActivityIfNeeded can only be called from a top-level activity");
2938     }
2939 
2940     /**
2941      * Special version of starting an activity, for use when you are replacing
2942      * other activity components.  You can use this to hand the Intent off
2943      * to the next Activity that can handle it.  You typically call this in
2944      * {@link #onCreate} with the Intent returned by {@link #getIntent}.
2945      *
2946      * @param intent The intent to dispatch to the next activity.  For
2947      * correct behavior, this must be the same as the Intent that started
2948      * your own activity; the only changes you can make are to the extras
2949      * inside of it.
2950      *
2951      * @return Returns a boolean indicating whether there was another Activity
2952      * to start: true if there was a next activity to start, false if there
2953      * wasn't.  In general, if true is returned you will then want to call
2954      * finish() on yourself.
2955      */
startNextMatchingActivity(Intent intent)2956     public boolean startNextMatchingActivity(Intent intent) {
2957         if (mParent == null) {
2958             try {
2959                 return ActivityManagerNative.getDefault()
2960                     .startNextMatchingActivity(mToken, intent);
2961             } catch (RemoteException e) {
2962                 // Empty
2963             }
2964             return false;
2965         }
2966 
2967         throw new UnsupportedOperationException(
2968             "startNextMatchingActivity can only be called from a top-level activity");
2969     }
2970 
2971     /**
2972      * This is called when a child activity of this one calls its
2973      * {@link #startActivity} or {@link #startActivityForResult} method.
2974      *
2975      * <p>This method throws {@link android.content.ActivityNotFoundException}
2976      * if there was no Activity found to run the given Intent.
2977      *
2978      * @param child The activity making the call.
2979      * @param intent The intent to start.
2980      * @param requestCode Reply request code.  < 0 if reply is not requested.
2981      *
2982      * @throws android.content.ActivityNotFoundException
2983      *
2984      * @see #startActivity
2985      * @see #startActivityForResult
2986      */
startActivityFromChild(Activity child, Intent intent, int requestCode)2987     public void startActivityFromChild(Activity child, Intent intent,
2988             int requestCode) {
2989         Instrumentation.ActivityResult ar =
2990             mInstrumentation.execStartActivity(
2991                 this, mMainThread.getApplicationThread(), mToken, child,
2992                 intent, requestCode);
2993         if (ar != null) {
2994             mMainThread.sendActivityResult(
2995                 mToken, child.mEmbeddedID, requestCode,
2996                 ar.getResultCode(), ar.getResultData());
2997         }
2998     }
2999 
3000     /**
3001      * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
3002      * taking a IntentSender; see
3003      * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
3004      * for more information.
3005      */
startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)3006     public void startIntentSenderFromChild(Activity child, IntentSender intent,
3007             int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3008             int extraFlags)
3009             throws IntentSender.SendIntentException {
3010         startIntentSenderForResultInner(intent, requestCode, fillInIntent,
3011                 flagsMask, flagsValues, child);
3012     }
3013 
3014     /**
3015      * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3016      * or {@link #finish} to specify an explicit transition animation to
3017      * perform next.
3018      * @param enterAnim A resource ID of the animation resource to use for
3019      * the incoming activity.  Use 0 for no animation.
3020      * @param exitAnim A resource ID of the animation resource to use for
3021      * the outgoing activity.  Use 0 for no animation.
3022      */
overridePendingTransition(int enterAnim, int exitAnim)3023     public void overridePendingTransition(int enterAnim, int exitAnim) {
3024         try {
3025             ActivityManagerNative.getDefault().overridePendingTransition(
3026                     mToken, getPackageName(), enterAnim, exitAnim);
3027         } catch (RemoteException e) {
3028         }
3029     }
3030 
3031     /**
3032      * Call this to set the result that your activity will return to its
3033      * caller.
3034      *
3035      * @param resultCode The result code to propagate back to the originating
3036      *                   activity, often RESULT_CANCELED or RESULT_OK
3037      *
3038      * @see #RESULT_CANCELED
3039      * @see #RESULT_OK
3040      * @see #RESULT_FIRST_USER
3041      * @see #setResult(int, Intent)
3042      */
setResult(int resultCode)3043     public final void setResult(int resultCode) {
3044         synchronized (this) {
3045             mResultCode = resultCode;
3046             mResultData = null;
3047         }
3048     }
3049 
3050     /**
3051      * Call this to set the result that your activity will return to its
3052      * caller.
3053      *
3054      * @param resultCode The result code to propagate back to the originating
3055      *                   activity, often RESULT_CANCELED or RESULT_OK
3056      * @param data The data to propagate back to the originating activity.
3057      *
3058      * @see #RESULT_CANCELED
3059      * @see #RESULT_OK
3060      * @see #RESULT_FIRST_USER
3061      * @see #setResult(int)
3062      */
setResult(int resultCode, Intent data)3063     public final void setResult(int resultCode, Intent data) {
3064         synchronized (this) {
3065             mResultCode = resultCode;
3066             mResultData = data;
3067         }
3068     }
3069 
3070     /**
3071      * Return the name of the package that invoked this activity.  This is who
3072      * the data in {@link #setResult setResult()} will be sent to.  You can
3073      * use this information to validate that the recipient is allowed to
3074      * receive the data.
3075      *
3076      * <p>Note: if the calling activity is not expecting a result (that is it
3077      * did not use the {@link #startActivityForResult}
3078      * form that includes a request code), then the calling package will be
3079      * null.
3080      *
3081      * @return The package of the activity that will receive your
3082      *         reply, or null if none.
3083      */
getCallingPackage()3084     public String getCallingPackage() {
3085         try {
3086             return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3087         } catch (RemoteException e) {
3088             return null;
3089         }
3090     }
3091 
3092     /**
3093      * Return the name of the activity that invoked this activity.  This is
3094      * who the data in {@link #setResult setResult()} will be sent to.  You
3095      * can use this information to validate that the recipient is allowed to
3096      * receive the data.
3097      *
3098      * <p>Note: if the calling activity is not expecting a result (that is it
3099      * did not use the {@link #startActivityForResult}
3100      * form that includes a request code), then the calling package will be
3101      * null.
3102      *
3103      * @return String The full name of the activity that will receive your
3104      *         reply, or null if none.
3105      */
getCallingActivity()3106     public ComponentName getCallingActivity() {
3107         try {
3108             return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3109         } catch (RemoteException e) {
3110             return null;
3111         }
3112     }
3113 
3114     /**
3115      * Control whether this activity's main window is visible.  This is intended
3116      * only for the special case of an activity that is not going to show a
3117      * UI itself, but can't just finish prior to onResume() because it needs
3118      * to wait for a service binding or such.  Setting this to false allows
3119      * you to prevent your UI from being shown during that time.
3120      *
3121      * <p>The default value for this is taken from the
3122      * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3123      */
setVisible(boolean visible)3124     public void setVisible(boolean visible) {
3125         if (mVisibleFromClient != visible) {
3126             mVisibleFromClient = visible;
3127             if (mVisibleFromServer) {
3128                 if (visible) makeVisible();
3129                 else mDecor.setVisibility(View.INVISIBLE);
3130             }
3131         }
3132     }
3133 
makeVisible()3134     void makeVisible() {
3135         if (!mWindowAdded) {
3136             ViewManager wm = getWindowManager();
3137             wm.addView(mDecor, getWindow().getAttributes());
3138             mWindowAdded = true;
3139         }
3140         mDecor.setVisibility(View.VISIBLE);
3141     }
3142 
3143     /**
3144      * Check to see whether this activity is in the process of finishing,
3145      * either because you called {@link #finish} on it or someone else
3146      * has requested that it finished.  This is often used in
3147      * {@link #onPause} to determine whether the activity is simply pausing or
3148      * completely finishing.
3149      *
3150      * @return If the activity is finishing, returns true; else returns false.
3151      *
3152      * @see #finish
3153      */
isFinishing()3154     public boolean isFinishing() {
3155         return mFinished;
3156     }
3157 
3158     /**
3159      * Call this when your activity is done and should be closed.  The
3160      * ActivityResult is propagated back to whoever launched you via
3161      * onActivityResult().
3162      */
finish()3163     public void finish() {
3164         if (mParent == null) {
3165             int resultCode;
3166             Intent resultData;
3167             synchronized (this) {
3168                 resultCode = mResultCode;
3169                 resultData = mResultData;
3170             }
3171             if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3172             try {
3173                 if (ActivityManagerNative.getDefault()
3174                     .finishActivity(mToken, resultCode, resultData)) {
3175                     mFinished = true;
3176                 }
3177             } catch (RemoteException e) {
3178                 // Empty
3179             }
3180         } else {
3181             mParent.finishFromChild(this);
3182         }
3183     }
3184 
3185     /**
3186      * This is called when a child activity of this one calls its
3187      * {@link #finish} method.  The default implementation simply calls
3188      * finish() on this activity (the parent), finishing the entire group.
3189      *
3190      * @param child The activity making the call.
3191      *
3192      * @see #finish
3193      */
finishFromChild(Activity child)3194     public void finishFromChild(Activity child) {
3195         finish();
3196     }
3197 
3198     /**
3199      * Force finish another activity that you had previously started with
3200      * {@link #startActivityForResult}.
3201      *
3202      * @param requestCode The request code of the activity that you had
3203      *                    given to startActivityForResult().  If there are multiple
3204      *                    activities started with this request code, they
3205      *                    will all be finished.
3206      */
finishActivity(int requestCode)3207     public void finishActivity(int requestCode) {
3208         if (mParent == null) {
3209             try {
3210                 ActivityManagerNative.getDefault()
3211                     .finishSubActivity(mToken, mEmbeddedID, requestCode);
3212             } catch (RemoteException e) {
3213                 // Empty
3214             }
3215         } else {
3216             mParent.finishActivityFromChild(this, requestCode);
3217         }
3218     }
3219 
3220     /**
3221      * This is called when a child activity of this one calls its
3222      * finishActivity().
3223      *
3224      * @param child The activity making the call.
3225      * @param requestCode Request code that had been used to start the
3226      *                    activity.
3227      */
finishActivityFromChild(Activity child, int requestCode)3228     public void finishActivityFromChild(Activity child, int requestCode) {
3229         try {
3230             ActivityManagerNative.getDefault()
3231                 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3232         } catch (RemoteException e) {
3233             // Empty
3234         }
3235     }
3236 
3237     /**
3238      * Called when an activity you launched exits, giving you the requestCode
3239      * you started it with, the resultCode it returned, and any additional
3240      * data from it.  The <var>resultCode</var> will be
3241      * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3242      * didn't return any result, or crashed during its operation.
3243      *
3244      * <p>You will receive this call immediately before onResume() when your
3245      * activity is re-starting.
3246      *
3247      * @param requestCode The integer request code originally supplied to
3248      *                    startActivityForResult(), allowing you to identify who this
3249      *                    result came from.
3250      * @param resultCode The integer result code returned by the child activity
3251      *                   through its setResult().
3252      * @param data An Intent, which can return result data to the caller
3253      *               (various data can be attached to Intent "extras").
3254      *
3255      * @see #startActivityForResult
3256      * @see #createPendingResult
3257      * @see #setResult(int)
3258      */
onActivityResult(int requestCode, int resultCode, Intent data)3259     protected void onActivityResult(int requestCode, int resultCode,
3260             Intent data) {
3261     }
3262 
3263     /**
3264      * Create a new PendingIntent object which you can hand to others
3265      * for them to use to send result data back to your
3266      * {@link #onActivityResult} callback.  The created object will be either
3267      * one-shot (becoming invalid after a result is sent back) or multiple
3268      * (allowing any number of results to be sent through it).
3269      *
3270      * @param requestCode Private request code for the sender that will be
3271      * associated with the result data when it is returned.  The sender can not
3272      * modify this value, allowing you to identify incoming results.
3273      * @param data Default data to supply in the result, which may be modified
3274      * by the sender.
3275      * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3276      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3277      * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3278      * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3279      * or any of the flags as supported by
3280      * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3281      * of the intent that can be supplied when the actual send happens.
3282      *
3283      * @return Returns an existing or new PendingIntent matching the given
3284      * parameters.  May return null only if
3285      * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3286      * supplied.
3287      *
3288      * @see PendingIntent
3289      */
createPendingResult(int requestCode, Intent data, int flags)3290     public PendingIntent createPendingResult(int requestCode, Intent data,
3291             int flags) {
3292         String packageName = getPackageName();
3293         try {
3294             IIntentSender target =
3295                 ActivityManagerNative.getDefault().getIntentSender(
3296                         IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3297                         mParent == null ? mToken : mParent.mToken,
3298                         mEmbeddedID, requestCode, data, null, flags);
3299             return target != null ? new PendingIntent(target) : null;
3300         } catch (RemoteException e) {
3301             // Empty
3302         }
3303         return null;
3304     }
3305 
3306     /**
3307      * Change the desired orientation of this activity.  If the activity
3308      * is currently in the foreground or otherwise impacting the screen
3309      * orientation, the screen will immediately be changed (possibly causing
3310      * the activity to be restarted). Otherwise, this will be used the next
3311      * time the activity is visible.
3312      *
3313      * @param requestedOrientation An orientation constant as used in
3314      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3315      */
setRequestedOrientation(int requestedOrientation)3316     public void setRequestedOrientation(int requestedOrientation) {
3317         if (mParent == null) {
3318             try {
3319                 ActivityManagerNative.getDefault().setRequestedOrientation(
3320                         mToken, requestedOrientation);
3321             } catch (RemoteException e) {
3322                 // Empty
3323             }
3324         } else {
3325             mParent.setRequestedOrientation(requestedOrientation);
3326         }
3327     }
3328 
3329     /**
3330      * Return the current requested orientation of the activity.  This will
3331      * either be the orientation requested in its component's manifest, or
3332      * the last requested orientation given to
3333      * {@link #setRequestedOrientation(int)}.
3334      *
3335      * @return Returns an orientation constant as used in
3336      * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3337      */
getRequestedOrientation()3338     public int getRequestedOrientation() {
3339         if (mParent == null) {
3340             try {
3341                 return ActivityManagerNative.getDefault()
3342                         .getRequestedOrientation(mToken);
3343             } catch (RemoteException e) {
3344                 // Empty
3345             }
3346         } else {
3347             return mParent.getRequestedOrientation();
3348         }
3349         return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3350     }
3351 
3352     /**
3353      * Return the identifier of the task this activity is in.  This identifier
3354      * will remain the same for the lifetime of the activity.
3355      *
3356      * @return Task identifier, an opaque integer.
3357      */
getTaskId()3358     public int getTaskId() {
3359         try {
3360             return ActivityManagerNative.getDefault()
3361                 .getTaskForActivity(mToken, false);
3362         } catch (RemoteException e) {
3363             return -1;
3364         }
3365     }
3366 
3367     /**
3368      * Return whether this activity is the root of a task.  The root is the
3369      * first activity in a task.
3370      *
3371      * @return True if this is the root activity, else false.
3372      */
isTaskRoot()3373     public boolean isTaskRoot() {
3374         try {
3375             return ActivityManagerNative.getDefault()
3376                 .getTaskForActivity(mToken, true) >= 0;
3377         } catch (RemoteException e) {
3378             return false;
3379         }
3380     }
3381 
3382     /**
3383      * Move the task containing this activity to the back of the activity
3384      * stack.  The activity's order within the task is unchanged.
3385      *
3386      * @param nonRoot If false then this only works if the activity is the root
3387      *                of a task; if true it will work for any activity in
3388      *                a task.
3389      *
3390      * @return If the task was moved (or it was already at the
3391      *         back) true is returned, else false.
3392      */
moveTaskToBack(boolean nonRoot)3393     public boolean moveTaskToBack(boolean nonRoot) {
3394         try {
3395             return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3396                     mToken, nonRoot);
3397         } catch (RemoteException e) {
3398             // Empty
3399         }
3400         return false;
3401     }
3402 
3403     /**
3404      * Returns class name for this activity with the package prefix removed.
3405      * This is the default name used to read and write settings.
3406      *
3407      * @return The local class name.
3408      */
getLocalClassName()3409     public String getLocalClassName() {
3410         final String pkg = getPackageName();
3411         final String cls = mComponent.getClassName();
3412         int packageLen = pkg.length();
3413         if (!cls.startsWith(pkg) || cls.length() <= packageLen
3414                 || cls.charAt(packageLen) != '.') {
3415             return cls;
3416         }
3417         return cls.substring(packageLen+1);
3418     }
3419 
3420     /**
3421      * Returns complete component name of this activity.
3422      *
3423      * @return Returns the complete component name for this activity
3424      */
getComponentName()3425     public ComponentName getComponentName()
3426     {
3427         return mComponent;
3428     }
3429 
3430     /**
3431      * Retrieve a {@link SharedPreferences} object for accessing preferences
3432      * that are private to this activity.  This simply calls the underlying
3433      * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3434      * class name as the preferences name.
3435      *
3436      * @param mode Operating mode.  Use {@link #MODE_PRIVATE} for the default
3437      *             operation, {@link #MODE_WORLD_READABLE} and
3438      *             {@link #MODE_WORLD_WRITEABLE} to control permissions.
3439      *
3440      * @return Returns the single SharedPreferences instance that can be used
3441      *         to retrieve and modify the preference values.
3442      */
getPreferences(int mode)3443     public SharedPreferences getPreferences(int mode) {
3444         return getSharedPreferences(getLocalClassName(), mode);
3445     }
3446 
ensureSearchManager()3447     private void ensureSearchManager() {
3448         if (mSearchManager != null) {
3449             return;
3450         }
3451 
3452         // uses super.getSystemService() since this.getSystemService() looks at the
3453         // mSearchManager field.
3454         mSearchManager = (SearchManager) super.getSystemService(Context.SEARCH_SERVICE);
3455         int ident = mIdent;
3456         if (ident == 0) {
3457             if (mParent != null) ident = mParent.mIdent;
3458             if (ident == 0) {
3459                 throw new IllegalArgumentException("no ident");
3460             }
3461         }
3462         mSearchManager.setIdent(ident, getComponentName());
3463     }
3464 
3465     @Override
getSystemService(String name)3466     public Object getSystemService(String name) {
3467         if (getBaseContext() == null) {
3468             throw new IllegalStateException(
3469                     "System services not available to Activities before onCreate()");
3470         }
3471 
3472         if (WINDOW_SERVICE.equals(name)) {
3473             return mWindowManager;
3474         } else if (SEARCH_SERVICE.equals(name)) {
3475             ensureSearchManager();
3476             return mSearchManager;
3477         }
3478         return super.getSystemService(name);
3479     }
3480 
3481     /**
3482      * Change the title associated with this activity.  If this is a
3483      * top-level activity, the title for its window will change.  If it
3484      * is an embedded activity, the parent can do whatever it wants
3485      * with it.
3486      */
setTitle(CharSequence title)3487     public void setTitle(CharSequence title) {
3488         mTitle = title;
3489         onTitleChanged(title, mTitleColor);
3490 
3491         if (mParent != null) {
3492             mParent.onChildTitleChanged(this, title);
3493         }
3494     }
3495 
3496     /**
3497      * Change the title associated with this activity.  If this is a
3498      * top-level activity, the title for its window will change.  If it
3499      * is an embedded activity, the parent can do whatever it wants
3500      * with it.
3501      */
setTitle(int titleId)3502     public void setTitle(int titleId) {
3503         setTitle(getText(titleId));
3504     }
3505 
setTitleColor(int textColor)3506     public void setTitleColor(int textColor) {
3507         mTitleColor = textColor;
3508         onTitleChanged(mTitle, textColor);
3509     }
3510 
getTitle()3511     public final CharSequence getTitle() {
3512         return mTitle;
3513     }
3514 
getTitleColor()3515     public final int getTitleColor() {
3516         return mTitleColor;
3517     }
3518 
onTitleChanged(CharSequence title, int color)3519     protected void onTitleChanged(CharSequence title, int color) {
3520         if (mTitleReady) {
3521             final Window win = getWindow();
3522             if (win != null) {
3523                 win.setTitle(title);
3524                 if (color != 0) {
3525                     win.setTitleColor(color);
3526                 }
3527             }
3528         }
3529     }
3530 
onChildTitleChanged(Activity childActivity, CharSequence title)3531     protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3532     }
3533 
3534     /**
3535      * Sets the visibility of the progress bar in the title.
3536      * <p>
3537      * In order for the progress bar to be shown, the feature must be requested
3538      * via {@link #requestWindowFeature(int)}.
3539      *
3540      * @param visible Whether to show the progress bars in the title.
3541      */
setProgressBarVisibility(boolean visible)3542     public final void setProgressBarVisibility(boolean visible) {
3543         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3544             Window.PROGRESS_VISIBILITY_OFF);
3545     }
3546 
3547     /**
3548      * Sets the visibility of the indeterminate progress bar in the title.
3549      * <p>
3550      * In order for the progress bar to be shown, the feature must be requested
3551      * via {@link #requestWindowFeature(int)}.
3552      *
3553      * @param visible Whether to show the progress bars in the title.
3554      */
setProgressBarIndeterminateVisibility(boolean visible)3555     public final void setProgressBarIndeterminateVisibility(boolean visible) {
3556         getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3557                 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3558     }
3559 
3560     /**
3561      * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3562      * is always indeterminate).
3563      * <p>
3564      * In order for the progress bar to be shown, the feature must be requested
3565      * via {@link #requestWindowFeature(int)}.
3566      *
3567      * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3568      */
setProgressBarIndeterminate(boolean indeterminate)3569     public final void setProgressBarIndeterminate(boolean indeterminate) {
3570         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3571                 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3572     }
3573 
3574     /**
3575      * Sets the progress for the progress bars in the title.
3576      * <p>
3577      * In order for the progress bar to be shown, the feature must be requested
3578      * via {@link #requestWindowFeature(int)}.
3579      *
3580      * @param progress The progress for the progress bar. Valid ranges are from
3581      *            0 to 10000 (both inclusive). If 10000 is given, the progress
3582      *            bar will be completely filled and will fade out.
3583      */
setProgress(int progress)3584     public final void setProgress(int progress) {
3585         getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3586     }
3587 
3588     /**
3589      * Sets the secondary progress for the progress bar in the title. This
3590      * progress is drawn between the primary progress (set via
3591      * {@link #setProgress(int)} and the background. It can be ideal for media
3592      * scenarios such as showing the buffering progress while the default
3593      * progress shows the play progress.
3594      * <p>
3595      * In order for the progress bar to be shown, the feature must be requested
3596      * via {@link #requestWindowFeature(int)}.
3597      *
3598      * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3599      *            0 to 10000 (both inclusive).
3600      */
setSecondaryProgress(int secondaryProgress)3601     public final void setSecondaryProgress(int secondaryProgress) {
3602         getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3603                 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3604     }
3605 
3606     /**
3607      * Suggests an audio stream whose volume should be changed by the hardware
3608      * volume controls.
3609      * <p>
3610      * The suggested audio stream will be tied to the window of this Activity.
3611      * If the Activity is switched, the stream set here is no longer the
3612      * suggested stream. The client does not need to save and restore the old
3613      * suggested stream value in onPause and onResume.
3614      *
3615      * @param streamType The type of the audio stream whose volume should be
3616      *        changed by the hardware volume controls. It is not guaranteed that
3617      *        the hardware volume controls will always change this stream's
3618      *        volume (for example, if a call is in progress, its stream's volume
3619      *        may be changed instead). To reset back to the default, use
3620      *        {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3621      */
setVolumeControlStream(int streamType)3622     public final void setVolumeControlStream(int streamType) {
3623         getWindow().setVolumeControlStream(streamType);
3624     }
3625 
3626     /**
3627      * Gets the suggested audio stream whose volume should be changed by the
3628      * harwdare volume controls.
3629      *
3630      * @return The suggested audio stream type whose volume should be changed by
3631      *         the hardware volume controls.
3632      * @see #setVolumeControlStream(int)
3633      */
getVolumeControlStream()3634     public final int getVolumeControlStream() {
3635         return getWindow().getVolumeControlStream();
3636     }
3637 
3638     /**
3639      * Runs the specified action on the UI thread. If the current thread is the UI
3640      * thread, then the action is executed immediately. If the current thread is
3641      * not the UI thread, the action is posted to the event queue of the UI thread.
3642      *
3643      * @param action the action to run on the UI thread
3644      */
runOnUiThread(Runnable action)3645     public final void runOnUiThread(Runnable action) {
3646         if (Thread.currentThread() != mUiThread) {
3647             mHandler.post(action);
3648         } else {
3649             action.run();
3650         }
3651     }
3652 
3653     /**
3654      * Stub implementation of {@link android.view.LayoutInflater.Factory#onCreateView} used when
3655      * inflating with the LayoutInflater returned by {@link #getSystemService}.  This
3656      * implementation simply returns null for all view names.
3657      *
3658      * @see android.view.LayoutInflater#createView
3659      * @see android.view.Window#getLayoutInflater
3660      */
onCreateView(String name, Context context, AttributeSet attrs)3661     public View onCreateView(String name, Context context, AttributeSet attrs) {
3662         return null;
3663     }
3664 
3665     // ------------------ Internal API ------------------
3666 
setParent(Activity parent)3667     final void setParent(Activity parent) {
3668         mParent = parent;
3669     }
3670 
attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, Object lastNonConfigurationInstance, Configuration config)3671     final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
3672             Application application, Intent intent, ActivityInfo info, CharSequence title,
3673             Activity parent, String id, Object lastNonConfigurationInstance,
3674             Configuration config) {
3675         attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
3676             lastNonConfigurationInstance, null, config);
3677     }
3678 
attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, int ident, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, Object lastNonConfigurationInstance, HashMap<String,Object> lastNonConfigurationChildInstances, Configuration config)3679     final void attach(Context context, ActivityThread aThread,
3680             Instrumentation instr, IBinder token, int ident,
3681             Application application, Intent intent, ActivityInfo info,
3682             CharSequence title, Activity parent, String id,
3683             Object lastNonConfigurationInstance,
3684             HashMap<String,Object> lastNonConfigurationChildInstances,
3685             Configuration config) {
3686         attachBaseContext(context);
3687 
3688         mWindow = PolicyManager.makeNewWindow(this);
3689         mWindow.setCallback(this);
3690         if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
3691             mWindow.setSoftInputMode(info.softInputMode);
3692         }
3693         mUiThread = Thread.currentThread();
3694 
3695         mMainThread = aThread;
3696         mInstrumentation = instr;
3697         mToken = token;
3698         mIdent = ident;
3699         mApplication = application;
3700         mIntent = intent;
3701         mComponent = intent.getComponent();
3702         mActivityInfo = info;
3703         mTitle = title;
3704         mParent = parent;
3705         mEmbeddedID = id;
3706         mLastNonConfigurationInstance = lastNonConfigurationInstance;
3707         mLastNonConfigurationChildInstances = lastNonConfigurationChildInstances;
3708 
3709         mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
3710         if (mParent != null) {
3711             mWindow.setContainer(mParent.getWindow());
3712         }
3713         mWindowManager = mWindow.getWindowManager();
3714         mCurrentConfig = config;
3715     }
3716 
getActivityToken()3717     final IBinder getActivityToken() {
3718         return mParent != null ? mParent.getActivityToken() : mToken;
3719     }
3720 
performStart()3721     final void performStart() {
3722         mCalled = false;
3723         mInstrumentation.callActivityOnStart(this);
3724         if (!mCalled) {
3725             throw new SuperNotCalledException(
3726                 "Activity " + mComponent.toShortString() +
3727                 " did not call through to super.onStart()");
3728         }
3729     }
3730 
performRestart()3731     final void performRestart() {
3732         final int N = mManagedCursors.size();
3733         for (int i=0; i<N; i++) {
3734             ManagedCursor mc = mManagedCursors.get(i);
3735             if (mc.mReleased || mc.mUpdated) {
3736                 mc.mCursor.requery();
3737                 mc.mReleased = false;
3738                 mc.mUpdated = false;
3739             }
3740         }
3741 
3742         if (mStopped) {
3743             mStopped = false;
3744             mCalled = false;
3745             mInstrumentation.callActivityOnRestart(this);
3746             if (!mCalled) {
3747                 throw new SuperNotCalledException(
3748                     "Activity " + mComponent.toShortString() +
3749                     " did not call through to super.onRestart()");
3750             }
3751             performStart();
3752         }
3753     }
3754 
performResume()3755     final void performResume() {
3756         performRestart();
3757 
3758         mLastNonConfigurationInstance = null;
3759 
3760         // First call onResume() -before- setting mResumed, so we don't
3761         // send out any status bar / menu notifications the client makes.
3762         mCalled = false;
3763         mInstrumentation.callActivityOnResume(this);
3764         if (!mCalled) {
3765             throw new SuperNotCalledException(
3766                 "Activity " + mComponent.toShortString() +
3767                 " did not call through to super.onResume()");
3768         }
3769 
3770         // Now really resume, and install the current status bar and menu.
3771         mResumed = true;
3772         mCalled = false;
3773         onPostResume();
3774         if (!mCalled) {
3775             throw new SuperNotCalledException(
3776                 "Activity " + mComponent.toShortString() +
3777                 " did not call through to super.onPostResume()");
3778         }
3779     }
3780 
performPause()3781     final void performPause() {
3782         onPause();
3783     }
3784 
performUserLeaving()3785     final void performUserLeaving() {
3786         onUserInteraction();
3787         onUserLeaveHint();
3788     }
3789 
performStop()3790     final void performStop() {
3791         if (!mStopped) {
3792             if (mWindow != null) {
3793                 mWindow.closeAllPanels();
3794             }
3795 
3796             mCalled = false;
3797             mInstrumentation.callActivityOnStop(this);
3798             if (!mCalled) {
3799                 throw new SuperNotCalledException(
3800                     "Activity " + mComponent.toShortString() +
3801                     " did not call through to super.onStop()");
3802             }
3803 
3804             final int N = mManagedCursors.size();
3805             for (int i=0; i<N; i++) {
3806                 ManagedCursor mc = mManagedCursors.get(i);
3807                 if (!mc.mReleased) {
3808                     mc.mCursor.deactivate();
3809                     mc.mReleased = true;
3810                 }
3811             }
3812 
3813             mStopped = true;
3814         }
3815         mResumed = false;
3816     }
3817 
isResumed()3818     final boolean isResumed() {
3819         return mResumed;
3820     }
3821 
dispatchActivityResult(String who, int requestCode, int resultCode, Intent data)3822     void dispatchActivityResult(String who, int requestCode,
3823         int resultCode, Intent data) {
3824         if (Config.LOGV) Log.v(
3825             TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
3826             + ", resCode=" + resultCode + ", data=" + data);
3827         if (who == null) {
3828             onActivityResult(requestCode, resultCode, data);
3829         }
3830     }
3831 }
3832