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