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