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