blob: a1cf233a9dfb9888416ee6157ac0b9f2ef6d62ea [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
Adam Powell33b97432010-04-20 10:01:14 -070019import java.util.ArrayList;
20import java.util.HashMap;
svetoslavganov75986cf2009-05-14 22:28:01 -070021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ComponentCallbacks;
23import android.content.ComponentName;
24import android.content.ContentResolver;
25import android.content.Context;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070026import android.content.IIntentSender;
Adam Powell33b97432010-04-20 10:01:14 -070027import android.content.Intent;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070028import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.SharedPreferences;
30import android.content.pm.ActivityInfo;
31import android.content.res.Configuration;
32import android.content.res.Resources;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070033import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.Cursor;
35import android.graphics.Bitmap;
36import android.graphics.Canvas;
37import android.graphics.drawable.Drawable;
38import android.media.AudioManager;
39import android.net.Uri;
Dianne Hackborn8d374262009-09-14 21:21:52 -070040import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Handler;
43import android.os.IBinder;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -070044import android.os.Parcelable;
svetoslavganov75986cf2009-05-14 22:28:01 -070045import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.text.Selection;
47import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070048import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.text.method.TextKeyListener;
50import android.util.AttributeSet;
51import android.util.Config;
52import android.util.EventLog;
53import android.util.Log;
54import android.util.SparseArray;
55import android.view.ContextMenu;
56import android.view.ContextThemeWrapper;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070057import android.view.InflateException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.KeyEvent;
59import android.view.LayoutInflater;
60import android.view.Menu;
61import android.view.MenuInflater;
62import android.view.MenuItem;
63import android.view.MotionEvent;
64import android.view.View;
65import android.view.ViewGroup;
66import android.view.ViewManager;
67import android.view.Window;
68import android.view.WindowManager;
69import android.view.ContextMenu.ContextMenuInfo;
70import android.view.View.OnCreateContextMenuListener;
svetoslavganov75986cf2009-05-14 22:28:01 -070071import android.view.ViewGroup.LayoutParams;
72import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.widget.AdapterView;
Adam Powell33b97432010-04-20 10:01:14 -070074import android.widget.LinearLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
Adam Powell89e06452010-06-23 20:24:52 -070076import com.android.internal.app.ActionBarImpl;
Adam Powell33b97432010-04-20 10:01:14 -070077import com.android.internal.policy.PolicyManager;
Adam Powell89e06452010-06-23 20:24:52 -070078import com.android.internal.widget.ActionBarView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80/**
81 * An activity is a single, focused thing that the user can do. Almost all
82 * activities interact with the user, so the Activity class takes care of
83 * creating a window for you in which you can place your UI with
84 * {@link #setContentView}. While activities are often presented to the user
85 * as full-screen windows, they can also be used in other ways: as floating
86 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
87 * or embedded inside of another activity (using {@link ActivityGroup}).
88 *
89 * There are two methods almost all subclasses of Activity will implement:
90 *
91 * <ul>
92 * <li> {@link #onCreate} is where you initialize your activity. Most
93 * importantly, here you will usually call {@link #setContentView(int)}
94 * with a layout resource defining your UI, and using {@link #findViewById}
95 * to retrieve the widgets in that UI that you need to interact with
96 * programmatically.
97 *
98 * <li> {@link #onPause} is where you deal with the user leaving your
99 * activity. Most importantly, any changes made by the user should at this
100 * point be committed (usually to the
101 * {@link android.content.ContentProvider} holding the data).
102 * </ul>
103 *
104 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
105 * activity classes must have a corresponding
106 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
107 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
108 *
109 * <p>The Activity class is an important part of an application's overall lifecycle,
110 * and the way activities are launched and put together is a fundamental
111 * part of the platform's application model. For a detailed perspective on the structure of
112 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
113 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
114 *
115 * <p>Topics covered here:
116 * <ol>
117 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
118 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
119 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
120 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
121 * <li><a href="#Permissions">Permissions</a>
122 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
123 * </ol>
124 *
125 * <a name="ActivityLifecycle"></a>
126 * <h3>Activity Lifecycle</h3>
127 *
128 * <p>Activities in the system are managed as an <em>activity stack</em>.
129 * When a new activity is started, it is placed on the top of the stack
130 * and becomes the running activity -- the previous activity always remains
131 * below it in the stack, and will not come to the foreground again until
132 * the new activity exits.</p>
133 *
134 * <p>An activity has essentially four states:</p>
135 * <ul>
136 * <li> If an activity in the foreground of the screen (at the top of
137 * the stack),
138 * it is <em>active</em> or <em>running</em>. </li>
139 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
140 * or transparent activity has focus on top of your activity), it
141 * is <em>paused</em>. A paused activity is completely alive (it
142 * maintains all state and member information and remains attached to
143 * the window manager), but can be killed by the system in extreme
144 * low memory situations.
145 * <li>If an activity is completely obscured by another activity,
146 * it is <em>stopped</em>. It still retains all state and member information,
147 * however, it is no longer visible to the user so its window is hidden
148 * and it will often be killed by the system when memory is needed
149 * elsewhere.</li>
150 * <li>If an activity is paused or stopped, the system can drop the activity
151 * from memory by either asking it to finish, or simply killing its
152 * process. When it is displayed again to the user, it must be
153 * completely restarted and restored to its previous state.</li>
154 * </ul>
155 *
156 * <p>The following diagram shows the important state paths of an Activity.
157 * The square rectangles represent callback methods you can implement to
158 * perform operations when the Activity moves between states. The colored
159 * ovals are major states the Activity can be in.</p>
160 *
161 * <p><img src="../../../images/activity_lifecycle.png"
162 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
163 *
164 * <p>There are three key loops you may be interested in monitoring within your
165 * activity:
166 *
167 * <ul>
168 * <li>The <b>entire lifetime</b> of an activity happens between the first call
169 * to {@link android.app.Activity#onCreate} through to a single final call
170 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
171 * of "global" state in onCreate(), and release all remaining resources in
172 * onDestroy(). For example, if it has a thread running in the background
173 * to download data from the network, it may create that thread in onCreate()
174 * and then stop the thread in onDestroy().
175 *
176 * <li>The <b>visible lifetime</b> of an activity happens between a call to
177 * {@link android.app.Activity#onStart} until a corresponding call to
178 * {@link android.app.Activity#onStop}. During this time the user can see the
179 * activity on-screen, though it may not be in the foreground and interacting
180 * with the user. Between these two methods you can maintain resources that
181 * are needed to show the activity to the user. For example, you can register
182 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
183 * that impact your UI, and unregister it in onStop() when the user an no
184 * longer see what you are displaying. The onStart() and onStop() methods
185 * can be called multiple times, as the activity becomes visible and hidden
186 * to the user.
187 *
188 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
189 * {@link android.app.Activity#onResume} until a corresponding call to
190 * {@link android.app.Activity#onPause}. During this time the activity is
191 * in front of all other activities and interacting with the user. An activity
192 * can frequently go between the resumed and paused states -- for example when
193 * the device goes to sleep, when an activity result is delivered, when a new
194 * intent is delivered -- so the code in these methods should be fairly
195 * lightweight.
196 * </ul>
197 *
198 * <p>The entire lifecycle of an activity is defined by the following
199 * Activity methods. All of these are hooks that you can override
200 * to do appropriate work when the activity changes state. All
201 * activities will implement {@link android.app.Activity#onCreate}
202 * to do their initial setup; many will also implement
203 * {@link android.app.Activity#onPause} to commit changes to data and
204 * otherwise prepare to stop interacting with the user. You should always
205 * call up to your superclass when implementing these methods.</p>
206 *
207 * </p>
208 * <pre class="prettyprint">
209 * public class Activity extends ApplicationContext {
210 * protected void onCreate(Bundle savedInstanceState);
211 *
212 * protected void onStart();
213 *
214 * protected void onRestart();
215 *
216 * protected void onResume();
217 *
218 * protected void onPause();
219 *
220 * protected void onStop();
221 *
222 * protected void onDestroy();
223 * }
224 * </pre>
225 *
226 * <p>In general the movement through an activity's lifecycle looks like
227 * this:</p>
228 *
229 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
230 * <colgroup align="left" span="3" />
231 * <colgroup align="left" />
232 * <colgroup align="center" />
233 * <colgroup align="center" />
234 *
235 * <thead>
236 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
237 * </thead>
238 *
239 * <tbody>
240 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
241 * <td>Called when the activity is first created.
242 * This is where you should do all of your normal static set up:
243 * create views, bind data to lists, etc. This method also
244 * provides you with a Bundle containing the activity's previously
245 * frozen state, if there was one.
246 * <p>Always followed by <code>onStart()</code>.</td>
247 * <td align="center">No</td>
248 * <td align="center"><code>onStart()</code></td>
249 * </tr>
250 *
251 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
252 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
253 * <td>Called after your activity has been stopped, prior to it being
254 * started again.
255 * <p>Always followed by <code>onStart()</code></td>
256 * <td align="center">No</td>
257 * <td align="center"><code>onStart()</code></td>
258 * </tr>
259 *
260 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
261 * <td>Called when the activity is becoming visible to the user.
262 * <p>Followed by <code>onResume()</code> if the activity comes
263 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
264 * <td align="center">No</td>
265 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
266 * </tr>
267 *
268 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
269 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
270 * <td>Called when the activity will start
271 * interacting with the user. At this point your activity is at
272 * the top of the activity stack, with user input going to it.
273 * <p>Always followed by <code>onPause()</code>.</td>
274 * <td align="center">No</td>
275 * <td align="center"><code>onPause()</code></td>
276 * </tr>
277 *
278 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
279 * <td>Called when the system is about to start resuming a previous
280 * activity. This is typically used to commit unsaved changes to
281 * persistent data, stop animations and other things that may be consuming
282 * CPU, etc. Implementations of this method must be very quick because
283 * the next activity will not be resumed until this method returns.
284 * <p>Followed by either <code>onResume()</code> if the activity
285 * returns back to the front, or <code>onStop()</code> if it becomes
286 * invisible to the user.</td>
287 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
288 * <td align="center"><code>onResume()</code> or<br>
289 * <code>onStop()</code></td>
290 * </tr>
291 *
292 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
293 * <td>Called when the activity is no longer visible to the user, because
294 * another activity has been resumed and is covering this one. This
295 * may happen either because a new activity is being started, an existing
296 * one is being brought in front of this one, or this one is being
297 * destroyed.
298 * <p>Followed by either <code>onRestart()</code> if
299 * this activity is coming back to interact with the user, or
300 * <code>onDestroy()</code> if this activity is going away.</td>
301 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
302 * <td align="center"><code>onRestart()</code> or<br>
303 * <code>onDestroy()</code></td>
304 * </tr>
305 *
306 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
307 * <td>The final call you receive before your
308 * activity is destroyed. This can happen either because the
309 * activity is finishing (someone called {@link Activity#finish} on
310 * it, or because the system is temporarily destroying this
311 * instance of the activity to save space. You can distinguish
312 * between these two scenarios with the {@link
313 * Activity#isFinishing} method.</td>
314 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
315 * <td align="center"><em>nothing</em></td>
316 * </tr>
317 * </tbody>
318 * </table>
319 *
320 * <p>Note the "Killable" column in the above table -- for those methods that
321 * are marked as being killable, after that method returns the process hosting the
322 * activity may killed by the system <em>at any time</em> without another line
323 * of its code being executed. Because of this, you should use the
324 * {@link #onPause} method to write any persistent data (such as user edits)
325 * to storage. In addition, the method
326 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
327 * in such a background state, allowing you to save away any dynamic instance
328 * state in your activity into the given Bundle, to be later received in
329 * {@link #onCreate} if the activity needs to be re-created.
330 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
331 * section for more information on how the lifecycle of a process is tied
332 * to the activities it is hosting. Note that it is important to save
333 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
334 * because the later is not part of the lifecycle callbacks, so will not
335 * be called in every situation as described in its documentation.</p>
336 *
337 * <p>For those methods that are not marked as being killable, the activity's
338 * process will not be killed by the system starting from the time the method
339 * is called and continuing after it returns. Thus an activity is in the killable
340 * state, for example, between after <code>onPause()</code> to the start of
341 * <code>onResume()</code>.</p>
342 *
343 * <a name="ConfigurationChanges"></a>
344 * <h3>Configuration Changes</h3>
345 *
346 * <p>If the configuration of the device (as defined by the
347 * {@link Configuration Resources.Configuration} class) changes,
348 * then anything displaying a user interface will need to update to match that
349 * configuration. Because Activity is the primary mechanism for interacting
350 * with the user, it includes special support for handling configuration
351 * changes.</p>
352 *
353 * <p>Unless you specify otherwise, a configuration change (such as a change
354 * in screen orientation, language, input devices, etc) will cause your
355 * current activity to be <em>destroyed</em>, going through the normal activity
356 * lifecycle process of {@link #onPause},
357 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
358 * had been in the foreground or visible to the user, once {@link #onDestroy} is
359 * called in that instance then a new instance of the activity will be
360 * created, with whatever savedInstanceState the previous instance had generated
361 * from {@link #onSaveInstanceState}.</p>
362 *
363 * <p>This is done because any application resource,
364 * including layout files, can change based on any configuration value. Thus
365 * the only safe way to handle a configuration change is to re-retrieve all
366 * resources, including layouts, drawables, and strings. Because activities
367 * must already know how to save their state and re-create themselves from
368 * that state, this is a convenient way to have an activity restart itself
369 * with a new configuration.</p>
370 *
371 * <p>In some special cases, you may want to bypass restarting of your
372 * activity based on one or more types of configuration changes. This is
373 * done with the {@link android.R.attr#configChanges android:configChanges}
374 * attribute in its manifest. For any types of configuration changes you say
375 * that you handle there, you will receive a call to your current activity's
376 * {@link #onConfigurationChanged} method instead of being restarted. If
377 * a configuration change involves any that you do not handle, however, the
378 * activity will still be restarted and {@link #onConfigurationChanged}
379 * will not be called.</p>
380 *
381 * <a name="StartingActivities"></a>
382 * <h3>Starting Activities and Getting Results</h3>
383 *
384 * <p>The {@link android.app.Activity#startActivity}
385 * method is used to start a
386 * new activity, which will be placed at the top of the activity stack. It
387 * takes a single argument, an {@link android.content.Intent Intent},
388 * which describes the activity
389 * to be executed.</p>
390 *
391 * <p>Sometimes you want to get a result back from an activity when it
392 * ends. For example, you may start an activity that lets the user pick
393 * a person in a list of contacts; when it ends, it returns the person
394 * that was selected. To do this, you call the
395 * {@link android.app.Activity#startActivityForResult(Intent, int)}
396 * version with a second integer parameter identifying the call. The result
397 * will come back through your {@link android.app.Activity#onActivityResult}
398 * method.</p>
399 *
400 * <p>When an activity exits, it can call
401 * {@link android.app.Activity#setResult(int)}
402 * to return data back to its parent. It must always supply a result code,
403 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
404 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
405 * return back an Intent containing any additional data it wants. All of this
406 * information appears back on the
407 * parent's <code>Activity.onActivityResult()</code>, along with the integer
408 * identifier it originally supplied.</p>
409 *
410 * <p>If a child activity fails for any reason (such as crashing), the parent
411 * activity will receive a result with the code RESULT_CANCELED.</p>
412 *
413 * <pre class="prettyprint">
414 * public class MyActivity extends Activity {
415 * ...
416 *
417 * static final int PICK_CONTACT_REQUEST = 0;
418 *
419 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
420 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
421 * // When the user center presses, let them pick a contact.
422 * startActivityForResult(
423 * new Intent(Intent.ACTION_PICK,
424 * new Uri("content://contacts")),
425 * PICK_CONTACT_REQUEST);
426 * return true;
427 * }
428 * return false;
429 * }
430 *
431 * protected void onActivityResult(int requestCode, int resultCode,
432 * Intent data) {
433 * if (requestCode == PICK_CONTACT_REQUEST) {
434 * if (resultCode == RESULT_OK) {
435 * // A contact was picked. Here we will just display it
436 * // to the user.
437 * startActivity(new Intent(Intent.ACTION_VIEW, data));
438 * }
439 * }
440 * }
441 * }
442 * </pre>
443 *
444 * <a name="SavingPersistentState"></a>
445 * <h3>Saving Persistent State</h3>
446 *
447 * <p>There are generally two kinds of persistent state than an activity
448 * will deal with: shared document-like data (typically stored in a SQLite
449 * database using a {@linkplain android.content.ContentProvider content provider})
450 * and internal state such as user preferences.</p>
451 *
452 * <p>For content provider data, we suggest that activities use a
453 * "edit in place" user model. That is, any edits a user makes are effectively
454 * made immediately without requiring an additional confirmation step.
455 * Supporting this model is generally a simple matter of following two rules:</p>
456 *
457 * <ul>
458 * <li> <p>When creating a new document, the backing database entry or file for
459 * it is created immediately. For example, if the user chooses to write
460 * a new e-mail, a new entry for that e-mail is created as soon as they
461 * start entering data, so that if they go to any other activity after
462 * that point this e-mail will now appear in the list of drafts.</p>
463 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
464 * commit to the backing content provider or file any changes the user
465 * has made. This ensures that those changes will be seen by any other
466 * activity that is about to run. You will probably want to commit
467 * your data even more aggressively at key times during your
468 * activity's lifecycle: for example before starting a new
469 * activity, before finishing your own activity, when the user
470 * switches between input fields, etc.</p>
471 * </ul>
472 *
473 * <p>This model is designed to prevent data loss when a user is navigating
474 * between activities, and allows the system to safely kill an activity (because
475 * system resources are needed somewhere else) at any time after it has been
476 * paused. Note this implies
477 * that the user pressing BACK from your activity does <em>not</em>
478 * mean "cancel" -- it means to leave the activity with its current contents
479 * saved away. Cancelling edits in an activity must be provided through
480 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
481 *
482 * <p>See the {@linkplain android.content.ContentProvider content package} for
483 * more information about content providers. These are a key aspect of how
484 * different activities invoke and propagate data between themselves.</p>
485 *
486 * <p>The Activity class also provides an API for managing internal persistent state
487 * associated with an activity. This can be used, for example, to remember
488 * the user's preferred initial display in a calendar (day view or week view)
489 * or the user's default home page in a web browser.</p>
490 *
491 * <p>Activity persistent state is managed
492 * with the method {@link #getPreferences},
493 * allowing you to retrieve and
494 * modify a set of name/value pairs associated with the activity. To use
495 * preferences that are shared across multiple application components
496 * (activities, receivers, services, providers), you can use the underlying
497 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
498 * to retrieve a preferences
499 * object stored under a specific name.
500 * (Note that it is not possible to share settings data across application
501 * packages -- for that you will need a content provider.)</p>
502 *
503 * <p>Here is an excerpt from a calendar activity that stores the user's
504 * preferred view mode in its persistent settings:</p>
505 *
506 * <pre class="prettyprint">
507 * public class CalendarActivity extends Activity {
508 * ...
509 *
510 * static final int DAY_VIEW_MODE = 0;
511 * static final int WEEK_VIEW_MODE = 1;
512 *
513 * private SharedPreferences mPrefs;
514 * private int mCurViewMode;
515 *
516 * protected void onCreate(Bundle savedInstanceState) {
517 * super.onCreate(savedInstanceState);
518 *
519 * SharedPreferences mPrefs = getSharedPreferences();
520 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
521 * }
522 *
523 * protected void onPause() {
524 * super.onPause();
525 *
526 * SharedPreferences.Editor ed = mPrefs.edit();
527 * ed.putInt("view_mode", mCurViewMode);
528 * ed.commit();
529 * }
530 * }
531 * </pre>
532 *
533 * <a name="Permissions"></a>
534 * <h3>Permissions</h3>
535 *
536 * <p>The ability to start a particular Activity can be enforced when it is
537 * declared in its
538 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
539 * tag. By doing so, other applications will need to declare a corresponding
540 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
541 * element in their own manifest to be able to start that activity.
542 *
543 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
544 * document for more information on permissions and security in general.
545 *
546 * <a name="ProcessLifecycle"></a>
547 * <h3>Process Lifecycle</h3>
548 *
549 * <p>The Android system attempts to keep application process around for as
550 * long as possible, but eventually will need to remove old processes when
551 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
552 * Lifecycle</a>, the decision about which process to remove is intimately
553 * tied to the state of the user's interaction with it. In general, there
554 * are four states a process can be in based on the activities running in it,
555 * listed here in order of importance. The system will kill less important
556 * processes (the last ones) before it resorts to killing more important
557 * processes (the first ones).
558 *
559 * <ol>
560 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
561 * that the user is currently interacting with) is considered the most important.
562 * Its process will only be killed as a last resort, if it uses more memory
563 * than is available on the device. Generally at this point the device has
564 * reached a memory paging state, so this is required in order to keep the user
565 * interface responsive.
566 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
567 * but not in the foreground, such as one sitting behind a foreground dialog)
568 * is considered extremely important and will not be killed unless that is
569 * required to keep the foreground activity running.
570 * <li> <p>A <b>background activity</b> (an activity that is not visible to
571 * the user and has been paused) is no longer critical, so the system may
572 * safely kill its process to reclaim memory for other foreground or
573 * visible processes. If its process needs to be killed, when the user navigates
574 * back to the activity (making it visible on the screen again), its
575 * {@link #onCreate} method will be called with the savedInstanceState it had previously
576 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
577 * state as the user last left it.
578 * <li> <p>An <b>empty process</b> is one hosting no activities or other
579 * application components (such as {@link Service} or
580 * {@link android.content.BroadcastReceiver} classes). These are killed very
581 * quickly by the system as memory becomes low. For this reason, any
582 * background operation you do outside of an activity must be executed in the
583 * context of an activity BroadcastReceiver or Service to ensure that the system
584 * knows it needs to keep your process around.
585 * </ol>
586 *
587 * <p>Sometimes an Activity may need to do a long-running operation that exists
588 * independently of the activity lifecycle itself. An example may be a camera
589 * application that allows you to upload a picture to a web site. The upload
590 * may take a long time, and the application should allow the user to leave
591 * the application will it is executing. To accomplish this, your Activity
592 * should start a {@link Service} in which the upload takes place. This allows
593 * the system to properly prioritize your process (considering it to be more
594 * important than other non-visible applications) for the duration of the
595 * upload, independent of whether the original activity is paused, stopped,
596 * or finished.
597 */
598public class Activity extends ContextThemeWrapper
599 implements LayoutInflater.Factory,
600 Window.Callback, KeyEvent.Callback,
601 OnCreateContextMenuListener, ComponentCallbacks {
602 private static final String TAG = "Activity";
603
604 /** Standard activity result: operation canceled. */
605 public static final int RESULT_CANCELED = 0;
606 /** Standard activity result: operation succeeded. */
607 public static final int RESULT_OK = -1;
608 /** Start of user-defined activity results. */
609 public static final int RESULT_FIRST_USER = 1;
610
611 private static long sInstanceCount = 0;
612
613 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700614 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
616 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
617 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800618 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800620 private static class ManagedDialog {
621 Dialog mDialog;
622 Bundle mArgs;
623 }
624 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625
626 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
627 private Instrumentation mInstrumentation;
628 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700629 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 /*package*/ String mEmbeddedID;
631 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700632 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 private ComponentName mComponent;
634 /*package*/ ActivityInfo mActivityInfo;
635 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 Activity mParent;
637 boolean mCalled;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700638 boolean mStarted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 private boolean mResumed;
640 private boolean mStopped;
641 boolean mFinished;
642 boolean mStartedActivity;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500643 /** true if the activity is being destroyed in order to recreate it with a new configuration */
644 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 /*package*/ int mConfigChangeFlags;
646 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100647 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700649 static final class NonConfigurationInstances {
650 Object activity;
651 HashMap<String, Object> children;
652 ArrayList<Fragment> fragments;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700653 SparseArray<LoaderManager> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700654 }
655 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 private Window mWindow;
658
659 private WindowManager mWindowManager;
660 /*package*/ View mDecor = null;
661 /*package*/ boolean mWindowAdded = false;
662 /*package*/ boolean mVisibleFromServer = false;
663 /*package*/ boolean mVisibleFromClient = true;
Adam Powell33b97432010-04-20 10:01:14 -0700664 /*package*/ ActionBar mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
666 private CharSequence mTitle;
667 private int mTitleColor = 0;
668
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700669 final FragmentManager mFragments = new FragmentManager();
670
Dianne Hackbornc8017682010-07-06 13:34:38 -0700671 SparseArray<LoaderManager> mAllLoaderManagers;
672 LoaderManager mLoaderManager;
673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 private static final class ManagedCursor {
675 ManagedCursor(Cursor cursor) {
676 mCursor = cursor;
677 mReleased = false;
678 mUpdated = false;
679 }
680
681 private final Cursor mCursor;
682 private boolean mReleased;
683 private boolean mUpdated;
684 }
685 private final ArrayList<ManagedCursor> mManagedCursors =
686 new ArrayList<ManagedCursor>();
687
688 // protected by synchronized (this)
689 int mResultCode = RESULT_CANCELED;
690 Intent mResultData = null;
691
692 private boolean mTitleReady = false;
693
694 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
695 private SpannableStringBuilder mDefaultKeySsb = null;
696
697 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
698
699 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700700 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
Carl Shapiro82fe5642010-02-24 00:14:23 -0800702 // Used for debug only
703 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 public Activity() {
705 ++sInstanceCount;
706 }
707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 @Override
709 protected void finalize() throws Throwable {
710 super.finalize();
711 --sInstanceCount;
712 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800713 */
714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 public static long getInstanceCount() {
716 return sInstanceCount;
717 }
718
719 /** Return the intent that started this activity. */
720 public Intent getIntent() {
721 return mIntent;
722 }
723
724 /**
725 * Change the intent returned by {@link #getIntent}. This holds a
726 * reference to the given intent; it does not copy it. Often used in
727 * conjunction with {@link #onNewIntent}.
728 *
729 * @param newIntent The new Intent object to return from getIntent
730 *
731 * @see #getIntent
732 * @see #onNewIntent
733 */
734 public void setIntent(Intent newIntent) {
735 mIntent = newIntent;
736 }
737
738 /** Return the application that owns this activity. */
739 public final Application getApplication() {
740 return mApplication;
741 }
742
743 /** Is this activity embedded inside of another activity? */
744 public final boolean isChild() {
745 return mParent != null;
746 }
747
748 /** Return the parent activity if this view is an embedded child. */
749 public final Activity getParent() {
750 return mParent;
751 }
752
753 /** Retrieve the window manager for showing custom windows. */
754 public WindowManager getWindowManager() {
755 return mWindowManager;
756 }
757
758 /**
759 * Retrieve the current {@link android.view.Window} for the activity.
760 * This can be used to directly access parts of the Window API that
761 * are not available through Activity/Screen.
762 *
763 * @return Window The current window, or null if the activity is not
764 * visual.
765 */
766 public Window getWindow() {
767 return mWindow;
768 }
769
770 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700771 * Return the LoaderManager for this fragment, creating it if needed.
772 */
773 public LoaderManager getLoaderManager() {
774 if (mLoaderManager != null) {
775 return mLoaderManager;
776 }
777 mLoaderManager = getLoaderManager(-1, false);
778 return mLoaderManager;
779 }
780
781 LoaderManager getLoaderManager(int index, boolean started) {
782 if (mAllLoaderManagers == null) {
783 mAllLoaderManagers = new SparseArray<LoaderManager>();
784 }
785 LoaderManager lm = mAllLoaderManagers.get(index);
786 if (lm == null) {
787 lm = new LoaderManager(started);
788 mAllLoaderManagers.put(index, lm);
789 }
790 return lm;
791 }
792
793 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 * Calls {@link android.view.Window#getCurrentFocus} on the
795 * Window of this Activity to return the currently focused view.
796 *
797 * @return View The current View with focus or null.
798 *
799 * @see #getWindow
800 * @see android.view.Window#getCurrentFocus
801 */
802 public View getCurrentFocus() {
803 return mWindow != null ? mWindow.getCurrentFocus() : null;
804 }
805
806 @Override
807 public int getWallpaperDesiredMinimumWidth() {
808 int width = super.getWallpaperDesiredMinimumWidth();
809 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
810 }
811
812 @Override
813 public int getWallpaperDesiredMinimumHeight() {
814 int height = super.getWallpaperDesiredMinimumHeight();
815 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
816 }
817
818 /**
819 * Called when the activity is starting. This is where most initialization
820 * should go: calling {@link #setContentView(int)} to inflate the
821 * activity's UI, using {@link #findViewById} to programmatically interact
822 * with widgets in the UI, calling
823 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
824 * cursors for data being displayed, etc.
825 *
826 * <p>You can call {@link #finish} from within this function, in
827 * which case onDestroy() will be immediately called without any of the rest
828 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
829 * {@link #onPause}, etc) executing.
830 *
831 * <p><em>Derived classes must call through to the super class's
832 * implementation of this method. If they do not, an exception will be
833 * thrown.</em></p>
834 *
835 * @param savedInstanceState If the activity is being re-initialized after
836 * previously being shut down then this Bundle contains the data it most
837 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
838 *
839 * @see #onStart
840 * @see #onSaveInstanceState
841 * @see #onRestoreInstanceState
842 * @see #onPostCreate
843 */
844 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700845 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
846 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700847 if (mLastNonConfigurationInstances != null) {
848 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
849 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700850 if (savedInstanceState != null) {
851 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
852 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
853 ? mLastNonConfigurationInstances.fragments : null);
854 }
855 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 mCalled = true;
857 }
858
859 /**
860 * The hook for {@link ActivityThread} to restore the state of this activity.
861 *
862 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
863 * {@link #restoreManagedDialogs(android.os.Bundle)}.
864 *
865 * @param savedInstanceState contains the saved state
866 */
867 final void performRestoreInstanceState(Bundle savedInstanceState) {
868 onRestoreInstanceState(savedInstanceState);
869 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
872 /**
873 * This method is called after {@link #onStart} when the activity is
874 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800875 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 * to restore their state, but it is sometimes convenient to do it here
877 * after all of the initialization has been done or to allow subclasses to
878 * decide whether to use your default implementation. The default
879 * implementation of this method performs a restore of any view state that
880 * had previously been frozen by {@link #onSaveInstanceState}.
881 *
882 * <p>This method is called between {@link #onStart} and
883 * {@link #onPostCreate}.
884 *
885 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
886 *
887 * @see #onCreate
888 * @see #onPostCreate
889 * @see #onResume
890 * @see #onSaveInstanceState
891 */
892 protected void onRestoreInstanceState(Bundle savedInstanceState) {
893 if (mWindow != null) {
894 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
895 if (windowState != null) {
896 mWindow.restoreHierarchyState(windowState);
897 }
898 }
899 }
900
901 /**
902 * Restore the state of any saved managed dialogs.
903 *
904 * @param savedInstanceState The bundle to restore from.
905 */
906 private void restoreManagedDialogs(Bundle savedInstanceState) {
907 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
908 if (b == null) {
909 return;
910 }
911
912 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
913 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800914 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 for (int i = 0; i < numDialogs; i++) {
916 final Integer dialogId = ids[i];
917 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
918 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700919 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
920 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800921 final ManagedDialog md = new ManagedDialog();
922 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
923 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
924 if (md.mDialog != null) {
925 mManagedDialogs.put(dialogId, md);
926 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
927 md.mDialog.onRestoreInstanceState(dialogState);
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930 }
931 }
932
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800933 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
934 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700935 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800936 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700937 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700938 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700939 return dialog;
940 }
941
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800942 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 return SAVED_DIALOG_KEY_PREFIX + key;
944 }
945
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800946 private static String savedDialogArgsKeyFor(int key) {
947 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949
950 /**
951 * Called when activity start-up is complete (after {@link #onStart}
952 * and {@link #onRestoreInstanceState} have been called). Applications will
953 * generally not implement this method; it is intended for system
954 * classes to do final initialization after application code has run.
955 *
956 * <p><em>Derived classes must call through to the super class's
957 * implementation of this method. If they do not, an exception will be
958 * thrown.</em></p>
959 *
960 * @param savedInstanceState If the activity is being re-initialized after
961 * previously being shut down then this Bundle contains the data it most
962 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
963 * @see #onCreate
964 */
965 protected void onPostCreate(Bundle savedInstanceState) {
966 if (!isChild()) {
967 mTitleReady = true;
968 onTitleChanged(getTitle(), getTitleColor());
969 }
Adam Powell96675b12010-06-10 18:58:59 -0700970 if (mWindow != null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
971 // Invalidate the action bar menu so that it can initialize properly.
972 mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 mCalled = true;
975 }
976
977 /**
978 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
979 * the activity had been stopped, but is now again being displayed to the
980 * user. It will be followed by {@link #onResume}.
981 *
982 * <p><em>Derived classes must call through to the super class's
983 * implementation of this method. If they do not, an exception will be
984 * thrown.</em></p>
985 *
986 * @see #onCreate
987 * @see #onStop
988 * @see #onResume
989 */
990 protected void onStart() {
991 mCalled = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700992 mStarted = true;
993 if (mLoaderManager != null) {
994 mLoaderManager.doStart();
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
997
998 /**
999 * Called after {@link #onStop} when the current activity is being
1000 * re-displayed to the user (the user has navigated back to it). It will
1001 * be followed by {@link #onStart} and then {@link #onResume}.
1002 *
1003 * <p>For activities that are using raw {@link Cursor} objects (instead of
1004 * creating them through
1005 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1006 * this is usually the place
1007 * where the cursor should be requeried (because you had deactivated it in
1008 * {@link #onStop}.
1009 *
1010 * <p><em>Derived classes must call through to the super class's
1011 * implementation of this method. If they do not, an exception will be
1012 * thrown.</em></p>
1013 *
1014 * @see #onStop
1015 * @see #onStart
1016 * @see #onResume
1017 */
1018 protected void onRestart() {
1019 mCalled = true;
1020 }
1021
1022 /**
1023 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1024 * {@link #onPause}, for your activity to start interacting with the user.
1025 * This is a good place to begin animations, open exclusive-access devices
1026 * (such as the camera), etc.
1027 *
1028 * <p>Keep in mind that onResume is not the best indicator that your activity
1029 * is visible to the user; a system window such as the keyguard may be in
1030 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1031 * activity is visible to the user (for example, to resume a game).
1032 *
1033 * <p><em>Derived classes must call through to the super class's
1034 * implementation of this method. If they do not, an exception will be
1035 * thrown.</em></p>
1036 *
1037 * @see #onRestoreInstanceState
1038 * @see #onRestart
1039 * @see #onPostResume
1040 * @see #onPause
1041 */
1042 protected void onResume() {
1043 mCalled = true;
1044 }
1045
1046 /**
1047 * Called when activity resume is complete (after {@link #onResume} has
1048 * been called). Applications will generally not implement this method;
1049 * it is intended for system classes to do final setup after application
1050 * resume code has run.
1051 *
1052 * <p><em>Derived classes must call through to the super class's
1053 * implementation of this method. If they do not, an exception will be
1054 * thrown.</em></p>
1055 *
1056 * @see #onResume
1057 */
1058 protected void onPostResume() {
1059 final Window win = getWindow();
1060 if (win != null) win.makeActive();
1061 mCalled = true;
1062 }
1063
1064 /**
1065 * This is called for activities that set launchMode to "singleTop" in
1066 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1067 * flag when calling {@link #startActivity}. In either case, when the
1068 * activity is re-launched while at the top of the activity stack instead
1069 * of a new instance of the activity being started, onNewIntent() will be
1070 * called on the existing instance with the Intent that was used to
1071 * re-launch it.
1072 *
1073 * <p>An activity will always be paused before receiving a new intent, so
1074 * you can count on {@link #onResume} being called after this method.
1075 *
1076 * <p>Note that {@link #getIntent} still returns the original Intent. You
1077 * can use {@link #setIntent} to update it to this new Intent.
1078 *
1079 * @param intent The new intent that was started for the activity.
1080 *
1081 * @see #getIntent
1082 * @see #setIntent
1083 * @see #onResume
1084 */
1085 protected void onNewIntent(Intent intent) {
1086 }
1087
1088 /**
1089 * The hook for {@link ActivityThread} to save the state of this activity.
1090 *
1091 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1092 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1093 *
1094 * @param outState The bundle to save the state to.
1095 */
1096 final void performSaveInstanceState(Bundle outState) {
1097 onSaveInstanceState(outState);
1098 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100
1101 /**
1102 * Called to retrieve per-instance state from an activity before being killed
1103 * so that the state can be restored in {@link #onCreate} or
1104 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1105 * will be passed to both).
1106 *
1107 * <p>This method is called before an activity may be killed so that when it
1108 * comes back some time in the future it can restore its state. For example,
1109 * if activity B is launched in front of activity A, and at some point activity
1110 * A is killed to reclaim resources, activity A will have a chance to save the
1111 * current state of its user interface via this method so that when the user
1112 * returns to activity A, the state of the user interface can be restored
1113 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1114 *
1115 * <p>Do not confuse this method with activity lifecycle callbacks such as
1116 * {@link #onPause}, which is always called when an activity is being placed
1117 * in the background or on its way to destruction, or {@link #onStop} which
1118 * is called before destruction. One example of when {@link #onPause} and
1119 * {@link #onStop} is called and not this method is when a user navigates back
1120 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1121 * on B because that particular instance will never be restored, so the
1122 * system avoids calling it. An example when {@link #onPause} is called and
1123 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1124 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1125 * killed during the lifetime of B since the state of the user interface of
1126 * A will stay intact.
1127 *
1128 * <p>The default implementation takes care of most of the UI per-instance
1129 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1130 * view in the hierarchy that has an id, and by saving the id of the currently
1131 * focused view (all of which is restored by the default implementation of
1132 * {@link #onRestoreInstanceState}). If you override this method to save additional
1133 * information not captured by each individual view, you will likely want to
1134 * call through to the default implementation, otherwise be prepared to save
1135 * all of the state of each view yourself.
1136 *
1137 * <p>If called, this method will occur before {@link #onStop}. There are
1138 * no guarantees about whether it will occur before or after {@link #onPause}.
1139 *
1140 * @param outState Bundle in which to place your saved state.
1141 *
1142 * @see #onCreate
1143 * @see #onRestoreInstanceState
1144 * @see #onPause
1145 */
1146 protected void onSaveInstanceState(Bundle outState) {
1147 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001148 Parcelable p = mFragments.saveAllState();
1149 if (p != null) {
1150 outState.putParcelable(FRAGMENTS_TAG, p);
1151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153
1154 /**
1155 * Save the state of any managed dialogs.
1156 *
1157 * @param outState place to store the saved state.
1158 */
1159 private void saveManagedDialogs(Bundle outState) {
1160 if (mManagedDialogs == null) {
1161 return;
1162 }
1163
1164 final int numDialogs = mManagedDialogs.size();
1165 if (numDialogs == 0) {
1166 return;
1167 }
1168
1169 Bundle dialogState = new Bundle();
1170
1171 int[] ids = new int[mManagedDialogs.size()];
1172
1173 // save each dialog's bundle, gather the ids
1174 for (int i = 0; i < numDialogs; i++) {
1175 final int key = mManagedDialogs.keyAt(i);
1176 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001177 final ManagedDialog md = mManagedDialogs.valueAt(i);
1178 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1179 if (md.mArgs != null) {
1180 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183
1184 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1185 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1186 }
1187
1188
1189 /**
1190 * Called as part of the activity lifecycle when an activity is going into
1191 * the background, but has not (yet) been killed. The counterpart to
1192 * {@link #onResume}.
1193 *
1194 * <p>When activity B is launched in front of activity A, this callback will
1195 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1196 * so be sure to not do anything lengthy here.
1197 *
1198 * <p>This callback is mostly used for saving any persistent state the
1199 * activity is editing, to present a "edit in place" model to the user and
1200 * making sure nothing is lost if there are not enough resources to start
1201 * the new activity without first killing this one. This is also a good
1202 * place to do things like stop animations and other things that consume a
1203 * noticeable mount of CPU in order to make the switch to the next activity
1204 * as fast as possible, or to close resources that are exclusive access
1205 * such as the camera.
1206 *
1207 * <p>In situations where the system needs more memory it may kill paused
1208 * processes to reclaim resources. Because of this, you should be sure
1209 * that all of your state is saved by the time you return from
1210 * this function. In general {@link #onSaveInstanceState} is used to save
1211 * per-instance state in the activity and this method is used to store
1212 * global persistent data (in content providers, files, etc.)
1213 *
1214 * <p>After receiving this call you will usually receive a following call
1215 * to {@link #onStop} (after the next activity has been resumed and
1216 * displayed), however in some cases there will be a direct call back to
1217 * {@link #onResume} without going through the stopped state.
1218 *
1219 * <p><em>Derived classes must call through to the super class's
1220 * implementation of this method. If they do not, an exception will be
1221 * thrown.</em></p>
1222 *
1223 * @see #onResume
1224 * @see #onSaveInstanceState
1225 * @see #onStop
1226 */
1227 protected void onPause() {
1228 mCalled = true;
1229 }
1230
1231 /**
1232 * Called as part of the activity lifecycle when an activity is about to go
1233 * into the background as the result of user choice. For example, when the
1234 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1235 * when an incoming phone call causes the in-call Activity to be automatically
1236 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1237 * the activity being interrupted. In cases when it is invoked, this method
1238 * is called right before the activity's {@link #onPause} callback.
1239 *
1240 * <p>This callback and {@link #onUserInteraction} are intended to help
1241 * activities manage status bar notifications intelligently; specifically,
1242 * for helping activities determine the proper time to cancel a notfication.
1243 *
1244 * @see #onUserInteraction()
1245 */
1246 protected void onUserLeaveHint() {
1247 }
1248
1249 /**
1250 * Generate a new thumbnail for this activity. This method is called before
1251 * pausing the activity, and should draw into <var>outBitmap</var> the
1252 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1253 * can use the given <var>canvas</var>, which is configured to draw into the
1254 * bitmap, for rendering if desired.
1255 *
1256 * <p>The default implementation renders the Screen's current view
1257 * hierarchy into the canvas to generate a thumbnail.
1258 *
1259 * <p>If you return false, the bitmap will be filled with a default
1260 * thumbnail.
1261 *
1262 * @param outBitmap The bitmap to contain the thumbnail.
1263 * @param canvas Can be used to render into the bitmap.
1264 *
1265 * @return Return true if you have drawn into the bitmap; otherwise after
1266 * you return it will be filled with a default thumbnail.
1267 *
1268 * @see #onCreateDescription
1269 * @see #onSaveInstanceState
1270 * @see #onPause
1271 */
1272 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1273 final View view = mDecor;
1274 if (view == null) {
1275 return false;
1276 }
1277
1278 final int vw = view.getWidth();
1279 final int vh = view.getHeight();
1280 final int dw = outBitmap.getWidth();
1281 final int dh = outBitmap.getHeight();
1282
1283 canvas.save();
1284 canvas.scale(((float)dw)/vw, ((float)dh)/vh);
1285 view.draw(canvas);
1286 canvas.restore();
1287
1288 return true;
1289 }
1290
1291 /**
1292 * Generate a new description for this activity. This method is called
1293 * before pausing the activity and can, if desired, return some textual
1294 * description of its current state to be displayed to the user.
1295 *
1296 * <p>The default implementation returns null, which will cause you to
1297 * inherit the description from the previous activity. If all activities
1298 * return null, generally the label of the top activity will be used as the
1299 * description.
1300 *
1301 * @return A description of what the user is doing. It should be short and
1302 * sweet (only a few words).
1303 *
1304 * @see #onCreateThumbnail
1305 * @see #onSaveInstanceState
1306 * @see #onPause
1307 */
1308 public CharSequence onCreateDescription() {
1309 return null;
1310 }
1311
1312 /**
1313 * Called when you are no longer visible to the user. You will next
1314 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1315 * depending on later user activity.
1316 *
1317 * <p>Note that this method may never be called, in low memory situations
1318 * where the system does not have enough memory to keep your activity's
1319 * process running after its {@link #onPause} method is called.
1320 *
1321 * <p><em>Derived classes must call through to the super class's
1322 * implementation of this method. If they do not, an exception will be
1323 * thrown.</em></p>
1324 *
1325 * @see #onRestart
1326 * @see #onResume
1327 * @see #onSaveInstanceState
1328 * @see #onDestroy
1329 */
1330 protected void onStop() {
1331 mCalled = true;
1332 }
1333
1334 /**
1335 * Perform any final cleanup before an activity is destroyed. This can
1336 * happen either because the activity is finishing (someone called
1337 * {@link #finish} on it, or because the system is temporarily destroying
1338 * this instance of the activity to save space. You can distinguish
1339 * between these two scenarios with the {@link #isFinishing} method.
1340 *
1341 * <p><em>Note: do not count on this method being called as a place for
1342 * saving data! For example, if an activity is editing data in a content
1343 * provider, those edits should be committed in either {@link #onPause} or
1344 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1345 * free resources like threads that are associated with an activity, so
1346 * that a destroyed activity does not leave such things around while the
1347 * rest of its application is still running. There are situations where
1348 * the system will simply kill the activity's hosting process without
1349 * calling this method (or any others) in it, so it should not be used to
1350 * do things that are intended to remain around after the process goes
1351 * away.
1352 *
1353 * <p><em>Derived classes must call through to the super class's
1354 * implementation of this method. If they do not, an exception will be
1355 * thrown.</em></p>
1356 *
1357 * @see #onPause
1358 * @see #onStop
1359 * @see #finish
1360 * @see #isFinishing
1361 */
1362 protected void onDestroy() {
1363 mCalled = true;
1364
1365 // dismiss any dialogs we are managing.
1366 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 final int numDialogs = mManagedDialogs.size();
1368 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001369 final ManagedDialog md = mManagedDialogs.valueAt(i);
1370 if (md.mDialog.isShowing()) {
1371 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001374 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
1377 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001378 synchronized (mManagedCursors) {
1379 int numCursors = mManagedCursors.size();
1380 for (int i = 0; i < numCursors; i++) {
1381 ManagedCursor c = mManagedCursors.get(i);
1382 if (c != null) {
1383 c.mCursor.close();
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001386 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Amith Yamasani49860442010-03-17 20:54:10 -07001388
1389 // Close any open search dialog
1390 if (mSearchManager != null) {
1391 mSearchManager.stopSearch();
1392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394
1395 /**
1396 * Called by the system when the device configuration changes while your
1397 * activity is running. Note that this will <em>only</em> be called if
1398 * you have selected configurations you would like to handle with the
1399 * {@link android.R.attr#configChanges} attribute in your manifest. If
1400 * any configuration change occurs that is not selected to be reported
1401 * by that attribute, then instead of reporting it the system will stop
1402 * and restart the activity (to have it launched with the new
1403 * configuration).
1404 *
1405 * <p>At the time that this function has been called, your Resources
1406 * object will have been updated to return resource values matching the
1407 * new configuration.
1408 *
1409 * @param newConfig The new device configuration.
1410 */
1411 public void onConfigurationChanged(Configuration newConfig) {
1412 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 if (mWindow != null) {
1415 // Pass the configuration changed event to the window
1416 mWindow.onConfigurationChanged(newConfig);
1417 }
1418 }
1419
1420 /**
1421 * If this activity is being destroyed because it can not handle a
1422 * configuration parameter being changed (and thus its
1423 * {@link #onConfigurationChanged(Configuration)} method is
1424 * <em>not</em> being called), then you can use this method to discover
1425 * the set of changes that have occurred while in the process of being
1426 * destroyed. Note that there is no guarantee that these will be
1427 * accurate (other changes could have happened at any time), so you should
1428 * only use this as an optimization hint.
1429 *
1430 * @return Returns a bit field of the configuration parameters that are
1431 * changing, as defined by the {@link android.content.res.Configuration}
1432 * class.
1433 */
1434 public int getChangingConfigurations() {
1435 return mConfigChangeFlags;
1436 }
1437
1438 /**
1439 * Retrieve the non-configuration instance data that was previously
1440 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1441 * be available from the initial {@link #onCreate} and
1442 * {@link #onStart} calls to the new instance, allowing you to extract
1443 * any useful dynamic state from the previous instance.
1444 *
1445 * <p>Note that the data you retrieve here should <em>only</em> be used
1446 * as an optimization for handling configuration changes. You should always
1447 * be able to handle getting a null pointer back, and an activity must
1448 * still be able to restore itself to its previous state (through the
1449 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1450 * function returns null.
1451 *
1452 * @return Returns the object previously returned by
1453 * {@link #onRetainNonConfigurationInstance()}.
1454 */
1455 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001456 return mLastNonConfigurationInstances != null
1457 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459
1460 /**
1461 * Called by the system, as part of destroying an
1462 * activity due to a configuration change, when it is known that a new
1463 * instance will immediately be created for the new configuration. You
1464 * can return any object you like here, including the activity instance
1465 * itself, which can later be retrieved by calling
1466 * {@link #getLastNonConfigurationInstance()} in the new activity
1467 * instance.
1468 *
1469 * <p>This function is called purely as an optimization, and you must
1470 * not rely on it being called. When it is called, a number of guarantees
1471 * will be made to help optimize configuration switching:
1472 * <ul>
1473 * <li> The function will be called between {@link #onStop} and
1474 * {@link #onDestroy}.
1475 * <li> A new instance of the activity will <em>always</em> be immediately
1476 * created after this one's {@link #onDestroy()} is called.
1477 * <li> The object you return here will <em>always</em> be available from
1478 * the {@link #getLastNonConfigurationInstance()} method of the following
1479 * activity instance as described there.
1480 * </ul>
1481 *
1482 * <p>These guarantees are designed so that an activity can use this API
1483 * to propagate extensive state from the old to new activity instance, from
1484 * loaded bitmaps, to network connections, to evenly actively running
1485 * threads. Note that you should <em>not</em> propagate any data that
1486 * may change based on the configuration, including any data loaded from
1487 * resources such as strings, layouts, or drawables.
1488 *
1489 * @return Return any Object holding the desired state to propagate to the
1490 * next activity instance.
1491 */
1492 public Object onRetainNonConfigurationInstance() {
1493 return null;
1494 }
1495
1496 /**
1497 * Retrieve the non-configuration instance data that was previously
1498 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1499 * be available from the initial {@link #onCreate} and
1500 * {@link #onStart} calls to the new instance, allowing you to extract
1501 * any useful dynamic state from the previous instance.
1502 *
1503 * <p>Note that the data you retrieve here should <em>only</em> be used
1504 * as an optimization for handling configuration changes. You should always
1505 * be able to handle getting a null pointer back, and an activity must
1506 * still be able to restore itself to its previous state (through the
1507 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1508 * function returns null.
1509 *
1510 * @return Returns the object previously returned by
1511 * {@link #onRetainNonConfigurationChildInstances()}
1512 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001513 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1514 return mLastNonConfigurationInstances != null
1515 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517
1518 /**
1519 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1520 * it should return either a mapping from child activity id strings to arbitrary objects,
1521 * or null. This method is intended to be used by Activity framework subclasses that control a
1522 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1523 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1524 */
1525 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1526 return null;
1527 }
1528
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001529 NonConfigurationInstances retainNonConfigurationInstances() {
1530 Object activity = onRetainNonConfigurationInstance();
1531 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1532 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001533 boolean retainLoaders = false;
1534 if (mAllLoaderManagers != null) {
1535 // prune out any loader managers that were already stopped, so
1536 // have nothing useful to retain.
1537 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
1538 LoaderManager lm = mAllLoaderManagers.valueAt(i);
1539 if (lm.mRetaining) {
1540 retainLoaders = true;
1541 } else {
1542 mAllLoaderManagers.removeAt(i);
1543 }
1544 }
1545 }
1546 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001547 return null;
1548 }
1549
1550 NonConfigurationInstances nci = new NonConfigurationInstances();
1551 nci.activity = activity;
1552 nci.children = children;
1553 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001554 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001555 return nci;
1556 }
1557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 public void onLowMemory() {
1559 mCalled = true;
1560 }
1561
1562 /**
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001563 * Start a series of edit operations on the Fragments associated with
1564 * this activity.
1565 */
1566 public FragmentTransaction openFragmentTransaction() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001567 return new BackStackEntry(mFragments);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001568 }
1569
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001570 void invalidateFragmentIndex(int index) {
1571 if (mAllLoaderManagers != null) {
1572 mAllLoaderManagers.remove(index);
1573 }
1574 }
1575
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001576 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001577 * Called when a Fragment is being attached to this activity, immediately
1578 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1579 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1580 */
1581 public void onAttachFragment(Fragment fragment) {
1582 }
1583
1584 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 * Wrapper around
1586 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1587 * that gives the resulting {@link Cursor} to call
1588 * {@link #startManagingCursor} so that the activity will manage its
1589 * lifecycle for you.
1590 *
1591 * @param uri The URI of the content provider to query.
1592 * @param projection List of columns to return.
1593 * @param selection SQL WHERE clause.
1594 * @param sortOrder SQL ORDER BY clause.
1595 *
1596 * @return The Cursor that was returned by query().
1597 *
1598 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1599 * @see #startManagingCursor
1600 * @hide
1601 */
1602 public final Cursor managedQuery(Uri uri,
1603 String[] projection,
1604 String selection,
1605 String sortOrder)
1606 {
1607 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1608 if (c != null) {
1609 startManagingCursor(c);
1610 }
1611 return c;
1612 }
1613
1614 /**
1615 * Wrapper around
1616 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1617 * that gives the resulting {@link Cursor} to call
1618 * {@link #startManagingCursor} so that the activity will manage its
1619 * lifecycle for you.
1620 *
1621 * @param uri The URI of the content provider to query.
1622 * @param projection List of columns to return.
1623 * @param selection SQL WHERE clause.
1624 * @param selectionArgs The arguments to selection, if any ?s are pesent
1625 * @param sortOrder SQL ORDER BY clause.
1626 *
1627 * @return The Cursor that was returned by query().
1628 *
1629 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1630 * @see #startManagingCursor
1631 */
1632 public final Cursor managedQuery(Uri uri,
1633 String[] projection,
1634 String selection,
1635 String[] selectionArgs,
1636 String sortOrder)
1637 {
1638 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1639 if (c != null) {
1640 startManagingCursor(c);
1641 }
1642 return c;
1643 }
1644
1645 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 * This method allows the activity to take care of managing the given
1647 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1648 * That is, when the activity is stopped it will automatically call
1649 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1650 * it will call {@link Cursor#requery} for you. When the activity is
1651 * destroyed, all managed Cursors will be closed automatically.
1652 *
1653 * @param c The Cursor to be managed.
1654 *
1655 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1656 * @see #stopManagingCursor
1657 */
1658 public void startManagingCursor(Cursor c) {
1659 synchronized (mManagedCursors) {
1660 mManagedCursors.add(new ManagedCursor(c));
1661 }
1662 }
1663
1664 /**
1665 * Given a Cursor that was previously given to
1666 * {@link #startManagingCursor}, stop the activity's management of that
1667 * cursor.
1668 *
1669 * @param c The Cursor that was being managed.
1670 *
1671 * @see #startManagingCursor
1672 */
1673 public void stopManagingCursor(Cursor c) {
1674 synchronized (mManagedCursors) {
1675 final int N = mManagedCursors.size();
1676 for (int i=0; i<N; i++) {
1677 ManagedCursor mc = mManagedCursors.get(i);
1678 if (mc.mCursor == c) {
1679 mManagedCursors.remove(i);
1680 break;
1681 }
1682 }
1683 }
1684 }
1685
1686 /**
1687 * Control whether this activity is required to be persistent. By default
1688 * activities are not persistent; setting this to true will prevent the
1689 * system from stopping this activity or its process when running low on
1690 * resources.
1691 *
1692 * <p><em>You should avoid using this method</em>, it has severe negative
1693 * consequences on how well the system can manage its resources. A better
1694 * approach is to implement an application service that you control with
1695 * {@link Context#startService} and {@link Context#stopService}.
1696 *
1697 * @param isPersistent Control whether the current activity must be
1698 * persistent, true if so, false for the normal
1699 * behavior.
1700 */
1701 public void setPersistent(boolean isPersistent) {
1702 if (mParent == null) {
1703 try {
1704 ActivityManagerNative.getDefault()
1705 .setPersistent(mToken, isPersistent);
1706 } catch (RemoteException e) {
1707 // Empty
1708 }
1709 } else {
1710 throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1711 }
1712 }
1713
1714 /**
1715 * Finds a view that was identified by the id attribute from the XML that
1716 * was processed in {@link #onCreate}.
1717 *
1718 * @return The view if found or null otherwise.
1719 */
1720 public View findViewById(int id) {
1721 return getWindow().findViewById(id);
1722 }
Adam Powell33b97432010-04-20 10:01:14 -07001723
1724 /**
1725 * Retrieve a reference to this activity's ActionBar.
1726 *
1727 * <p><em>Note:</em> The ActionBar is initialized when a content view
1728 * is set. This function will return null if called before {@link #setContentView}
1729 * or {@link #addContentView}.
1730 * @return The Activity's ActionBar, or null if it does not have one.
1731 */
1732 public ActionBar getActionBar() {
1733 return mActionBar;
1734 }
1735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 /**
Adam Powell33b97432010-04-20 10:01:14 -07001737 * Creates a new ActionBar, locates the inflated ActionBarView,
1738 * initializes the ActionBar with the view, and sets mActionBar.
1739 */
1740 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001741 Window window = getWindow();
Adam Powell661c9082010-07-02 10:09:44 -07001742 if (!window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001743 return;
1744 }
1745
Adam Powell661c9082010-07-02 10:09:44 -07001746 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001747 }
1748
1749 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001750 * Finds a fragment that was identified by the given id either when inflated
1751 * from XML or as the container ID when added in a transaction. This only
1752 * returns fragments that are currently added to the activity's content.
1753 * @return The fragment if found or null otherwise.
1754 */
1755 public Fragment findFragmentById(int id) {
1756 return mFragments.findFragmentById(id);
1757 }
1758
1759 /**
1760 * Finds a fragment that was identified by the given tag either when inflated
1761 * from XML or as supplied when added in a transaction. This only
1762 * returns fragments that are currently added to the activity's content.
1763 * @return The fragment if found or null otherwise.
1764 */
1765 public Fragment findFragmentByTag(String tag) {
1766 return mFragments.findFragmentByTag(tag);
1767 }
1768
1769 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 * Set the activity content from a layout resource. The resource will be
1771 * inflated, adding all top-level views to the activity.
1772 *
1773 * @param layoutResID Resource ID to be inflated.
1774 */
1775 public void setContentView(int layoutResID) {
1776 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001777 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779
1780 /**
1781 * Set the activity content to an explicit view. This view is placed
1782 * directly into the activity's view hierarchy. It can itself be a complex
1783 * view hierarhcy.
1784 *
1785 * @param view The desired content to display.
1786 */
1787 public void setContentView(View view) {
1788 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001789 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791
1792 /**
1793 * Set the activity content to an explicit view. This view is placed
1794 * directly into the activity's view hierarchy. It can itself be a complex
1795 * view hierarhcy.
1796 *
1797 * @param view The desired content to display.
1798 * @param params Layout parameters for the view.
1799 */
1800 public void setContentView(View view, ViewGroup.LayoutParams params) {
1801 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001802 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804
1805 /**
1806 * Add an additional content view to the activity. Added after any existing
1807 * ones in the activity -- existing views are NOT removed.
1808 *
1809 * @param view The desired content to display.
1810 * @param params Layout parameters for the view.
1811 */
1812 public void addContentView(View view, ViewGroup.LayoutParams params) {
1813 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001814 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816
1817 /**
1818 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1819 * keys.
1820 *
1821 * @see #setDefaultKeyMode
1822 */
1823 static public final int DEFAULT_KEYS_DISABLE = 0;
1824 /**
1825 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1826 * key handling.
1827 *
1828 * @see #setDefaultKeyMode
1829 */
1830 static public final int DEFAULT_KEYS_DIALER = 1;
1831 /**
1832 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1833 * default key handling.
1834 *
1835 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1836 *
1837 * @see #setDefaultKeyMode
1838 */
1839 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1840 /**
1841 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1842 * will start an application-defined search. (If the application or activity does not
1843 * actually define a search, the the keys will be ignored.)
1844 *
1845 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1846 *
1847 * @see #setDefaultKeyMode
1848 */
1849 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1850
1851 /**
1852 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1853 * will start a global search (typically web search, but some platforms may define alternate
1854 * methods for global search)
1855 *
1856 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1857 *
1858 * @see #setDefaultKeyMode
1859 */
1860 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1861
1862 /**
1863 * Select the default key handling for this activity. This controls what
1864 * will happen to key events that are not otherwise handled. The default
1865 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1866 * floor. Other modes allow you to launch the dialer
1867 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1868 * menu without requiring the menu key be held down
1869 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1870 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1871 *
1872 * <p>Note that the mode selected here does not impact the default
1873 * handling of system keys, such as the "back" and "menu" keys, and your
1874 * activity and its views always get a first chance to receive and handle
1875 * all application keys.
1876 *
1877 * @param mode The desired default key mode constant.
1878 *
1879 * @see #DEFAULT_KEYS_DISABLE
1880 * @see #DEFAULT_KEYS_DIALER
1881 * @see #DEFAULT_KEYS_SHORTCUT
1882 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1883 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1884 * @see #onKeyDown
1885 */
1886 public final void setDefaultKeyMode(int mode) {
1887 mDefaultKeyMode = mode;
1888
1889 // Some modes use a SpannableStringBuilder to track & dispatch input events
1890 // This list must remain in sync with the switch in onKeyDown()
1891 switch (mode) {
1892 case DEFAULT_KEYS_DISABLE:
1893 case DEFAULT_KEYS_SHORTCUT:
1894 mDefaultKeySsb = null; // not used in these modes
1895 break;
1896 case DEFAULT_KEYS_DIALER:
1897 case DEFAULT_KEYS_SEARCH_LOCAL:
1898 case DEFAULT_KEYS_SEARCH_GLOBAL:
1899 mDefaultKeySsb = new SpannableStringBuilder();
1900 Selection.setSelection(mDefaultKeySsb,0);
1901 break;
1902 default:
1903 throw new IllegalArgumentException();
1904 }
1905 }
1906
1907 /**
1908 * Called when a key was pressed down and not handled by any of the views
1909 * inside of the activity. So, for example, key presses while the cursor
1910 * is inside a TextView will not trigger the event (unless it is a navigation
1911 * to another object) because TextView handles its own key presses.
1912 *
1913 * <p>If the focused view didn't want this event, this method is called.
1914 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001915 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1916 * by calling {@link #onBackPressed()}, though the behavior varies based
1917 * on the application compatibility mode: for
1918 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1919 * it will set up the dispatch to call {@link #onKeyUp} where the action
1920 * will be performed; for earlier applications, it will perform the
1921 * action immediately in on-down, as those versions of the platform
1922 * behaved.
1923 *
1924 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001925 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 *
1927 * @return Return <code>true</code> to prevent this event from being propagated
1928 * further, or <code>false</code> to indicate that you have not handled
1929 * this event and it should continue to be propagated.
1930 * @see #onKeyUp
1931 * @see android.view.KeyEvent
1932 */
1933 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001934 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001935 if (getApplicationInfo().targetSdkVersion
1936 >= Build.VERSION_CODES.ECLAIR) {
1937 event.startTracking();
1938 } else {
1939 onBackPressed();
1940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 return true;
1942 }
1943
1944 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1945 return false;
1946 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001947 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1948 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1949 return true;
1950 }
1951 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 } else {
1953 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1954 boolean clearSpannable = false;
1955 boolean handled;
1956 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1957 clearSpannable = true;
1958 handled = false;
1959 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001960 handled = TextKeyListener.getInstance().onKeyDown(
1961 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 if (handled && mDefaultKeySsb.length() > 0) {
1963 // something useable has been typed - dispatch it now.
1964
1965 final String str = mDefaultKeySsb.toString();
1966 clearSpannable = true;
1967
1968 switch (mDefaultKeyMode) {
1969 case DEFAULT_KEYS_DIALER:
1970 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1971 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1972 startActivity(intent);
1973 break;
1974 case DEFAULT_KEYS_SEARCH_LOCAL:
1975 startSearch(str, false, null, false);
1976 break;
1977 case DEFAULT_KEYS_SEARCH_GLOBAL:
1978 startSearch(str, false, null, true);
1979 break;
1980 }
1981 }
1982 }
1983 if (clearSpannable) {
1984 mDefaultKeySsb.clear();
1985 mDefaultKeySsb.clearSpans();
1986 Selection.setSelection(mDefaultKeySsb,0);
1987 }
1988 return handled;
1989 }
1990 }
1991
1992 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001993 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
1994 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
1995 * the event).
1996 */
1997 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1998 return false;
1999 }
2000
2001 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 * Called when a key was released and not handled by any of the views
2003 * inside of the activity. So, for example, key presses while the cursor
2004 * is inside a TextView will not trigger the event (unless it is a navigation
2005 * to another object) because TextView handles its own key presses.
2006 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002007 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2008 * and go back.
2009 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 * @return Return <code>true</code> to prevent this event from being propagated
2011 * further, or <code>false</code> to indicate that you have not handled
2012 * this event and it should continue to be propagated.
2013 * @see #onKeyDown
2014 * @see KeyEvent
2015 */
2016 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002017 if (getApplicationInfo().targetSdkVersion
2018 >= Build.VERSION_CODES.ECLAIR) {
2019 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2020 && !event.isCanceled()) {
2021 onBackPressed();
2022 return true;
2023 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 return false;
2026 }
2027
2028 /**
2029 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2030 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2031 * the event).
2032 */
2033 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2034 return false;
2035 }
2036
2037 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002038 * Pop the last fragment transition from the local activity's fragment
2039 * back stack. If there is nothing to pop, false is returned.
Dianne Hackbornf121be72010-05-06 14:10:32 -07002040 * @param name If non-null, this is the name of a previous back state
2041 * to look for; if found, all states up to (but not including) that
2042 * state will be popped. If null, only the top state is popped.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002043 */
Dianne Hackbornf121be72010-05-06 14:10:32 -07002044 public boolean popBackStack(String name) {
2045 return mFragments.popBackStackState(mHandler, name);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002046 }
2047
2048 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002049 * Called when the activity has detected the user's press of the back
2050 * key. The default implementation simply finishes the current activity,
2051 * but you can override this to do whatever you want.
2052 */
2053 public void onBackPressed() {
Dianne Hackbornf121be72010-05-06 14:10:32 -07002054 if (!popBackStack(null)) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002055 finish();
2056 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002057 }
2058
2059 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 * Called when a touch screen event was not handled by any of the views
2061 * under it. This is most useful to process touch events that happen
2062 * outside of your window bounds, where there is no view to receive it.
2063 *
2064 * @param event The touch screen event being processed.
2065 *
2066 * @return Return true if you have consumed the event, false if you haven't.
2067 * The default implementation always returns false.
2068 */
2069 public boolean onTouchEvent(MotionEvent event) {
2070 return false;
2071 }
2072
2073 /**
2074 * Called when the trackball was moved and not handled by any of the
2075 * views inside of the activity. So, for example, if the trackball moves
2076 * while focus is on a button, you will receive a call here because
2077 * buttons do not normally do anything with trackball events. The call
2078 * here happens <em>before</em> trackball movements are converted to
2079 * DPAD key events, which then get sent back to the view hierarchy, and
2080 * will be processed at the point for things like focus navigation.
2081 *
2082 * @param event The trackball event being processed.
2083 *
2084 * @return Return true if you have consumed the event, false if you haven't.
2085 * The default implementation always returns false.
2086 */
2087 public boolean onTrackballEvent(MotionEvent event) {
2088 return false;
2089 }
2090
2091 /**
2092 * Called whenever a key, touch, or trackball event is dispatched to the
2093 * activity. Implement this method if you wish to know that the user has
2094 * interacted with the device in some way while your activity is running.
2095 * This callback and {@link #onUserLeaveHint} are intended to help
2096 * activities manage status bar notifications intelligently; specifically,
2097 * for helping activities determine the proper time to cancel a notfication.
2098 *
2099 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2100 * be accompanied by calls to {@link #onUserInteraction}. This
2101 * ensures that your activity will be told of relevant user activity such
2102 * as pulling down the notification pane and touching an item there.
2103 *
2104 * <p>Note that this callback will be invoked for the touch down action
2105 * that begins a touch gesture, but may not be invoked for the touch-moved
2106 * and touch-up actions that follow.
2107 *
2108 * @see #onUserLeaveHint()
2109 */
2110 public void onUserInteraction() {
2111 }
2112
2113 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2114 // Update window manager if: we have a view, that view is
2115 // attached to its parent (which will be a RootView), and
2116 // this activity is not embedded.
2117 if (mParent == null) {
2118 View decor = mDecor;
2119 if (decor != null && decor.getParent() != null) {
2120 getWindowManager().updateViewLayout(decor, params);
2121 }
2122 }
2123 }
2124
2125 public void onContentChanged() {
2126 }
2127
2128 /**
2129 * Called when the current {@link Window} of the activity gains or loses
2130 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002131 * to the user. The default implementation clears the key tracking
2132 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002134 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 * is managed independently of activity lifecycles. As such, while focus
2136 * changes will generally have some relation to lifecycle changes (an
2137 * activity that is stopped will not generally get window focus), you
2138 * should not rely on any particular order between the callbacks here and
2139 * those in the other lifecycle methods such as {@link #onResume}.
2140 *
2141 * <p>As a general rule, however, a resumed activity will have window
2142 * focus... unless it has displayed other dialogs or popups that take
2143 * input focus, in which case the activity itself will not have focus
2144 * when the other windows have it. Likewise, the system may display
2145 * system-level windows (such as the status bar notification panel or
2146 * a system alert) which will temporarily take window input focus without
2147 * pausing the foreground activity.
2148 *
2149 * @param hasFocus Whether the window of this activity has focus.
2150 *
2151 * @see #hasWindowFocus()
2152 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002153 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 */
2155 public void onWindowFocusChanged(boolean hasFocus) {
2156 }
2157
2158 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002159 * Called when the main window associated with the activity has been
2160 * attached to the window manager.
2161 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2162 * for more information.
2163 * @see View#onAttachedToWindow
2164 */
2165 public void onAttachedToWindow() {
2166 }
2167
2168 /**
2169 * Called when the main window associated with the activity has been
2170 * detached from the window manager.
2171 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2172 * for more information.
2173 * @see View#onDetachedFromWindow
2174 */
2175 public void onDetachedFromWindow() {
2176 }
2177
2178 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 * Returns true if this activity's <em>main</em> window currently has window focus.
2180 * Note that this is not the same as the view itself having focus.
2181 *
2182 * @return True if this activity's main window currently has window focus.
2183 *
2184 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2185 */
2186 public boolean hasWindowFocus() {
2187 Window w = getWindow();
2188 if (w != null) {
2189 View d = w.getDecorView();
2190 if (d != null) {
2191 return d.hasWindowFocus();
2192 }
2193 }
2194 return false;
2195 }
2196
2197 /**
2198 * Called to process key events. You can override this to intercept all
2199 * key events before they are dispatched to the window. Be sure to call
2200 * this implementation for key events that should be handled normally.
2201 *
2202 * @param event The key event.
2203 *
2204 * @return boolean Return true if this event was consumed.
2205 */
2206 public boolean dispatchKeyEvent(KeyEvent event) {
2207 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002208 Window win = getWindow();
2209 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 return true;
2211 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002212 View decor = mDecor;
2213 if (decor == null) decor = win.getDecorView();
2214 return event.dispatch(this, decor != null
2215 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 }
2217
2218 /**
2219 * Called to process touch screen events. You can override this to
2220 * intercept all touch screen events before they are dispatched to the
2221 * window. Be sure to call this implementation for touch screen events
2222 * that should be handled normally.
2223 *
2224 * @param ev The touch screen event.
2225 *
2226 * @return boolean Return true if this event was consumed.
2227 */
2228 public boolean dispatchTouchEvent(MotionEvent ev) {
2229 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2230 onUserInteraction();
2231 }
2232 if (getWindow().superDispatchTouchEvent(ev)) {
2233 return true;
2234 }
2235 return onTouchEvent(ev);
2236 }
2237
2238 /**
2239 * Called to process trackball events. You can override this to
2240 * intercept all trackball events before they are dispatched to the
2241 * window. Be sure to call this implementation for trackball events
2242 * that should be handled normally.
2243 *
2244 * @param ev The trackball event.
2245 *
2246 * @return boolean Return true if this event was consumed.
2247 */
2248 public boolean dispatchTrackballEvent(MotionEvent ev) {
2249 onUserInteraction();
2250 if (getWindow().superDispatchTrackballEvent(ev)) {
2251 return true;
2252 }
2253 return onTrackballEvent(ev);
2254 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002255
2256 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2257 event.setClassName(getClass().getName());
2258 event.setPackageName(getPackageName());
2259
2260 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002261 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2262 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002263 event.setFullScreen(isFullScreen);
2264
2265 CharSequence title = getTitle();
2266 if (!TextUtils.isEmpty(title)) {
2267 event.getText().add(title);
2268 }
2269
2270 return true;
2271 }
2272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 /**
2274 * Default implementation of
2275 * {@link android.view.Window.Callback#onCreatePanelView}
2276 * for activities. This
2277 * simply returns null so that all panel sub-windows will have the default
2278 * menu behavior.
2279 */
2280 public View onCreatePanelView(int featureId) {
2281 return null;
2282 }
2283
2284 /**
2285 * Default implementation of
2286 * {@link android.view.Window.Callback#onCreatePanelMenu}
2287 * for activities. This calls through to the new
2288 * {@link #onCreateOptionsMenu} method for the
2289 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2290 * so that subclasses of Activity don't need to deal with feature codes.
2291 */
2292 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2293 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002294 boolean show = onCreateOptionsMenu(menu);
2295 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2296 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
2298 return false;
2299 }
2300
2301 /**
2302 * Default implementation of
2303 * {@link android.view.Window.Callback#onPreparePanel}
2304 * for activities. This
2305 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2306 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2307 * panel, so that subclasses of
2308 * Activity don't need to deal with feature codes.
2309 */
2310 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2311 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2312 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002313 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 return goforit && menu.hasVisibleItems();
2315 }
2316 return true;
2317 }
2318
2319 /**
2320 * {@inheritDoc}
2321 *
2322 * @return The default implementation returns true.
2323 */
2324 public boolean onMenuOpened(int featureId, Menu menu) {
2325 return true;
2326 }
2327
2328 /**
2329 * Default implementation of
2330 * {@link android.view.Window.Callback#onMenuItemSelected}
2331 * for activities. This calls through to the new
2332 * {@link #onOptionsItemSelected} method for the
2333 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2334 * panel, so that subclasses of
2335 * Activity don't need to deal with feature codes.
2336 */
2337 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2338 switch (featureId) {
2339 case Window.FEATURE_OPTIONS_PANEL:
2340 // Put event logging here so it gets called even if subclass
2341 // doesn't call through to superclass's implmeentation of each
2342 // of these methods below
2343 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002344 if (onOptionsItemSelected(item)) {
2345 return true;
2346 }
2347 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348
2349 case Window.FEATURE_CONTEXT_MENU:
2350 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002351 if (onContextItemSelected(item)) {
2352 return true;
2353 }
2354 return mFragments.dispatchContextItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355
2356 default:
2357 return false;
2358 }
2359 }
2360
2361 /**
2362 * Default implementation of
2363 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2364 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2365 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2366 * so that subclasses of Activity don't need to deal with feature codes.
2367 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2368 * {@link #onContextMenuClosed(Menu)} will be called.
2369 */
2370 public void onPanelClosed(int featureId, Menu menu) {
2371 switch (featureId) {
2372 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002373 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 onOptionsMenuClosed(menu);
2375 break;
2376
2377 case Window.FEATURE_CONTEXT_MENU:
2378 onContextMenuClosed(menu);
2379 break;
2380 }
2381 }
2382
2383 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002384 * Declare that the options menu has changed, so should be recreated.
2385 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2386 * time it needs to be displayed.
2387 */
2388 public void invalidateOptionsMenu() {
2389 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2390 }
2391
2392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 * Initialize the contents of the Activity's standard options menu. You
2394 * should place your menu items in to <var>menu</var>.
2395 *
2396 * <p>This is only called once, the first time the options menu is
2397 * displayed. To update the menu every time it is displayed, see
2398 * {@link #onPrepareOptionsMenu}.
2399 *
2400 * <p>The default implementation populates the menu with standard system
2401 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2402 * they will be correctly ordered with application-defined menu items.
2403 * Deriving classes should always call through to the base implementation.
2404 *
2405 * <p>You can safely hold on to <var>menu</var> (and any items created
2406 * from it), making modifications to it as desired, until the next
2407 * time onCreateOptionsMenu() is called.
2408 *
2409 * <p>When you add items to the menu, you can implement the Activity's
2410 * {@link #onOptionsItemSelected} method to handle them there.
2411 *
2412 * @param menu The options menu in which you place your items.
2413 *
2414 * @return You must return true for the menu to be displayed;
2415 * if you return false it will not be shown.
2416 *
2417 * @see #onPrepareOptionsMenu
2418 * @see #onOptionsItemSelected
2419 */
2420 public boolean onCreateOptionsMenu(Menu menu) {
2421 if (mParent != null) {
2422 return mParent.onCreateOptionsMenu(menu);
2423 }
2424 return true;
2425 }
2426
2427 /**
2428 * Prepare the Screen's standard options menu to be displayed. This is
2429 * called right before the menu is shown, every time it is shown. You can
2430 * use this method to efficiently enable/disable items or otherwise
2431 * dynamically modify the contents.
2432 *
2433 * <p>The default implementation updates the system menu items based on the
2434 * activity's state. Deriving classes should always call through to the
2435 * base class implementation.
2436 *
2437 * @param menu The options menu as last shown or first initialized by
2438 * onCreateOptionsMenu().
2439 *
2440 * @return You must return true for the menu to be displayed;
2441 * if you return false it will not be shown.
2442 *
2443 * @see #onCreateOptionsMenu
2444 */
2445 public boolean onPrepareOptionsMenu(Menu menu) {
2446 if (mParent != null) {
2447 return mParent.onPrepareOptionsMenu(menu);
2448 }
2449 return true;
2450 }
2451
2452 /**
2453 * This hook is called whenever an item in your options menu is selected.
2454 * The default implementation simply returns false to have the normal
2455 * processing happen (calling the item's Runnable or sending a message to
2456 * its Handler as appropriate). You can use this method for any items
2457 * for which you would like to do processing without those other
2458 * facilities.
2459 *
2460 * <p>Derived classes should call through to the base class for it to
2461 * perform the default menu handling.
2462 *
2463 * @param item The menu item that was selected.
2464 *
2465 * @return boolean Return false to allow normal menu processing to
2466 * proceed, true to consume it here.
2467 *
2468 * @see #onCreateOptionsMenu
2469 */
2470 public boolean onOptionsItemSelected(MenuItem item) {
2471 if (mParent != null) {
2472 return mParent.onOptionsItemSelected(item);
2473 }
2474 return false;
2475 }
2476
2477 /**
2478 * This hook is called whenever the options menu is being closed (either by the user canceling
2479 * the menu with the back/menu button, or when an item is selected).
2480 *
2481 * @param menu The options menu as last shown or first initialized by
2482 * onCreateOptionsMenu().
2483 */
2484 public void onOptionsMenuClosed(Menu menu) {
2485 if (mParent != null) {
2486 mParent.onOptionsMenuClosed(menu);
2487 }
2488 }
2489
2490 /**
2491 * Programmatically opens the options menu. If the options menu is already
2492 * open, this method does nothing.
2493 */
2494 public void openOptionsMenu() {
2495 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2496 }
2497
2498 /**
2499 * Progammatically closes the options menu. If the options menu is already
2500 * closed, this method does nothing.
2501 */
2502 public void closeOptionsMenu() {
2503 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2504 }
2505
2506 /**
2507 * Called when a context menu for the {@code view} is about to be shown.
2508 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2509 * time the context menu is about to be shown and should be populated for
2510 * the view (or item inside the view for {@link AdapterView} subclasses,
2511 * this can be found in the {@code menuInfo})).
2512 * <p>
2513 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2514 * item has been selected.
2515 * <p>
2516 * It is not safe to hold onto the context menu after this method returns.
2517 * {@inheritDoc}
2518 */
2519 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2520 }
2521
2522 /**
2523 * Registers a context menu to be shown for the given view (multiple views
2524 * can show the context menu). This method will set the
2525 * {@link OnCreateContextMenuListener} on the view to this activity, so
2526 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2527 * called when it is time to show the context menu.
2528 *
2529 * @see #unregisterForContextMenu(View)
2530 * @param view The view that should show a context menu.
2531 */
2532 public void registerForContextMenu(View view) {
2533 view.setOnCreateContextMenuListener(this);
2534 }
2535
2536 /**
2537 * Prevents a context menu to be shown for the given view. This method will remove the
2538 * {@link OnCreateContextMenuListener} on the view.
2539 *
2540 * @see #registerForContextMenu(View)
2541 * @param view The view that should stop showing a context menu.
2542 */
2543 public void unregisterForContextMenu(View view) {
2544 view.setOnCreateContextMenuListener(null);
2545 }
2546
2547 /**
2548 * Programmatically opens the context menu for a particular {@code view}.
2549 * The {@code view} should have been added via
2550 * {@link #registerForContextMenu(View)}.
2551 *
2552 * @param view The view to show the context menu for.
2553 */
2554 public void openContextMenu(View view) {
2555 view.showContextMenu();
2556 }
2557
2558 /**
2559 * Programmatically closes the most recently opened context menu, if showing.
2560 */
2561 public void closeContextMenu() {
2562 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2563 }
2564
2565 /**
2566 * This hook is called whenever an item in a context menu is selected. The
2567 * default implementation simply returns false to have the normal processing
2568 * happen (calling the item's Runnable or sending a message to its Handler
2569 * as appropriate). You can use this method for any items for which you
2570 * would like to do processing without those other facilities.
2571 * <p>
2572 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2573 * View that added this menu item.
2574 * <p>
2575 * Derived classes should call through to the base class for it to perform
2576 * the default menu handling.
2577 *
2578 * @param item The context menu item that was selected.
2579 * @return boolean Return false to allow normal context menu processing to
2580 * proceed, true to consume it here.
2581 */
2582 public boolean onContextItemSelected(MenuItem item) {
2583 if (mParent != null) {
2584 return mParent.onContextItemSelected(item);
2585 }
2586 return false;
2587 }
2588
2589 /**
2590 * This hook is called whenever the context menu is being closed (either by
2591 * the user canceling the menu with the back/menu button, or when an item is
2592 * selected).
2593 *
2594 * @param menu The context menu that is being closed.
2595 */
2596 public void onContextMenuClosed(Menu menu) {
2597 if (mParent != null) {
2598 mParent.onContextMenuClosed(menu);
2599 }
2600 }
2601
2602 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002603 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002605 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 protected Dialog onCreateDialog(int id) {
2607 return null;
2608 }
2609
2610 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002611 * Callback for creating dialogs that are managed (saved and restored) for you
2612 * by the activity. The default implementation calls through to
2613 * {@link #onCreateDialog(int)} for compatibility.
2614 *
2615 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2616 * this method the first time, and hang onto it thereafter. Any dialog
2617 * that is created by this method will automatically be saved and restored
2618 * for you, including whether it is showing.
2619 *
2620 * <p>If you would like the activity to manage saving and restoring dialogs
2621 * for you, you should override this method and handle any ids that are
2622 * passed to {@link #showDialog}.
2623 *
2624 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2625 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2626 *
2627 * @param id The id of the dialog.
2628 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2629 * @return The dialog. If you return null, the dialog will not be created.
2630 *
2631 * @see #onPrepareDialog(int, Dialog, Bundle)
2632 * @see #showDialog(int, Bundle)
2633 * @see #dismissDialog(int)
2634 * @see #removeDialog(int)
2635 */
2636 protected Dialog onCreateDialog(int id, Bundle args) {
2637 return onCreateDialog(id);
2638 }
2639
2640 /**
2641 * @deprecated Old no-arguments version of
2642 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2643 */
2644 @Deprecated
2645 protected void onPrepareDialog(int id, Dialog dialog) {
2646 dialog.setOwnerActivity(this);
2647 }
2648
2649 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002651 * shown. The default implementation calls through to
2652 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2653 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 * <p>
2655 * Override this if you need to update a managed dialog based on the state
2656 * of the application each time it is shown. For example, a time picker
2657 * dialog might want to be updated with the current time. You should call
2658 * through to the superclass's implementation. The default implementation
2659 * will set this Activity as the owner activity on the Dialog.
2660 *
2661 * @param id The id of the managed dialog.
2662 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002663 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2664 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 * @see #showDialog(int)
2666 * @see #dismissDialog(int)
2667 * @see #removeDialog(int)
2668 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002669 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2670 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672
2673 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002674 * Simple version of {@link #showDialog(int, Bundle)} that does not
2675 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2676 * with null arguments.
2677 */
2678 public final void showDialog(int id) {
2679 showDialog(id, null);
2680 }
2681
2682 /**
2683 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 * will be made with the same id the first time this is called for a given
2685 * id. From thereafter, the dialog will be automatically saved and restored.
2686 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002687 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 * be made to provide an opportunity to do any timely preparation.
2689 *
2690 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002691 * @param args Arguments to pass through to the dialog. These will be saved
2692 * and restored for you. Note that if the dialog is already created,
2693 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2694 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002695 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002696 * @return Returns true if the Dialog was created; false is returned if
2697 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2698 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002699 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002700 * @see #onCreateDialog(int, Bundle)
2701 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 * @see #dismissDialog(int)
2703 * @see #removeDialog(int)
2704 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002705 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002707 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002709 ManagedDialog md = mManagedDialogs.get(id);
2710 if (md == null) {
2711 md = new ManagedDialog();
2712 md.mDialog = createDialog(id, null, args);
2713 if (md.mDialog == null) {
2714 return false;
2715 }
2716 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
2718
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002719 md.mArgs = args;
2720 onPrepareDialog(id, md.mDialog, args);
2721 md.mDialog.show();
2722 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724
2725 /**
2726 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2727 *
2728 * @param id The id of the managed dialog.
2729 *
2730 * @throws IllegalArgumentException if the id was not previously shown via
2731 * {@link #showDialog(int)}.
2732 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002733 * @see #onCreateDialog(int, Bundle)
2734 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 * @see #showDialog(int)
2736 * @see #removeDialog(int)
2737 */
2738 public final void dismissDialog(int id) {
2739 if (mManagedDialogs == null) {
2740 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002742
2743 final ManagedDialog md = mManagedDialogs.get(id);
2744 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 throw missingDialog(id);
2746 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002747 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749
2750 /**
2751 * Creates an exception to throw if a user passed in a dialog id that is
2752 * unexpected.
2753 */
2754 private IllegalArgumentException missingDialog(int id) {
2755 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2756 + "shown via Activity#showDialog");
2757 }
2758
2759 /**
2760 * Removes any internal references to a dialog managed by this Activity.
2761 * If the dialog is showing, it will dismiss it as part of the clean up.
2762 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002763 * <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 -08002764 * want to avoid the overhead of saving and restoring it in the future.
2765 *
2766 * @param id The id of the managed dialog.
2767 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002768 * @see #onCreateDialog(int, Bundle)
2769 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 * @see #showDialog(int)
2771 * @see #dismissDialog(int)
2772 */
2773 public final void removeDialog(int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 if (mManagedDialogs == null) {
2775 return;
2776 }
2777
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002778 final ManagedDialog md = mManagedDialogs.get(id);
2779 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 return;
2781 }
2782
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002783 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 mManagedDialogs.remove(id);
2785 }
2786
2787 /**
2788 * This hook is called when the user signals the desire to start a search.
2789 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002790 * <p>You can use this function as a simple way to launch the search UI, in response to a
2791 * menu item, search button, or other widgets within your activity. Unless overidden,
2792 * calling this function is the same as calling
2793 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2794 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 *
2796 * <p>You can override this function to force global search, e.g. in response to a dedicated
2797 * search key, or to block search entirely (by simply returning false).
2798 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002799 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2800 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 *
2802 * @see android.app.SearchManager
2803 */
2804 public boolean onSearchRequested() {
2805 startSearch(null, false, null, false);
2806 return true;
2807 }
2808
2809 /**
2810 * This hook is called to launch the search UI.
2811 *
2812 * <p>It is typically called from onSearchRequested(), either directly from
2813 * Activity.onSearchRequested() or from an overridden version in any given
2814 * Activity. If your goal is simply to activate search, it is preferred to call
2815 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2816 * is to inject specific data such as context data, it is preferred to <i>override</i>
2817 * onSearchRequested(), so that any callers to it will benefit from the override.
2818 *
2819 * @param initialQuery Any non-null non-empty string will be inserted as
2820 * pre-entered text in the search query box.
2821 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2822 * any further typing will replace it. This is useful for cases where an entire pre-formed
2823 * query is being inserted. If false, the selection point will be placed at the end of the
2824 * inserted query. This is useful when the inserted query is text that the user entered,
2825 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2826 * if initialQuery is a non-empty string.</i>
2827 * @param appSearchData An application can insert application-specific
2828 * context here, in order to improve quality or specificity of its own
2829 * searches. This data will be returned with SEARCH intent(s). Null if
2830 * no extra data is required.
2831 * @param globalSearch If false, this will only launch the search that has been specifically
2832 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002833 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2835 *
2836 * @see android.app.SearchManager
2837 * @see #onSearchRequested
2838 */
2839 public void startSearch(String initialQuery, boolean selectInitialQuery,
2840 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002841 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002842 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 appSearchData, globalSearch);
2844 }
2845
2846 /**
krosaend2d60142009-08-17 08:56:48 -07002847 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2848 * the search dialog. Made available for testing purposes.
2849 *
2850 * @param query The query to trigger. If empty, the request will be ignored.
2851 * @param appSearchData An application can insert application-specific
2852 * context here, in order to improve quality or specificity of its own
2853 * searches. This data will be returned with SEARCH intent(s). Null if
2854 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002855 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002856 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002857 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002858 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002859 }
2860
2861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 * Request that key events come to this activity. Use this if your
2863 * activity has no views with focus, but the activity still wants
2864 * a chance to process key events.
2865 *
2866 * @see android.view.Window#takeKeyEvents
2867 */
2868 public void takeKeyEvents(boolean get) {
2869 getWindow().takeKeyEvents(get);
2870 }
2871
2872 /**
2873 * Enable extended window features. This is a convenience for calling
2874 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2875 *
2876 * @param featureId The desired feature as defined in
2877 * {@link android.view.Window}.
2878 * @return Returns true if the requested feature is supported and now
2879 * enabled.
2880 *
2881 * @see android.view.Window#requestFeature
2882 */
2883 public final boolean requestWindowFeature(int featureId) {
2884 return getWindow().requestFeature(featureId);
2885 }
2886
2887 /**
2888 * Convenience for calling
2889 * {@link android.view.Window#setFeatureDrawableResource}.
2890 */
2891 public final void setFeatureDrawableResource(int featureId, int resId) {
2892 getWindow().setFeatureDrawableResource(featureId, resId);
2893 }
2894
2895 /**
2896 * Convenience for calling
2897 * {@link android.view.Window#setFeatureDrawableUri}.
2898 */
2899 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2900 getWindow().setFeatureDrawableUri(featureId, uri);
2901 }
2902
2903 /**
2904 * Convenience for calling
2905 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2906 */
2907 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2908 getWindow().setFeatureDrawable(featureId, drawable);
2909 }
2910
2911 /**
2912 * Convenience for calling
2913 * {@link android.view.Window#setFeatureDrawableAlpha}.
2914 */
2915 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2916 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2917 }
2918
2919 /**
2920 * Convenience for calling
2921 * {@link android.view.Window#getLayoutInflater}.
2922 */
2923 public LayoutInflater getLayoutInflater() {
2924 return getWindow().getLayoutInflater();
2925 }
2926
2927 /**
2928 * Returns a {@link MenuInflater} with this context.
2929 */
2930 public MenuInflater getMenuInflater() {
2931 return new MenuInflater(this);
2932 }
2933
2934 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002935 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2936 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 if (mParent == null) {
2938 super.onApplyThemeResource(theme, resid, first);
2939 } else {
2940 try {
2941 theme.setTo(mParent.getTheme());
2942 } catch (Exception e) {
2943 // Empty
2944 }
2945 theme.applyStyle(resid, false);
2946 }
2947 }
2948
2949 /**
2950 * Launch an activity for which you would like a result when it finished.
2951 * When this activity exits, your
2952 * onActivityResult() method will be called with the given requestCode.
2953 * Using a negative requestCode is the same as calling
2954 * {@link #startActivity} (the activity is not launched as a sub-activity).
2955 *
2956 * <p>Note that this method should only be used with Intent protocols
2957 * that are defined to return a result. In other protocols (such as
2958 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
2959 * not get the result when you expect. For example, if the activity you
2960 * are launching uses the singleTask launch mode, it will not run in your
2961 * task and thus you will immediately receive a cancel result.
2962 *
2963 * <p>As a special case, if you call startActivityForResult() with a requestCode
2964 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
2965 * activity, then your window will not be displayed until a result is
2966 * returned back from the started activity. This is to avoid visible
2967 * flickering when redirecting to another activity.
2968 *
2969 * <p>This method throws {@link android.content.ActivityNotFoundException}
2970 * if there was no Activity found to run the given Intent.
2971 *
2972 * @param intent The intent to start.
2973 * @param requestCode If >= 0, this code will be returned in
2974 * onActivityResult() when the activity exits.
2975 *
2976 * @throws android.content.ActivityNotFoundException
2977 *
2978 * @see #startActivity
2979 */
2980 public void startActivityForResult(Intent intent, int requestCode) {
2981 if (mParent == null) {
2982 Instrumentation.ActivityResult ar =
2983 mInstrumentation.execStartActivity(
2984 this, mMainThread.getApplicationThread(), mToken, this,
2985 intent, requestCode);
2986 if (ar != null) {
2987 mMainThread.sendActivityResult(
2988 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
2989 ar.getResultData());
2990 }
2991 if (requestCode >= 0) {
2992 // If this start is requesting a result, we can avoid making
2993 // the activity visible until the result is received. Setting
2994 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2995 // activity hidden during this time, to avoid flickering.
2996 // This can only be done when a result is requested because
2997 // that guarantees we will get information back when the
2998 // activity is finished, no matter what happens to it.
2999 mStartedActivity = true;
3000 }
3001 } else {
3002 mParent.startActivityFromChild(this, intent, requestCode);
3003 }
3004 }
3005
3006 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003007 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003008 * to use a IntentSender to describe the activity to be started. If
3009 * the IntentSender is for an activity, that activity will be started
3010 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3011 * here; otherwise, its associated action will be executed (such as
3012 * sending a broadcast) as if you had called
3013 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003014 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003015 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003016 * @param requestCode If >= 0, this code will be returned in
3017 * onActivityResult() when the activity exits.
3018 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003019 * intent parameter to {@link IntentSender#sendIntent}.
3020 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003021 * would like to change.
3022 * @param flagsValues Desired values for any bits set in
3023 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003024 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003025 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003026 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3027 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3028 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003029 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003030 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003031 flagsMask, flagsValues, this);
3032 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003033 mParent.startIntentSenderFromChild(this, intent, requestCode,
3034 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003035 }
3036 }
3037
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003038 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003039 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003040 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003041 try {
3042 String resolvedType = null;
3043 if (fillInIntent != null) {
3044 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3045 }
3046 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003047 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003048 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3049 requestCode, flagsMask, flagsValues);
3050 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003051 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003052 }
3053 Instrumentation.checkStartActivityResult(result, null);
3054 } catch (RemoteException e) {
3055 }
3056 if (requestCode >= 0) {
3057 // If this start is requesting a result, we can avoid making
3058 // the activity visible until the result is received. Setting
3059 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3060 // activity hidden during this time, to avoid flickering.
3061 // This can only be done when a result is requested because
3062 // that guarantees we will get information back when the
3063 // activity is finished, no matter what happens to it.
3064 mStartedActivity = true;
3065 }
3066 }
3067
3068 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 * Launch a new activity. You will not receive any information about when
3070 * the activity exits. This implementation overrides the base version,
3071 * providing information about
3072 * the activity performing the launch. Because of this additional
3073 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3074 * required; if not specified, the new activity will be added to the
3075 * task of the caller.
3076 *
3077 * <p>This method throws {@link android.content.ActivityNotFoundException}
3078 * if there was no Activity found to run the given Intent.
3079 *
3080 * @param intent The intent to start.
3081 *
3082 * @throws android.content.ActivityNotFoundException
3083 *
3084 * @see #startActivityForResult
3085 */
3086 @Override
3087 public void startActivity(Intent intent) {
3088 startActivityForResult(intent, -1);
3089 }
3090
3091 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003092 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003093 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003094 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003095 * for more information.
3096 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003097 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003098 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003099 * intent parameter to {@link IntentSender#sendIntent}.
3100 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003101 * would like to change.
3102 * @param flagsValues Desired values for any bits set in
3103 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003104 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003105 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003106 public void startIntentSender(IntentSender intent,
3107 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3108 throws IntentSender.SendIntentException {
3109 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3110 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003111 }
3112
3113 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 * A special variation to launch an activity only if a new activity
3115 * instance is needed to handle the given Intent. In other words, this is
3116 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3117 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3118 * singleTask or singleTop
3119 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3120 * and the activity
3121 * that handles <var>intent</var> is the same as your currently running
3122 * activity, then a new instance is not needed. In this case, instead of
3123 * the normal behavior of calling {@link #onNewIntent} this function will
3124 * return and you can handle the Intent yourself.
3125 *
3126 * <p>This function can only be called from a top-level activity; if it is
3127 * called from a child activity, a runtime exception will be thrown.
3128 *
3129 * @param intent The intent to start.
3130 * @param requestCode If >= 0, this code will be returned in
3131 * onActivityResult() when the activity exits, as described in
3132 * {@link #startActivityForResult}.
3133 *
3134 * @return If a new activity was launched then true is returned; otherwise
3135 * false is returned and you must handle the Intent yourself.
3136 *
3137 * @see #startActivity
3138 * @see #startActivityForResult
3139 */
3140 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3141 if (mParent == null) {
3142 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3143 try {
3144 result = ActivityManagerNative.getDefault()
3145 .startActivity(mMainThread.getApplicationThread(),
3146 intent, intent.resolveTypeIfNeeded(
3147 getContentResolver()),
3148 null, 0,
3149 mToken, mEmbeddedID, requestCode, true, false);
3150 } catch (RemoteException e) {
3151 // Empty
3152 }
3153
3154 Instrumentation.checkStartActivityResult(result, intent);
3155
3156 if (requestCode >= 0) {
3157 // If this start is requesting a result, we can avoid making
3158 // the activity visible until the result is received. Setting
3159 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3160 // activity hidden during this time, to avoid flickering.
3161 // This can only be done when a result is requested because
3162 // that guarantees we will get information back when the
3163 // activity is finished, no matter what happens to it.
3164 mStartedActivity = true;
3165 }
3166 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3167 }
3168
3169 throw new UnsupportedOperationException(
3170 "startActivityIfNeeded can only be called from a top-level activity");
3171 }
3172
3173 /**
3174 * Special version of starting an activity, for use when you are replacing
3175 * other activity components. You can use this to hand the Intent off
3176 * to the next Activity that can handle it. You typically call this in
3177 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3178 *
3179 * @param intent The intent to dispatch to the next activity. For
3180 * correct behavior, this must be the same as the Intent that started
3181 * your own activity; the only changes you can make are to the extras
3182 * inside of it.
3183 *
3184 * @return Returns a boolean indicating whether there was another Activity
3185 * to start: true if there was a next activity to start, false if there
3186 * wasn't. In general, if true is returned you will then want to call
3187 * finish() on yourself.
3188 */
3189 public boolean startNextMatchingActivity(Intent intent) {
3190 if (mParent == null) {
3191 try {
3192 return ActivityManagerNative.getDefault()
3193 .startNextMatchingActivity(mToken, intent);
3194 } catch (RemoteException e) {
3195 // Empty
3196 }
3197 return false;
3198 }
3199
3200 throw new UnsupportedOperationException(
3201 "startNextMatchingActivity can only be called from a top-level activity");
3202 }
3203
3204 /**
3205 * This is called when a child activity of this one calls its
3206 * {@link #startActivity} or {@link #startActivityForResult} method.
3207 *
3208 * <p>This method throws {@link android.content.ActivityNotFoundException}
3209 * if there was no Activity found to run the given Intent.
3210 *
3211 * @param child The activity making the call.
3212 * @param intent The intent to start.
3213 * @param requestCode Reply request code. < 0 if reply is not requested.
3214 *
3215 * @throws android.content.ActivityNotFoundException
3216 *
3217 * @see #startActivity
3218 * @see #startActivityForResult
3219 */
3220 public void startActivityFromChild(Activity child, Intent intent,
3221 int requestCode) {
3222 Instrumentation.ActivityResult ar =
3223 mInstrumentation.execStartActivity(
3224 this, mMainThread.getApplicationThread(), mToken, child,
3225 intent, requestCode);
3226 if (ar != null) {
3227 mMainThread.sendActivityResult(
3228 mToken, child.mEmbeddedID, requestCode,
3229 ar.getResultCode(), ar.getResultData());
3230 }
3231 }
3232
3233 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003234 * This is called when a Fragment in this activity calls its
3235 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3236 * method.
3237 *
3238 * <p>This method throws {@link android.content.ActivityNotFoundException}
3239 * if there was no Activity found to run the given Intent.
3240 *
3241 * @param fragment The fragment making the call.
3242 * @param intent The intent to start.
3243 * @param requestCode Reply request code. < 0 if reply is not requested.
3244 *
3245 * @throws android.content.ActivityNotFoundException
3246 *
3247 * @see Fragment#startActivity
3248 * @see Fragment#startActivityForResult
3249 */
3250 public void startActivityFromFragment(Fragment fragment, Intent intent,
3251 int requestCode) {
3252 Instrumentation.ActivityResult ar =
3253 mInstrumentation.execStartActivity(
3254 this, mMainThread.getApplicationThread(), mToken, fragment,
3255 intent, requestCode);
3256 if (ar != null) {
3257 mMainThread.sendActivityResult(
3258 mToken, fragment.mWho, requestCode,
3259 ar.getResultCode(), ar.getResultData());
3260 }
3261 }
3262
3263 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003264 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003265 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003266 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003267 * for more information.
3268 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003269 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3270 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3271 int extraFlags)
3272 throws IntentSender.SendIntentException {
3273 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003274 flagsMask, flagsValues, child);
3275 }
3276
3277 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003278 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3279 * or {@link #finish} to specify an explicit transition animation to
3280 * perform next.
3281 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003282 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003283 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003284 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003285 */
3286 public void overridePendingTransition(int enterAnim, int exitAnim) {
3287 try {
3288 ActivityManagerNative.getDefault().overridePendingTransition(
3289 mToken, getPackageName(), enterAnim, exitAnim);
3290 } catch (RemoteException e) {
3291 }
3292 }
3293
3294 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 * Call this to set the result that your activity will return to its
3296 * caller.
3297 *
3298 * @param resultCode The result code to propagate back to the originating
3299 * activity, often RESULT_CANCELED or RESULT_OK
3300 *
3301 * @see #RESULT_CANCELED
3302 * @see #RESULT_OK
3303 * @see #RESULT_FIRST_USER
3304 * @see #setResult(int, Intent)
3305 */
3306 public final void setResult(int resultCode) {
3307 synchronized (this) {
3308 mResultCode = resultCode;
3309 mResultData = null;
3310 }
3311 }
3312
3313 /**
3314 * Call this to set the result that your activity will return to its
3315 * caller.
3316 *
3317 * @param resultCode The result code to propagate back to the originating
3318 * activity, often RESULT_CANCELED or RESULT_OK
3319 * @param data The data to propagate back to the originating activity.
3320 *
3321 * @see #RESULT_CANCELED
3322 * @see #RESULT_OK
3323 * @see #RESULT_FIRST_USER
3324 * @see #setResult(int)
3325 */
3326 public final void setResult(int resultCode, Intent data) {
3327 synchronized (this) {
3328 mResultCode = resultCode;
3329 mResultData = data;
3330 }
3331 }
3332
3333 /**
3334 * Return the name of the package that invoked this activity. This is who
3335 * the data in {@link #setResult setResult()} will be sent to. You can
3336 * use this information to validate that the recipient is allowed to
3337 * receive the data.
3338 *
3339 * <p>Note: if the calling activity is not expecting a result (that is it
3340 * did not use the {@link #startActivityForResult}
3341 * form that includes a request code), then the calling package will be
3342 * null.
3343 *
3344 * @return The package of the activity that will receive your
3345 * reply, or null if none.
3346 */
3347 public String getCallingPackage() {
3348 try {
3349 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3350 } catch (RemoteException e) {
3351 return null;
3352 }
3353 }
3354
3355 /**
3356 * Return the name of the activity that invoked this activity. This is
3357 * who the data in {@link #setResult setResult()} will be sent to. You
3358 * can use this information to validate that the recipient is allowed to
3359 * receive the data.
3360 *
3361 * <p>Note: if the calling activity is not expecting a result (that is it
3362 * did not use the {@link #startActivityForResult}
3363 * form that includes a request code), then the calling package will be
3364 * null.
3365 *
3366 * @return String The full name of the activity that will receive your
3367 * reply, or null if none.
3368 */
3369 public ComponentName getCallingActivity() {
3370 try {
3371 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3372 } catch (RemoteException e) {
3373 return null;
3374 }
3375 }
3376
3377 /**
3378 * Control whether this activity's main window is visible. This is intended
3379 * only for the special case of an activity that is not going to show a
3380 * UI itself, but can't just finish prior to onResume() because it needs
3381 * to wait for a service binding or such. Setting this to false allows
3382 * you to prevent your UI from being shown during that time.
3383 *
3384 * <p>The default value for this is taken from the
3385 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3386 */
3387 public void setVisible(boolean visible) {
3388 if (mVisibleFromClient != visible) {
3389 mVisibleFromClient = visible;
3390 if (mVisibleFromServer) {
3391 if (visible) makeVisible();
3392 else mDecor.setVisibility(View.INVISIBLE);
3393 }
3394 }
3395 }
3396
3397 void makeVisible() {
3398 if (!mWindowAdded) {
3399 ViewManager wm = getWindowManager();
3400 wm.addView(mDecor, getWindow().getAttributes());
3401 mWindowAdded = true;
3402 }
3403 mDecor.setVisibility(View.VISIBLE);
3404 }
3405
3406 /**
3407 * Check to see whether this activity is in the process of finishing,
3408 * either because you called {@link #finish} on it or someone else
3409 * has requested that it finished. This is often used in
3410 * {@link #onPause} to determine whether the activity is simply pausing or
3411 * completely finishing.
3412 *
3413 * @return If the activity is finishing, returns true; else returns false.
3414 *
3415 * @see #finish
3416 */
3417 public boolean isFinishing() {
3418 return mFinished;
3419 }
3420
3421 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003422 * Check to see whether this activity is in the process of being destroyed in order to be
3423 * recreated with a new configuration. This is often used in
3424 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3425 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3426 *
3427 * @return If the activity is being torn down in order to be recreated with a new configuration,
3428 * returns true; else returns false.
3429 */
3430 public boolean isChangingConfigurations() {
3431 return mChangingConfigurations;
3432 }
3433
3434 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 * Call this when your activity is done and should be closed. The
3436 * ActivityResult is propagated back to whoever launched you via
3437 * onActivityResult().
3438 */
3439 public void finish() {
3440 if (mParent == null) {
3441 int resultCode;
3442 Intent resultData;
3443 synchronized (this) {
3444 resultCode = mResultCode;
3445 resultData = mResultData;
3446 }
3447 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3448 try {
3449 if (ActivityManagerNative.getDefault()
3450 .finishActivity(mToken, resultCode, resultData)) {
3451 mFinished = true;
3452 }
3453 } catch (RemoteException e) {
3454 // Empty
3455 }
3456 } else {
3457 mParent.finishFromChild(this);
3458 }
3459 }
3460
3461 /**
3462 * This is called when a child activity of this one calls its
3463 * {@link #finish} method. The default implementation simply calls
3464 * finish() on this activity (the parent), finishing the entire group.
3465 *
3466 * @param child The activity making the call.
3467 *
3468 * @see #finish
3469 */
3470 public void finishFromChild(Activity child) {
3471 finish();
3472 }
3473
3474 /**
3475 * Force finish another activity that you had previously started with
3476 * {@link #startActivityForResult}.
3477 *
3478 * @param requestCode The request code of the activity that you had
3479 * given to startActivityForResult(). If there are multiple
3480 * activities started with this request code, they
3481 * will all be finished.
3482 */
3483 public void finishActivity(int requestCode) {
3484 if (mParent == null) {
3485 try {
3486 ActivityManagerNative.getDefault()
3487 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3488 } catch (RemoteException e) {
3489 // Empty
3490 }
3491 } else {
3492 mParent.finishActivityFromChild(this, requestCode);
3493 }
3494 }
3495
3496 /**
3497 * This is called when a child activity of this one calls its
3498 * finishActivity().
3499 *
3500 * @param child The activity making the call.
3501 * @param requestCode Request code that had been used to start the
3502 * activity.
3503 */
3504 public void finishActivityFromChild(Activity child, int requestCode) {
3505 try {
3506 ActivityManagerNative.getDefault()
3507 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3508 } catch (RemoteException e) {
3509 // Empty
3510 }
3511 }
3512
3513 /**
3514 * Called when an activity you launched exits, giving you the requestCode
3515 * you started it with, the resultCode it returned, and any additional
3516 * data from it. The <var>resultCode</var> will be
3517 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3518 * didn't return any result, or crashed during its operation.
3519 *
3520 * <p>You will receive this call immediately before onResume() when your
3521 * activity is re-starting.
3522 *
3523 * @param requestCode The integer request code originally supplied to
3524 * startActivityForResult(), allowing you to identify who this
3525 * result came from.
3526 * @param resultCode The integer result code returned by the child activity
3527 * through its setResult().
3528 * @param data An Intent, which can return result data to the caller
3529 * (various data can be attached to Intent "extras").
3530 *
3531 * @see #startActivityForResult
3532 * @see #createPendingResult
3533 * @see #setResult(int)
3534 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003535 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 }
3537
3538 /**
3539 * Create a new PendingIntent object which you can hand to others
3540 * for them to use to send result data back to your
3541 * {@link #onActivityResult} callback. The created object will be either
3542 * one-shot (becoming invalid after a result is sent back) or multiple
3543 * (allowing any number of results to be sent through it).
3544 *
3545 * @param requestCode Private request code for the sender that will be
3546 * associated with the result data when it is returned. The sender can not
3547 * modify this value, allowing you to identify incoming results.
3548 * @param data Default data to supply in the result, which may be modified
3549 * by the sender.
3550 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3551 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3552 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3553 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3554 * or any of the flags as supported by
3555 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3556 * of the intent that can be supplied when the actual send happens.
3557 *
3558 * @return Returns an existing or new PendingIntent matching the given
3559 * parameters. May return null only if
3560 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3561 * supplied.
3562 *
3563 * @see PendingIntent
3564 */
3565 public PendingIntent createPendingResult(int requestCode, Intent data,
3566 int flags) {
3567 String packageName = getPackageName();
3568 try {
3569 IIntentSender target =
3570 ActivityManagerNative.getDefault().getIntentSender(
3571 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3572 mParent == null ? mToken : mParent.mToken,
3573 mEmbeddedID, requestCode, data, null, flags);
3574 return target != null ? new PendingIntent(target) : null;
3575 } catch (RemoteException e) {
3576 // Empty
3577 }
3578 return null;
3579 }
3580
3581 /**
3582 * Change the desired orientation of this activity. If the activity
3583 * is currently in the foreground or otherwise impacting the screen
3584 * orientation, the screen will immediately be changed (possibly causing
3585 * the activity to be restarted). Otherwise, this will be used the next
3586 * time the activity is visible.
3587 *
3588 * @param requestedOrientation An orientation constant as used in
3589 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3590 */
3591 public void setRequestedOrientation(int requestedOrientation) {
3592 if (mParent == null) {
3593 try {
3594 ActivityManagerNative.getDefault().setRequestedOrientation(
3595 mToken, requestedOrientation);
3596 } catch (RemoteException e) {
3597 // Empty
3598 }
3599 } else {
3600 mParent.setRequestedOrientation(requestedOrientation);
3601 }
3602 }
3603
3604 /**
3605 * Return the current requested orientation of the activity. This will
3606 * either be the orientation requested in its component's manifest, or
3607 * the last requested orientation given to
3608 * {@link #setRequestedOrientation(int)}.
3609 *
3610 * @return Returns an orientation constant as used in
3611 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3612 */
3613 public int getRequestedOrientation() {
3614 if (mParent == null) {
3615 try {
3616 return ActivityManagerNative.getDefault()
3617 .getRequestedOrientation(mToken);
3618 } catch (RemoteException e) {
3619 // Empty
3620 }
3621 } else {
3622 return mParent.getRequestedOrientation();
3623 }
3624 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3625 }
3626
3627 /**
3628 * Return the identifier of the task this activity is in. This identifier
3629 * will remain the same for the lifetime of the activity.
3630 *
3631 * @return Task identifier, an opaque integer.
3632 */
3633 public int getTaskId() {
3634 try {
3635 return ActivityManagerNative.getDefault()
3636 .getTaskForActivity(mToken, false);
3637 } catch (RemoteException e) {
3638 return -1;
3639 }
3640 }
3641
3642 /**
3643 * Return whether this activity is the root of a task. The root is the
3644 * first activity in a task.
3645 *
3646 * @return True if this is the root activity, else false.
3647 */
3648 public boolean isTaskRoot() {
3649 try {
3650 return ActivityManagerNative.getDefault()
3651 .getTaskForActivity(mToken, true) >= 0;
3652 } catch (RemoteException e) {
3653 return false;
3654 }
3655 }
3656
3657 /**
3658 * Move the task containing this activity to the back of the activity
3659 * stack. The activity's order within the task is unchanged.
3660 *
3661 * @param nonRoot If false then this only works if the activity is the root
3662 * of a task; if true it will work for any activity in
3663 * a task.
3664 *
3665 * @return If the task was moved (or it was already at the
3666 * back) true is returned, else false.
3667 */
3668 public boolean moveTaskToBack(boolean nonRoot) {
3669 try {
3670 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3671 mToken, nonRoot);
3672 } catch (RemoteException e) {
3673 // Empty
3674 }
3675 return false;
3676 }
3677
3678 /**
3679 * Returns class name for this activity with the package prefix removed.
3680 * This is the default name used to read and write settings.
3681 *
3682 * @return The local class name.
3683 */
3684 public String getLocalClassName() {
3685 final String pkg = getPackageName();
3686 final String cls = mComponent.getClassName();
3687 int packageLen = pkg.length();
3688 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3689 || cls.charAt(packageLen) != '.') {
3690 return cls;
3691 }
3692 return cls.substring(packageLen+1);
3693 }
3694
3695 /**
3696 * Returns complete component name of this activity.
3697 *
3698 * @return Returns the complete component name for this activity
3699 */
3700 public ComponentName getComponentName()
3701 {
3702 return mComponent;
3703 }
3704
3705 /**
3706 * Retrieve a {@link SharedPreferences} object for accessing preferences
3707 * that are private to this activity. This simply calls the underlying
3708 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3709 * class name as the preferences name.
3710 *
3711 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3712 * operation, {@link #MODE_WORLD_READABLE} and
3713 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3714 *
3715 * @return Returns the single SharedPreferences instance that can be used
3716 * to retrieve and modify the preference values.
3717 */
3718 public SharedPreferences getPreferences(int mode) {
3719 return getSharedPreferences(getLocalClassName(), mode);
3720 }
3721
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003722 private void ensureSearchManager() {
3723 if (mSearchManager != null) {
3724 return;
3725 }
3726
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003727 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003728 }
3729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 @Override
3731 public Object getSystemService(String name) {
3732 if (getBaseContext() == null) {
3733 throw new IllegalStateException(
3734 "System services not available to Activities before onCreate()");
3735 }
3736
3737 if (WINDOW_SERVICE.equals(name)) {
3738 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003739 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003740 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003741 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 }
3743 return super.getSystemService(name);
3744 }
3745
3746 /**
3747 * Change the title associated with this activity. If this is a
3748 * top-level activity, the title for its window will change. If it
3749 * is an embedded activity, the parent can do whatever it wants
3750 * with it.
3751 */
3752 public void setTitle(CharSequence title) {
3753 mTitle = title;
3754 onTitleChanged(title, mTitleColor);
3755
3756 if (mParent != null) {
3757 mParent.onChildTitleChanged(this, title);
3758 }
3759 }
3760
3761 /**
3762 * Change the title associated with this activity. If this is a
3763 * top-level activity, the title for its window will change. If it
3764 * is an embedded activity, the parent can do whatever it wants
3765 * with it.
3766 */
3767 public void setTitle(int titleId) {
3768 setTitle(getText(titleId));
3769 }
3770
3771 public void setTitleColor(int textColor) {
3772 mTitleColor = textColor;
3773 onTitleChanged(mTitle, textColor);
3774 }
3775
3776 public final CharSequence getTitle() {
3777 return mTitle;
3778 }
3779
3780 public final int getTitleColor() {
3781 return mTitleColor;
3782 }
3783
3784 protected void onTitleChanged(CharSequence title, int color) {
3785 if (mTitleReady) {
3786 final Window win = getWindow();
3787 if (win != null) {
3788 win.setTitle(title);
3789 if (color != 0) {
3790 win.setTitleColor(color);
3791 }
3792 }
3793 }
3794 }
3795
3796 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3797 }
3798
3799 /**
3800 * Sets the visibility of the progress bar in the title.
3801 * <p>
3802 * In order for the progress bar to be shown, the feature must be requested
3803 * via {@link #requestWindowFeature(int)}.
3804 *
3805 * @param visible Whether to show the progress bars in the title.
3806 */
3807 public final void setProgressBarVisibility(boolean visible) {
3808 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3809 Window.PROGRESS_VISIBILITY_OFF);
3810 }
3811
3812 /**
3813 * Sets the visibility of the indeterminate progress bar in the title.
3814 * <p>
3815 * In order for the progress bar to be shown, the feature must be requested
3816 * via {@link #requestWindowFeature(int)}.
3817 *
3818 * @param visible Whether to show the progress bars in the title.
3819 */
3820 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3821 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3822 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3823 }
3824
3825 /**
3826 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3827 * is always indeterminate).
3828 * <p>
3829 * In order for the progress bar to be shown, the feature must be requested
3830 * via {@link #requestWindowFeature(int)}.
3831 *
3832 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3833 */
3834 public final void setProgressBarIndeterminate(boolean indeterminate) {
3835 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3836 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3837 }
3838
3839 /**
3840 * Sets the progress for the progress bars in the title.
3841 * <p>
3842 * In order for the progress bar to be shown, the feature must be requested
3843 * via {@link #requestWindowFeature(int)}.
3844 *
3845 * @param progress The progress for the progress bar. Valid ranges are from
3846 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3847 * bar will be completely filled and will fade out.
3848 */
3849 public final void setProgress(int progress) {
3850 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3851 }
3852
3853 /**
3854 * Sets the secondary progress for the progress bar in the title. This
3855 * progress is drawn between the primary progress (set via
3856 * {@link #setProgress(int)} and the background. It can be ideal for media
3857 * scenarios such as showing the buffering progress while the default
3858 * progress shows the play progress.
3859 * <p>
3860 * In order for the progress bar to be shown, the feature must be requested
3861 * via {@link #requestWindowFeature(int)}.
3862 *
3863 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3864 * 0 to 10000 (both inclusive).
3865 */
3866 public final void setSecondaryProgress(int secondaryProgress) {
3867 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3868 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3869 }
3870
3871 /**
3872 * Suggests an audio stream whose volume should be changed by the hardware
3873 * volume controls.
3874 * <p>
3875 * The suggested audio stream will be tied to the window of this Activity.
3876 * If the Activity is switched, the stream set here is no longer the
3877 * suggested stream. The client does not need to save and restore the old
3878 * suggested stream value in onPause and onResume.
3879 *
3880 * @param streamType The type of the audio stream whose volume should be
3881 * changed by the hardware volume controls. It is not guaranteed that
3882 * the hardware volume controls will always change this stream's
3883 * volume (for example, if a call is in progress, its stream's volume
3884 * may be changed instead). To reset back to the default, use
3885 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3886 */
3887 public final void setVolumeControlStream(int streamType) {
3888 getWindow().setVolumeControlStream(streamType);
3889 }
3890
3891 /**
3892 * Gets the suggested audio stream whose volume should be changed by the
3893 * harwdare volume controls.
3894 *
3895 * @return The suggested audio stream type whose volume should be changed by
3896 * the hardware volume controls.
3897 * @see #setVolumeControlStream(int)
3898 */
3899 public final int getVolumeControlStream() {
3900 return getWindow().getVolumeControlStream();
3901 }
3902
3903 /**
3904 * Runs the specified action on the UI thread. If the current thread is the UI
3905 * thread, then the action is executed immediately. If the current thread is
3906 * not the UI thread, the action is posted to the event queue of the UI thread.
3907 *
3908 * @param action the action to run on the UI thread
3909 */
3910 public final void runOnUiThread(Runnable action) {
3911 if (Thread.currentThread() != mUiThread) {
3912 mHandler.post(action);
3913 } else {
3914 action.run();
3915 }
3916 }
3917
3918 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003919 * Standard implementation of
3920 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
3921 * inflating with the LayoutInflater returned by {@link #getSystemService}.
3922 * This implementation handles <fragment> tags to embed fragments inside
3923 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 *
3925 * @see android.view.LayoutInflater#createView
3926 * @see android.view.Window#getLayoutInflater
3927 */
3928 public View onCreateView(String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003929 if (!"fragment".equals(name)) {
3930 return null;
3931 }
3932
3933 TypedArray a =
3934 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
3935 String fname = a.getString(com.android.internal.R.styleable.Fragment_name);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003936 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, 0);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003937 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
3938 a.recycle();
3939
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003940 if (id == 0) {
3941 throw new IllegalArgumentException(attrs.getPositionDescription()
3942 + ": Must specify unique android:id for " + fname);
3943 }
3944
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003945 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003946 // If we restored from a previous state, we may already have
3947 // instantiated this fragment from the state and should use
3948 // that instance instead of making a new one.
3949 Fragment fragment = mFragments.findFragmentById(id);
Dianne Hackborn5ae74d62010-05-19 19:14:57 -07003950 if (FragmentManager.DEBUG) Log.v(TAG, "onCreateView: id=0x"
3951 + Integer.toHexString(id) + " fname=" + fname
3952 + " existing=" + fragment);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003953 if (fragment == null) {
3954 fragment = Fragment.instantiate(this, fname);
3955 fragment.mFromLayout = true;
3956 fragment.mFragmentId = id;
3957 fragment.mTag = tag;
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07003958 fragment.mImmediateActivity = this;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003959 mFragments.addFragment(fragment, true);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003960 }
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003961 // If this fragment is newly instantiated (either right now, or
3962 // from last saved state), then give it the attributes to
3963 // initialize itself.
3964 if (!fragment.mRetaining) {
3965 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
3966 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003967 if (fragment.mView == null) {
3968 throw new IllegalStateException("Fragment " + fname
3969 + " did not create a view.");
3970 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003971 fragment.mView.setId(id);
3972 if (fragment.mView.getTag() == null) {
3973 fragment.mView.setTag(tag);
3974 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003975 return fragment.mView;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003976 } catch (Exception e) {
3977 InflateException ie = new InflateException(attrs.getPositionDescription()
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003978 + ": Error inflating fragment " + fname);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003979 ie.initCause(e);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003980 throw ie;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 }
3983
Daniel Sandler69a48172010-06-23 16:29:36 -04003984 /**
3985 * Bit indicating that this activity is "immersive" and should not be
3986 * interrupted by notifications if possible.
3987 *
3988 * This value is initially set by the manifest property
3989 * <code>android:immersive</code> but may be changed at runtime by
3990 * {@link #setImmersive}.
3991 *
3992 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
3993 */
3994 public boolean isImmersive() {
3995 try {
3996 return ActivityManagerNative.getDefault().isImmersive(mToken);
3997 } catch (RemoteException e) {
3998 return false;
3999 }
4000 }
4001
4002 /**
4003 * Adjust the current immersive mode setting.
4004 *
4005 * Note that changing this value will have no effect on the activity's
4006 * {@link android.content.pm.ActivityInfo} structure; that is, if
4007 * <code>android:immersive</code> is set to <code>true</code>
4008 * in the application's manifest entry for this activity, the {@link
4009 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4010 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4011 * FLAG_IMMERSIVE} bit set.
4012 *
4013 * @see #isImmersive
4014 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4015 */
4016 public void setImmersive(boolean i) {
4017 try {
4018 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4019 } catch (RemoteException e) {
4020 // pass
4021 }
4022 }
4023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 // ------------------ Internal API ------------------
4025
4026 final void setParent(Activity parent) {
4027 mParent = parent;
4028 }
4029
4030 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4031 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004032 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004034 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004035 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 }
4037
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004038 final void attach(Context context, ActivityThread aThread,
4039 Instrumentation instr, IBinder token, int ident,
4040 Application application, Intent intent, ActivityInfo info,
4041 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004042 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004043 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 attachBaseContext(context);
4045
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004046 mFragments.attachActivity(this);
4047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 mWindow = PolicyManager.makeNewWindow(this);
4049 mWindow.setCallback(this);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004050 mWindow.getLayoutInflater().setFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4052 mWindow.setSoftInputMode(info.softInputMode);
4053 }
4054 mUiThread = Thread.currentThread();
4055
4056 mMainThread = aThread;
4057 mInstrumentation = instr;
4058 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004059 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 mApplication = application;
4061 mIntent = intent;
4062 mComponent = intent.getComponent();
4063 mActivityInfo = info;
4064 mTitle = title;
4065 mParent = parent;
4066 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004067 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068
4069 mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
4070 if (mParent != null) {
4071 mWindow.setContainer(mParent.getWindow());
4072 }
4073 mWindowManager = mWindow.getWindowManager();
4074 mCurrentConfig = config;
4075 }
4076
4077 final IBinder getActivityToken() {
4078 return mParent != null ? mParent.getActivityToken() : mToken;
4079 }
4080
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004081 final void performCreate(Bundle icicle) {
4082 onCreate(icicle);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004083 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004084 }
4085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 final void performStart() {
4087 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004088 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 mInstrumentation.callActivityOnStart(this);
4090 if (!mCalled) {
4091 throw new SuperNotCalledException(
4092 "Activity " + mComponent.toShortString() +
4093 " did not call through to super.onStart()");
4094 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004095 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004096 if (mAllLoaderManagers != null) {
4097 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4098 mAllLoaderManagers.valueAt(i).finishRetain();
4099 }
4100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102
4103 final void performRestart() {
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004104 synchronized (mManagedCursors) {
4105 final int N = mManagedCursors.size();
4106 for (int i=0; i<N; i++) {
4107 ManagedCursor mc = mManagedCursors.get(i);
4108 if (mc.mReleased || mc.mUpdated) {
4109 mc.mCursor.requery();
4110 mc.mReleased = false;
4111 mc.mUpdated = false;
4112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115
4116 if (mStopped) {
4117 mStopped = false;
4118 mCalled = false;
4119 mInstrumentation.callActivityOnRestart(this);
4120 if (!mCalled) {
4121 throw new SuperNotCalledException(
4122 "Activity " + mComponent.toShortString() +
4123 " did not call through to super.onRestart()");
4124 }
4125 performStart();
4126 }
4127 }
4128
4129 final void performResume() {
4130 performRestart();
4131
Dianne Hackborn445646c2010-06-25 15:52:59 -07004132 mFragments.execPendingActions();
4133
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004134 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135
4136 // First call onResume() -before- setting mResumed, so we don't
4137 // send out any status bar / menu notifications the client makes.
4138 mCalled = false;
4139 mInstrumentation.callActivityOnResume(this);
4140 if (!mCalled) {
4141 throw new SuperNotCalledException(
4142 "Activity " + mComponent.toShortString() +
4143 " did not call through to super.onResume()");
4144 }
4145
4146 // Now really resume, and install the current status bar and menu.
4147 mResumed = true;
4148 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004149
4150 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004151 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 onPostResume();
4154 if (!mCalled) {
4155 throw new SuperNotCalledException(
4156 "Activity " + mComponent.toShortString() +
4157 " did not call through to super.onPostResume()");
4158 }
4159 }
4160
4161 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004162 mFragments.dispatchPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 onPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 }
4165
4166 final void performUserLeaving() {
4167 onUserInteraction();
4168 onUserLeaveHint();
4169 }
4170
4171 final void performStop() {
Dianne Hackborn2707d602010-07-09 18:01:20 -07004172 if (mStarted) {
4173 mStarted = false;
4174 if (mLoaderManager != null) {
4175 if (!mChangingConfigurations) {
4176 mLoaderManager.doStop();
4177 } else {
4178 mLoaderManager.doRetain();
4179 }
4180 }
4181 }
4182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 if (!mStopped) {
4184 if (mWindow != null) {
4185 mWindow.closeAllPanels();
4186 }
4187
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004188 mFragments.dispatchStop();
4189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 mCalled = false;
4191 mInstrumentation.callActivityOnStop(this);
4192 if (!mCalled) {
4193 throw new SuperNotCalledException(
4194 "Activity " + mComponent.toShortString() +
4195 " did not call through to super.onStop()");
4196 }
4197
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004198 synchronized (mManagedCursors) {
4199 final int N = mManagedCursors.size();
4200 for (int i=0; i<N; i++) {
4201 ManagedCursor mc = mManagedCursors.get(i);
4202 if (!mc.mReleased) {
4203 mc.mCursor.deactivate();
4204 mc.mReleased = true;
4205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 }
4207 }
4208
4209 mStopped = true;
4210 }
4211 mResumed = false;
4212 }
4213
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004214 final void performDestroy() {
4215 mFragments.dispatchDestroy();
4216 onDestroy();
4217 }
4218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 final boolean isResumed() {
4220 return mResumed;
4221 }
4222
4223 void dispatchActivityResult(String who, int requestCode,
4224 int resultCode, Intent data) {
4225 if (Config.LOGV) Log.v(
4226 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4227 + ", resCode=" + resultCode + ", data=" + data);
4228 if (who == null) {
4229 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004230 } else {
4231 Fragment frag = mFragments.findFragmentByWho(who);
4232 if (frag != null) {
4233 frag.onActivityResult(requestCode, resultCode, data);
4234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 }
4236 }
4237}