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