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