blob: 61fd5f3690a32d3e043a40cb95cc619974b677e7 [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 Powell6e346362010-07-23 10:18:23 -070019import com.android.internal.app.ActionBarImpl;
20import com.android.internal.policy.PolicyManager;
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;
Adam Powell6e346362010-07-23 10:18:23 -070055import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070057import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.ContextThemeWrapper;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070059import android.view.InflateException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.KeyEvent;
61import android.view.LayoutInflater;
62import android.view.Menu;
63import android.view.MenuInflater;
64import android.view.MenuItem;
65import android.view.MotionEvent;
66import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -070067import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070069import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.ViewManager;
71import android.view.Window;
72import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070073import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.widget.AdapterView;
Jim Miller0b2a6d02010-07-13 18:01:29 -070075import android.widget.FrameLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
Adam Powell6e346362010-07-23 10:18:23 -070077import java.util.ArrayList;
78import java.util.HashMap;
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 Hackborn4911b782010-07-15 12:54:39 -0700653 SparseArray<LoaderManagerImpl> 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 Powellac695c62010-07-20 18:19:27 -0700664 /*package*/ ActionBarImpl 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 Hackborn4911b782010-07-15 12:54:39 -0700671 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
672 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700673
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 }
Ben Komalo7cd83422010-07-22 17:50:45 -0700777 mLoaderManager = getLoaderManager(-1, mStarted);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700778 return mLoaderManager;
779 }
780
Dianne Hackborn4911b782010-07-15 12:54:39 -0700781 LoaderManagerImpl getLoaderManager(int index, boolean started) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700782 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700783 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700784 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700785 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700786 if (lm == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700787 lm = new LoaderManagerImpl(started);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700788 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) {
Jim Miller0b2a6d02010-07-13 18:01:29 -07001273 if (mDecor == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 return false;
1275 }
1276
Jim Miller0b2a6d02010-07-13 18:01:29 -07001277 int paddingLeft = 0;
1278 int paddingRight = 0;
1279 int paddingTop = 0;
1280 int paddingBottom = 0;
1281
1282 // Find System window and use padding so we ignore space reserved for decorations
1283 // like the status bar and such.
1284 final FrameLayout top = (FrameLayout) mDecor;
1285 for (int i = 0; i < top.getChildCount(); i++) {
1286 View child = top.getChildAt(i);
1287 if (child.isFitsSystemWindowsFlagSet()) {
1288 paddingLeft = child.getPaddingLeft();
1289 paddingRight = child.getPaddingRight();
1290 paddingTop = child.getPaddingTop();
1291 paddingBottom = child.getPaddingBottom();
1292 break;
1293 }
1294 }
1295
1296 final int visibleWidth = mDecor.getWidth() - paddingLeft - paddingRight;
1297 final int visibleHeight = mDecor.getHeight() - paddingTop - paddingBottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298
1299 canvas.save();
Jim Miller0b2a6d02010-07-13 18:01:29 -07001300 canvas.scale( (float) outBitmap.getWidth() / visibleWidth,
1301 (float) outBitmap.getHeight() / visibleHeight);
1302 canvas.translate(-paddingLeft, -paddingTop);
1303 mDecor.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 canvas.restore();
1305
1306 return true;
1307 }
1308
1309 /**
1310 * Generate a new description for this activity. This method is called
1311 * before pausing the activity and can, if desired, return some textual
1312 * description of its current state to be displayed to the user.
1313 *
1314 * <p>The default implementation returns null, which will cause you to
1315 * inherit the description from the previous activity. If all activities
1316 * return null, generally the label of the top activity will be used as the
1317 * description.
1318 *
1319 * @return A description of what the user is doing. It should be short and
1320 * sweet (only a few words).
1321 *
1322 * @see #onCreateThumbnail
1323 * @see #onSaveInstanceState
1324 * @see #onPause
1325 */
1326 public CharSequence onCreateDescription() {
1327 return null;
1328 }
1329
1330 /**
1331 * Called when you are no longer visible to the user. You will next
1332 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1333 * depending on later user activity.
1334 *
1335 * <p>Note that this method may never be called, in low memory situations
1336 * where the system does not have enough memory to keep your activity's
1337 * process running after its {@link #onPause} method is called.
1338 *
1339 * <p><em>Derived classes must call through to the super class's
1340 * implementation of this method. If they do not, an exception will be
1341 * thrown.</em></p>
1342 *
1343 * @see #onRestart
1344 * @see #onResume
1345 * @see #onSaveInstanceState
1346 * @see #onDestroy
1347 */
1348 protected void onStop() {
1349 mCalled = true;
1350 }
1351
1352 /**
1353 * Perform any final cleanup before an activity is destroyed. This can
1354 * happen either because the activity is finishing (someone called
1355 * {@link #finish} on it, or because the system is temporarily destroying
1356 * this instance of the activity to save space. You can distinguish
1357 * between these two scenarios with the {@link #isFinishing} method.
1358 *
1359 * <p><em>Note: do not count on this method being called as a place for
1360 * saving data! For example, if an activity is editing data in a content
1361 * provider, those edits should be committed in either {@link #onPause} or
1362 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1363 * free resources like threads that are associated with an activity, so
1364 * that a destroyed activity does not leave such things around while the
1365 * rest of its application is still running. There are situations where
1366 * the system will simply kill the activity's hosting process without
1367 * calling this method (or any others) in it, so it should not be used to
1368 * do things that are intended to remain around after the process goes
1369 * away.
1370 *
1371 * <p><em>Derived classes must call through to the super class's
1372 * implementation of this method. If they do not, an exception will be
1373 * thrown.</em></p>
1374 *
1375 * @see #onPause
1376 * @see #onStop
1377 * @see #finish
1378 * @see #isFinishing
1379 */
1380 protected void onDestroy() {
1381 mCalled = true;
1382
1383 // dismiss any dialogs we are managing.
1384 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 final int numDialogs = mManagedDialogs.size();
1386 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001387 final ManagedDialog md = mManagedDialogs.valueAt(i);
1388 if (md.mDialog.isShowing()) {
1389 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
1391 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001392 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
1395 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001396 synchronized (mManagedCursors) {
1397 int numCursors = mManagedCursors.size();
1398 for (int i = 0; i < numCursors; i++) {
1399 ManagedCursor c = mManagedCursors.get(i);
1400 if (c != null) {
1401 c.mCursor.close();
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001404 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
Amith Yamasani49860442010-03-17 20:54:10 -07001406
1407 // Close any open search dialog
1408 if (mSearchManager != null) {
1409 mSearchManager.stopSearch();
1410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
1412
1413 /**
1414 * Called by the system when the device configuration changes while your
1415 * activity is running. Note that this will <em>only</em> be called if
1416 * you have selected configurations you would like to handle with the
1417 * {@link android.R.attr#configChanges} attribute in your manifest. If
1418 * any configuration change occurs that is not selected to be reported
1419 * by that attribute, then instead of reporting it the system will stop
1420 * and restart the activity (to have it launched with the new
1421 * configuration).
1422 *
1423 * <p>At the time that this function has been called, your Resources
1424 * object will have been updated to return resource values matching the
1425 * new configuration.
1426 *
1427 * @param newConfig The new device configuration.
1428 */
1429 public void onConfigurationChanged(Configuration newConfig) {
1430 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 if (mWindow != null) {
1433 // Pass the configuration changed event to the window
1434 mWindow.onConfigurationChanged(newConfig);
1435 }
1436 }
1437
1438 /**
1439 * If this activity is being destroyed because it can not handle a
1440 * configuration parameter being changed (and thus its
1441 * {@link #onConfigurationChanged(Configuration)} method is
1442 * <em>not</em> being called), then you can use this method to discover
1443 * the set of changes that have occurred while in the process of being
1444 * destroyed. Note that there is no guarantee that these will be
1445 * accurate (other changes could have happened at any time), so you should
1446 * only use this as an optimization hint.
1447 *
1448 * @return Returns a bit field of the configuration parameters that are
1449 * changing, as defined by the {@link android.content.res.Configuration}
1450 * class.
1451 */
1452 public int getChangingConfigurations() {
1453 return mConfigChangeFlags;
1454 }
1455
1456 /**
1457 * Retrieve the non-configuration instance data that was previously
1458 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1459 * be available from the initial {@link #onCreate} and
1460 * {@link #onStart} calls to the new instance, allowing you to extract
1461 * any useful dynamic state from the previous instance.
1462 *
1463 * <p>Note that the data you retrieve here should <em>only</em> be used
1464 * as an optimization for handling configuration changes. You should always
1465 * be able to handle getting a null pointer back, and an activity must
1466 * still be able to restore itself to its previous state (through the
1467 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1468 * function returns null.
1469 *
1470 * @return Returns the object previously returned by
1471 * {@link #onRetainNonConfigurationInstance()}.
1472 */
1473 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001474 return mLastNonConfigurationInstances != null
1475 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477
1478 /**
1479 * Called by the system, as part of destroying an
1480 * activity due to a configuration change, when it is known that a new
1481 * instance will immediately be created for the new configuration. You
1482 * can return any object you like here, including the activity instance
1483 * itself, which can later be retrieved by calling
1484 * {@link #getLastNonConfigurationInstance()} in the new activity
1485 * instance.
1486 *
1487 * <p>This function is called purely as an optimization, and you must
1488 * not rely on it being called. When it is called, a number of guarantees
1489 * will be made to help optimize configuration switching:
1490 * <ul>
1491 * <li> The function will be called between {@link #onStop} and
1492 * {@link #onDestroy}.
1493 * <li> A new instance of the activity will <em>always</em> be immediately
1494 * created after this one's {@link #onDestroy()} is called.
1495 * <li> The object you return here will <em>always</em> be available from
1496 * the {@link #getLastNonConfigurationInstance()} method of the following
1497 * activity instance as described there.
1498 * </ul>
1499 *
1500 * <p>These guarantees are designed so that an activity can use this API
1501 * to propagate extensive state from the old to new activity instance, from
1502 * loaded bitmaps, to network connections, to evenly actively running
1503 * threads. Note that you should <em>not</em> propagate any data that
1504 * may change based on the configuration, including any data loaded from
1505 * resources such as strings, layouts, or drawables.
1506 *
1507 * @return Return any Object holding the desired state to propagate to the
1508 * next activity instance.
1509 */
1510 public Object onRetainNonConfigurationInstance() {
1511 return null;
1512 }
1513
1514 /**
1515 * Retrieve the non-configuration instance data that was previously
1516 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1517 * be available from the initial {@link #onCreate} and
1518 * {@link #onStart} calls to the new instance, allowing you to extract
1519 * any useful dynamic state from the previous instance.
1520 *
1521 * <p>Note that the data you retrieve here should <em>only</em> be used
1522 * as an optimization for handling configuration changes. You should always
1523 * be able to handle getting a null pointer back, and an activity must
1524 * still be able to restore itself to its previous state (through the
1525 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1526 * function returns null.
1527 *
1528 * @return Returns the object previously returned by
1529 * {@link #onRetainNonConfigurationChildInstances()}
1530 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001531 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1532 return mLastNonConfigurationInstances != null
1533 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
1536 /**
1537 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1538 * it should return either a mapping from child activity id strings to arbitrary objects,
1539 * or null. This method is intended to be used by Activity framework subclasses that control a
1540 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1541 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1542 */
1543 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1544 return null;
1545 }
1546
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001547 NonConfigurationInstances retainNonConfigurationInstances() {
1548 Object activity = onRetainNonConfigurationInstance();
1549 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1550 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001551 boolean retainLoaders = false;
1552 if (mAllLoaderManagers != null) {
1553 // prune out any loader managers that were already stopped, so
1554 // have nothing useful to retain.
1555 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001556 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001557 if (lm.mRetaining) {
1558 retainLoaders = true;
1559 } else {
1560 mAllLoaderManagers.removeAt(i);
1561 }
1562 }
1563 }
1564 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001565 return null;
1566 }
1567
1568 NonConfigurationInstances nci = new NonConfigurationInstances();
1569 nci.activity = activity;
1570 nci.children = children;
1571 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001572 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001573 return nci;
1574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 public void onLowMemory() {
1577 mCalled = true;
1578 }
1579
1580 /**
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001581 * Start a series of edit operations on the Fragments associated with
1582 * this activity.
1583 */
1584 public FragmentTransaction openFragmentTransaction() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001585 return new BackStackEntry(mFragments);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001586 }
1587
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001588 void invalidateFragmentIndex(int index) {
1589 if (mAllLoaderManagers != null) {
1590 mAllLoaderManagers.remove(index);
1591 }
1592 }
1593
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001594 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001595 * Called when a Fragment is being attached to this activity, immediately
1596 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1597 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1598 */
1599 public void onAttachFragment(Fragment fragment) {
1600 }
1601
1602 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 * Wrapper around
1604 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1605 * that gives the resulting {@link Cursor} to call
1606 * {@link #startManagingCursor} so that the activity will manage its
1607 * lifecycle for you.
1608 *
1609 * @param uri The URI of the content provider to query.
1610 * @param projection List of columns to return.
1611 * @param selection SQL WHERE clause.
1612 * @param sortOrder SQL ORDER BY clause.
1613 *
1614 * @return The Cursor that was returned by query().
1615 *
1616 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1617 * @see #startManagingCursor
1618 * @hide
1619 */
1620 public final Cursor managedQuery(Uri uri,
1621 String[] projection,
1622 String selection,
1623 String sortOrder)
1624 {
1625 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1626 if (c != null) {
1627 startManagingCursor(c);
1628 }
1629 return c;
1630 }
1631
1632 /**
1633 * Wrapper around
1634 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1635 * that gives the resulting {@link Cursor} to call
1636 * {@link #startManagingCursor} so that the activity will manage its
1637 * lifecycle for you.
1638 *
1639 * @param uri The URI of the content provider to query.
1640 * @param projection List of columns to return.
1641 * @param selection SQL WHERE clause.
1642 * @param selectionArgs The arguments to selection, if any ?s are pesent
1643 * @param sortOrder SQL ORDER BY clause.
1644 *
1645 * @return The Cursor that was returned by query().
1646 *
1647 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1648 * @see #startManagingCursor
1649 */
1650 public final Cursor managedQuery(Uri uri,
1651 String[] projection,
1652 String selection,
1653 String[] selectionArgs,
1654 String sortOrder)
1655 {
1656 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1657 if (c != null) {
1658 startManagingCursor(c);
1659 }
1660 return c;
1661 }
1662
1663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * This method allows the activity to take care of managing the given
1665 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1666 * That is, when the activity is stopped it will automatically call
1667 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1668 * it will call {@link Cursor#requery} for you. When the activity is
1669 * destroyed, all managed Cursors will be closed automatically.
1670 *
1671 * @param c The Cursor to be managed.
1672 *
1673 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1674 * @see #stopManagingCursor
1675 */
1676 public void startManagingCursor(Cursor c) {
1677 synchronized (mManagedCursors) {
1678 mManagedCursors.add(new ManagedCursor(c));
1679 }
1680 }
1681
1682 /**
1683 * Given a Cursor that was previously given to
1684 * {@link #startManagingCursor}, stop the activity's management of that
1685 * cursor.
1686 *
1687 * @param c The Cursor that was being managed.
1688 *
1689 * @see #startManagingCursor
1690 */
1691 public void stopManagingCursor(Cursor c) {
1692 synchronized (mManagedCursors) {
1693 final int N = mManagedCursors.size();
1694 for (int i=0; i<N; i++) {
1695 ManagedCursor mc = mManagedCursors.get(i);
1696 if (mc.mCursor == c) {
1697 mManagedCursors.remove(i);
1698 break;
1699 }
1700 }
1701 }
1702 }
1703
1704 /**
1705 * Control whether this activity is required to be persistent. By default
1706 * activities are not persistent; setting this to true will prevent the
1707 * system from stopping this activity or its process when running low on
1708 * resources.
1709 *
1710 * <p><em>You should avoid using this method</em>, it has severe negative
1711 * consequences on how well the system can manage its resources. A better
1712 * approach is to implement an application service that you control with
1713 * {@link Context#startService} and {@link Context#stopService}.
1714 *
1715 * @param isPersistent Control whether the current activity must be
1716 * persistent, true if so, false for the normal
1717 * behavior.
1718 */
1719 public void setPersistent(boolean isPersistent) {
1720 if (mParent == null) {
1721 try {
1722 ActivityManagerNative.getDefault()
1723 .setPersistent(mToken, isPersistent);
1724 } catch (RemoteException e) {
1725 // Empty
1726 }
1727 } else {
1728 throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1729 }
1730 }
1731
1732 /**
1733 * Finds a view that was identified by the id attribute from the XML that
1734 * was processed in {@link #onCreate}.
1735 *
1736 * @return The view if found or null otherwise.
1737 */
1738 public View findViewById(int id) {
1739 return getWindow().findViewById(id);
1740 }
Adam Powell33b97432010-04-20 10:01:14 -07001741
1742 /**
1743 * Retrieve a reference to this activity's ActionBar.
1744 *
1745 * <p><em>Note:</em> The ActionBar is initialized when a content view
1746 * is set. This function will return null if called before {@link #setContentView}
1747 * or {@link #addContentView}.
1748 * @return The Activity's ActionBar, or null if it does not have one.
1749 */
1750 public ActionBar getActionBar() {
1751 return mActionBar;
1752 }
1753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 /**
Adam Powell33b97432010-04-20 10:01:14 -07001755 * Creates a new ActionBar, locates the inflated ActionBarView,
1756 * initializes the ActionBar with the view, and sets mActionBar.
1757 */
1758 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001759 Window window = getWindow();
Adam Powell661c9082010-07-02 10:09:44 -07001760 if (!window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001761 return;
1762 }
1763
Adam Powell661c9082010-07-02 10:09:44 -07001764 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001765 }
1766
1767 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001768 * Finds a fragment that was identified by the given id either when inflated
1769 * from XML or as the container ID when added in a transaction. This only
1770 * returns fragments that are currently added to the activity's content.
1771 * @return The fragment if found or null otherwise.
1772 */
1773 public Fragment findFragmentById(int id) {
1774 return mFragments.findFragmentById(id);
1775 }
1776
1777 /**
1778 * Finds a fragment that was identified by the given tag either when inflated
1779 * from XML or as supplied when added in a transaction. This only
1780 * returns fragments that are currently added to the activity's content.
1781 * @return The fragment if found or null otherwise.
1782 */
1783 public Fragment findFragmentByTag(String tag) {
1784 return mFragments.findFragmentByTag(tag);
1785 }
1786
1787 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 * Set the activity content from a layout resource. The resource will be
1789 * inflated, adding all top-level views to the activity.
1790 *
1791 * @param layoutResID Resource ID to be inflated.
1792 */
1793 public void setContentView(int layoutResID) {
1794 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001795 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797
1798 /**
1799 * Set the activity content to an explicit view. This view is placed
1800 * directly into the activity's view hierarchy. It can itself be a complex
1801 * view hierarhcy.
1802 *
1803 * @param view The desired content to display.
1804 */
1805 public void setContentView(View view) {
1806 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001807 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
1809
1810 /**
1811 * Set the activity content to an explicit view. This view is placed
1812 * directly into the activity's view hierarchy. It can itself be a complex
1813 * view hierarhcy.
1814 *
1815 * @param view The desired content to display.
1816 * @param params Layout parameters for the view.
1817 */
1818 public void setContentView(View view, ViewGroup.LayoutParams params) {
1819 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001820 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822
1823 /**
1824 * Add an additional content view to the activity. Added after any existing
1825 * ones in the activity -- existing views are NOT removed.
1826 *
1827 * @param view The desired content to display.
1828 * @param params Layout parameters for the view.
1829 */
1830 public void addContentView(View view, ViewGroup.LayoutParams params) {
1831 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001832 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834
1835 /**
1836 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1837 * keys.
1838 *
1839 * @see #setDefaultKeyMode
1840 */
1841 static public final int DEFAULT_KEYS_DISABLE = 0;
1842 /**
1843 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1844 * key handling.
1845 *
1846 * @see #setDefaultKeyMode
1847 */
1848 static public final int DEFAULT_KEYS_DIALER = 1;
1849 /**
1850 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1851 * default key handling.
1852 *
1853 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1854 *
1855 * @see #setDefaultKeyMode
1856 */
1857 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1858 /**
1859 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1860 * will start an application-defined search. (If the application or activity does not
1861 * actually define a search, the the keys will be ignored.)
1862 *
1863 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1864 *
1865 * @see #setDefaultKeyMode
1866 */
1867 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1868
1869 /**
1870 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1871 * will start a global search (typically web search, but some platforms may define alternate
1872 * methods for global search)
1873 *
1874 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1875 *
1876 * @see #setDefaultKeyMode
1877 */
1878 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1879
1880 /**
1881 * Select the default key handling for this activity. This controls what
1882 * will happen to key events that are not otherwise handled. The default
1883 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1884 * floor. Other modes allow you to launch the dialer
1885 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1886 * menu without requiring the menu key be held down
1887 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1888 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1889 *
1890 * <p>Note that the mode selected here does not impact the default
1891 * handling of system keys, such as the "back" and "menu" keys, and your
1892 * activity and its views always get a first chance to receive and handle
1893 * all application keys.
1894 *
1895 * @param mode The desired default key mode constant.
1896 *
1897 * @see #DEFAULT_KEYS_DISABLE
1898 * @see #DEFAULT_KEYS_DIALER
1899 * @see #DEFAULT_KEYS_SHORTCUT
1900 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1901 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1902 * @see #onKeyDown
1903 */
1904 public final void setDefaultKeyMode(int mode) {
1905 mDefaultKeyMode = mode;
1906
1907 // Some modes use a SpannableStringBuilder to track & dispatch input events
1908 // This list must remain in sync with the switch in onKeyDown()
1909 switch (mode) {
1910 case DEFAULT_KEYS_DISABLE:
1911 case DEFAULT_KEYS_SHORTCUT:
1912 mDefaultKeySsb = null; // not used in these modes
1913 break;
1914 case DEFAULT_KEYS_DIALER:
1915 case DEFAULT_KEYS_SEARCH_LOCAL:
1916 case DEFAULT_KEYS_SEARCH_GLOBAL:
1917 mDefaultKeySsb = new SpannableStringBuilder();
1918 Selection.setSelection(mDefaultKeySsb,0);
1919 break;
1920 default:
1921 throw new IllegalArgumentException();
1922 }
1923 }
1924
1925 /**
1926 * Called when a key was pressed down and not handled by any of the views
1927 * inside of the activity. So, for example, key presses while the cursor
1928 * is inside a TextView will not trigger the event (unless it is a navigation
1929 * to another object) because TextView handles its own key presses.
1930 *
1931 * <p>If the focused view didn't want this event, this method is called.
1932 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001933 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1934 * by calling {@link #onBackPressed()}, though the behavior varies based
1935 * on the application compatibility mode: for
1936 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1937 * it will set up the dispatch to call {@link #onKeyUp} where the action
1938 * will be performed; for earlier applications, it will perform the
1939 * action immediately in on-down, as those versions of the platform
1940 * behaved.
1941 *
1942 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001943 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 *
1945 * @return Return <code>true</code> to prevent this event from being propagated
1946 * further, or <code>false</code> to indicate that you have not handled
1947 * this event and it should continue to be propagated.
1948 * @see #onKeyUp
1949 * @see android.view.KeyEvent
1950 */
1951 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001952 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001953 if (getApplicationInfo().targetSdkVersion
1954 >= Build.VERSION_CODES.ECLAIR) {
1955 event.startTracking();
1956 } else {
1957 onBackPressed();
1958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 return true;
1960 }
1961
1962 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1963 return false;
1964 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001965 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1966 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1967 return true;
1968 }
1969 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 } else {
1971 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1972 boolean clearSpannable = false;
1973 boolean handled;
1974 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1975 clearSpannable = true;
1976 handled = false;
1977 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001978 handled = TextKeyListener.getInstance().onKeyDown(
1979 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if (handled && mDefaultKeySsb.length() > 0) {
1981 // something useable has been typed - dispatch it now.
1982
1983 final String str = mDefaultKeySsb.toString();
1984 clearSpannable = true;
1985
1986 switch (mDefaultKeyMode) {
1987 case DEFAULT_KEYS_DIALER:
1988 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1989 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1990 startActivity(intent);
1991 break;
1992 case DEFAULT_KEYS_SEARCH_LOCAL:
1993 startSearch(str, false, null, false);
1994 break;
1995 case DEFAULT_KEYS_SEARCH_GLOBAL:
1996 startSearch(str, false, null, true);
1997 break;
1998 }
1999 }
2000 }
2001 if (clearSpannable) {
2002 mDefaultKeySsb.clear();
2003 mDefaultKeySsb.clearSpans();
2004 Selection.setSelection(mDefaultKeySsb,0);
2005 }
2006 return handled;
2007 }
2008 }
2009
2010 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002011 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2012 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2013 * the event).
2014 */
2015 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2016 return false;
2017 }
2018
2019 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 * Called when a key was released and not handled by any of the views
2021 * inside of the activity. So, for example, key presses while the cursor
2022 * is inside a TextView will not trigger the event (unless it is a navigation
2023 * to another object) because TextView handles its own key presses.
2024 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002025 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2026 * and go back.
2027 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 * @return Return <code>true</code> to prevent this event from being propagated
2029 * further, or <code>false</code> to indicate that you have not handled
2030 * this event and it should continue to be propagated.
2031 * @see #onKeyDown
2032 * @see KeyEvent
2033 */
2034 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002035 if (getApplicationInfo().targetSdkVersion
2036 >= Build.VERSION_CODES.ECLAIR) {
2037 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2038 && !event.isCanceled()) {
2039 onBackPressed();
2040 return true;
2041 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 return false;
2044 }
2045
2046 /**
2047 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2048 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2049 * the event).
2050 */
2051 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2052 return false;
2053 }
2054
2055 /**
Dianne Hackborndd913a52010-07-22 12:17:04 -07002056 * Flag for {@link #popBackStack(String, int)}
2057 * and {@link #popBackStack(int, int)}: If set, and the name or ID of
2058 * a back stack entry has been supplied, then that entry will also be
2059 * removed. Otherwise, all entries up to but not including that entry
2060 * will be removed
2061 */
2062 static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
2063
2064 /**
2065 * Pop the top state off the back stack. Returns true if there was one
2066 * to pop, else false.
2067 */
2068 public boolean popBackStack() {
2069 return popBackStack(null, 0);
2070 }
2071
2072 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002073 * Pop the last fragment transition from the local activity's fragment
2074 * back stack. If there is nothing to pop, false is returned.
Dianne Hackbornf121be72010-05-06 14:10:32 -07002075 * @param name If non-null, this is the name of a previous back state
Dianne Hackborndd913a52010-07-22 12:17:04 -07002076 * to look for; if found, all states up to that state will be popped. The
2077 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2078 * the named state itself is popped. If null, only the top state is popped.
2079 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002080 */
Dianne Hackborndd913a52010-07-22 12:17:04 -07002081 public boolean popBackStack(String name, int flags) {
2082 return mFragments.popBackStackState(mHandler, name, flags);
2083 }
2084
2085 /**
2086 * Pop all back stack states up to the one with the given identifier.
2087 * @param id Identifier of the stated to be popped. If no identifier exists,
2088 * false is returned.
2089 * The identifier is the number returned by
2090 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The
2091 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2092 * the named state itself is popped.
2093 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
2094 */
2095 public boolean popBackStack(int id, int flags) {
2096 return mFragments.popBackStackState(mHandler, id, flags);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002097 }
2098
2099 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002100 * Called when the activity has detected the user's press of the back
2101 * key. The default implementation simply finishes the current activity,
2102 * but you can override this to do whatever you want.
2103 */
2104 public void onBackPressed() {
Dianne Hackborndd913a52010-07-22 12:17:04 -07002105 if (!popBackStack()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002106 finish();
2107 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002108 }
2109
2110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 * Called when a touch screen event was not handled by any of the views
2112 * under it. This is most useful to process touch events that happen
2113 * outside of your window bounds, where there is no view to receive it.
2114 *
2115 * @param event The touch screen event being processed.
2116 *
2117 * @return Return true if you have consumed the event, false if you haven't.
2118 * The default implementation always returns false.
2119 */
2120 public boolean onTouchEvent(MotionEvent event) {
2121 return false;
2122 }
2123
2124 /**
2125 * Called when the trackball was moved and not handled by any of the
2126 * views inside of the activity. So, for example, if the trackball moves
2127 * while focus is on a button, you will receive a call here because
2128 * buttons do not normally do anything with trackball events. The call
2129 * here happens <em>before</em> trackball movements are converted to
2130 * DPAD key events, which then get sent back to the view hierarchy, and
2131 * will be processed at the point for things like focus navigation.
2132 *
2133 * @param event The trackball event being processed.
2134 *
2135 * @return Return true if you have consumed the event, false if you haven't.
2136 * The default implementation always returns false.
2137 */
2138 public boolean onTrackballEvent(MotionEvent event) {
2139 return false;
2140 }
2141
2142 /**
2143 * Called whenever a key, touch, or trackball event is dispatched to the
2144 * activity. Implement this method if you wish to know that the user has
2145 * interacted with the device in some way while your activity is running.
2146 * This callback and {@link #onUserLeaveHint} are intended to help
2147 * activities manage status bar notifications intelligently; specifically,
2148 * for helping activities determine the proper time to cancel a notfication.
2149 *
2150 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2151 * be accompanied by calls to {@link #onUserInteraction}. This
2152 * ensures that your activity will be told of relevant user activity such
2153 * as pulling down the notification pane and touching an item there.
2154 *
2155 * <p>Note that this callback will be invoked for the touch down action
2156 * that begins a touch gesture, but may not be invoked for the touch-moved
2157 * and touch-up actions that follow.
2158 *
2159 * @see #onUserLeaveHint()
2160 */
2161 public void onUserInteraction() {
2162 }
2163
2164 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2165 // Update window manager if: we have a view, that view is
2166 // attached to its parent (which will be a RootView), and
2167 // this activity is not embedded.
2168 if (mParent == null) {
2169 View decor = mDecor;
2170 if (decor != null && decor.getParent() != null) {
2171 getWindowManager().updateViewLayout(decor, params);
2172 }
2173 }
2174 }
2175
2176 public void onContentChanged() {
2177 }
2178
2179 /**
2180 * Called when the current {@link Window} of the activity gains or loses
2181 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002182 * to the user. The default implementation clears the key tracking
2183 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002185 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 * is managed independently of activity lifecycles. As such, while focus
2187 * changes will generally have some relation to lifecycle changes (an
2188 * activity that is stopped will not generally get window focus), you
2189 * should not rely on any particular order between the callbacks here and
2190 * those in the other lifecycle methods such as {@link #onResume}.
2191 *
2192 * <p>As a general rule, however, a resumed activity will have window
2193 * focus... unless it has displayed other dialogs or popups that take
2194 * input focus, in which case the activity itself will not have focus
2195 * when the other windows have it. Likewise, the system may display
2196 * system-level windows (such as the status bar notification panel or
2197 * a system alert) which will temporarily take window input focus without
2198 * pausing the foreground activity.
2199 *
2200 * @param hasFocus Whether the window of this activity has focus.
2201 *
2202 * @see #hasWindowFocus()
2203 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002204 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 */
2206 public void onWindowFocusChanged(boolean hasFocus) {
2207 }
2208
2209 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002210 * Called when the main window associated with the activity has been
2211 * attached to the window manager.
2212 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2213 * for more information.
2214 * @see View#onAttachedToWindow
2215 */
2216 public void onAttachedToWindow() {
2217 }
2218
2219 /**
2220 * Called when the main window associated with the activity has been
2221 * detached from the window manager.
2222 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2223 * for more information.
2224 * @see View#onDetachedFromWindow
2225 */
2226 public void onDetachedFromWindow() {
2227 }
2228
2229 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 * Returns true if this activity's <em>main</em> window currently has window focus.
2231 * Note that this is not the same as the view itself having focus.
2232 *
2233 * @return True if this activity's main window currently has window focus.
2234 *
2235 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2236 */
2237 public boolean hasWindowFocus() {
2238 Window w = getWindow();
2239 if (w != null) {
2240 View d = w.getDecorView();
2241 if (d != null) {
2242 return d.hasWindowFocus();
2243 }
2244 }
2245 return false;
2246 }
2247
2248 /**
2249 * Called to process key events. You can override this to intercept all
2250 * key events before they are dispatched to the window. Be sure to call
2251 * this implementation for key events that should be handled normally.
2252 *
2253 * @param event The key event.
2254 *
2255 * @return boolean Return true if this event was consumed.
2256 */
2257 public boolean dispatchKeyEvent(KeyEvent event) {
2258 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002259 Window win = getWindow();
2260 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 return true;
2262 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002263 View decor = mDecor;
2264 if (decor == null) decor = win.getDecorView();
2265 return event.dispatch(this, decor != null
2266 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 }
2268
2269 /**
2270 * Called to process touch screen events. You can override this to
2271 * intercept all touch screen events before they are dispatched to the
2272 * window. Be sure to call this implementation for touch screen events
2273 * that should be handled normally.
2274 *
2275 * @param ev The touch screen event.
2276 *
2277 * @return boolean Return true if this event was consumed.
2278 */
2279 public boolean dispatchTouchEvent(MotionEvent ev) {
2280 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2281 onUserInteraction();
2282 }
2283 if (getWindow().superDispatchTouchEvent(ev)) {
2284 return true;
2285 }
2286 return onTouchEvent(ev);
2287 }
2288
2289 /**
2290 * Called to process trackball events. You can override this to
2291 * intercept all trackball events before they are dispatched to the
2292 * window. Be sure to call this implementation for trackball events
2293 * that should be handled normally.
2294 *
2295 * @param ev The trackball event.
2296 *
2297 * @return boolean Return true if this event was consumed.
2298 */
2299 public boolean dispatchTrackballEvent(MotionEvent ev) {
2300 onUserInteraction();
2301 if (getWindow().superDispatchTrackballEvent(ev)) {
2302 return true;
2303 }
2304 return onTrackballEvent(ev);
2305 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002306
2307 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2308 event.setClassName(getClass().getName());
2309 event.setPackageName(getPackageName());
2310
2311 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002312 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2313 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002314 event.setFullScreen(isFullScreen);
2315
2316 CharSequence title = getTitle();
2317 if (!TextUtils.isEmpty(title)) {
2318 event.getText().add(title);
2319 }
2320
2321 return true;
2322 }
2323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 /**
2325 * Default implementation of
2326 * {@link android.view.Window.Callback#onCreatePanelView}
2327 * for activities. This
2328 * simply returns null so that all panel sub-windows will have the default
2329 * menu behavior.
2330 */
2331 public View onCreatePanelView(int featureId) {
2332 return null;
2333 }
2334
2335 /**
2336 * Default implementation of
2337 * {@link android.view.Window.Callback#onCreatePanelMenu}
2338 * for activities. This calls through to the new
2339 * {@link #onCreateOptionsMenu} method for the
2340 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2341 * so that subclasses of Activity don't need to deal with feature codes.
2342 */
2343 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2344 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002345 boolean show = onCreateOptionsMenu(menu);
2346 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2347 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349 return false;
2350 }
2351
2352 /**
2353 * Default implementation of
2354 * {@link android.view.Window.Callback#onPreparePanel}
2355 * for activities. This
2356 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2357 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2358 * panel, so that subclasses of
2359 * Activity don't need to deal with feature codes.
2360 */
2361 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2362 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2363 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002364 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 return goforit && menu.hasVisibleItems();
2366 }
2367 return true;
2368 }
2369
2370 /**
2371 * {@inheritDoc}
2372 *
2373 * @return The default implementation returns true.
2374 */
2375 public boolean onMenuOpened(int featureId, Menu menu) {
2376 return true;
2377 }
2378
2379 /**
2380 * Default implementation of
2381 * {@link android.view.Window.Callback#onMenuItemSelected}
2382 * for activities. This calls through to the new
2383 * {@link #onOptionsItemSelected} method for the
2384 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2385 * panel, so that subclasses of
2386 * Activity don't need to deal with feature codes.
2387 */
2388 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2389 switch (featureId) {
2390 case Window.FEATURE_OPTIONS_PANEL:
2391 // Put event logging here so it gets called even if subclass
2392 // doesn't call through to superclass's implmeentation of each
2393 // of these methods below
2394 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002395 if (onOptionsItemSelected(item)) {
2396 return true;
2397 }
2398 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399
2400 case Window.FEATURE_CONTEXT_MENU:
2401 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002402 if (onContextItemSelected(item)) {
2403 return true;
2404 }
2405 return mFragments.dispatchContextItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406
2407 default:
2408 return false;
2409 }
2410 }
2411
2412 /**
2413 * Default implementation of
2414 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2415 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2416 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2417 * so that subclasses of Activity don't need to deal with feature codes.
2418 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2419 * {@link #onContextMenuClosed(Menu)} will be called.
2420 */
2421 public void onPanelClosed(int featureId, Menu menu) {
2422 switch (featureId) {
2423 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002424 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 onOptionsMenuClosed(menu);
2426 break;
2427
2428 case Window.FEATURE_CONTEXT_MENU:
2429 onContextMenuClosed(menu);
2430 break;
2431 }
2432 }
2433
2434 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002435 * Declare that the options menu has changed, so should be recreated.
2436 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2437 * time it needs to be displayed.
2438 */
2439 public void invalidateOptionsMenu() {
2440 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2441 }
2442
2443 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 * Initialize the contents of the Activity's standard options menu. You
2445 * should place your menu items in to <var>menu</var>.
2446 *
2447 * <p>This is only called once, the first time the options menu is
2448 * displayed. To update the menu every time it is displayed, see
2449 * {@link #onPrepareOptionsMenu}.
2450 *
2451 * <p>The default implementation populates the menu with standard system
2452 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2453 * they will be correctly ordered with application-defined menu items.
2454 * Deriving classes should always call through to the base implementation.
2455 *
2456 * <p>You can safely hold on to <var>menu</var> (and any items created
2457 * from it), making modifications to it as desired, until the next
2458 * time onCreateOptionsMenu() is called.
2459 *
2460 * <p>When you add items to the menu, you can implement the Activity's
2461 * {@link #onOptionsItemSelected} method to handle them there.
2462 *
2463 * @param menu The options menu in which you place your items.
2464 *
2465 * @return You must return true for the menu to be displayed;
2466 * if you return false it will not be shown.
2467 *
2468 * @see #onPrepareOptionsMenu
2469 * @see #onOptionsItemSelected
2470 */
2471 public boolean onCreateOptionsMenu(Menu menu) {
2472 if (mParent != null) {
2473 return mParent.onCreateOptionsMenu(menu);
2474 }
2475 return true;
2476 }
2477
2478 /**
2479 * Prepare the Screen's standard options menu to be displayed. This is
2480 * called right before the menu is shown, every time it is shown. You can
2481 * use this method to efficiently enable/disable items or otherwise
2482 * dynamically modify the contents.
2483 *
2484 * <p>The default implementation updates the system menu items based on the
2485 * activity's state. Deriving classes should always call through to the
2486 * base class implementation.
2487 *
2488 * @param menu The options menu as last shown or first initialized by
2489 * onCreateOptionsMenu().
2490 *
2491 * @return You must return true for the menu to be displayed;
2492 * if you return false it will not be shown.
2493 *
2494 * @see #onCreateOptionsMenu
2495 */
2496 public boolean onPrepareOptionsMenu(Menu menu) {
2497 if (mParent != null) {
2498 return mParent.onPrepareOptionsMenu(menu);
2499 }
2500 return true;
2501 }
2502
2503 /**
2504 * This hook is called whenever an item in your options menu is selected.
2505 * The default implementation simply returns false to have the normal
2506 * processing happen (calling the item's Runnable or sending a message to
2507 * its Handler as appropriate). You can use this method for any items
2508 * for which you would like to do processing without those other
2509 * facilities.
2510 *
2511 * <p>Derived classes should call through to the base class for it to
2512 * perform the default menu handling.
2513 *
2514 * @param item The menu item that was selected.
2515 *
2516 * @return boolean Return false to allow normal menu processing to
2517 * proceed, true to consume it here.
2518 *
2519 * @see #onCreateOptionsMenu
2520 */
2521 public boolean onOptionsItemSelected(MenuItem item) {
2522 if (mParent != null) {
2523 return mParent.onOptionsItemSelected(item);
2524 }
2525 return false;
2526 }
2527
2528 /**
2529 * This hook is called whenever the options menu is being closed (either by the user canceling
2530 * the menu with the back/menu button, or when an item is selected).
2531 *
2532 * @param menu The options menu as last shown or first initialized by
2533 * onCreateOptionsMenu().
2534 */
2535 public void onOptionsMenuClosed(Menu menu) {
2536 if (mParent != null) {
2537 mParent.onOptionsMenuClosed(menu);
2538 }
2539 }
2540
2541 /**
2542 * Programmatically opens the options menu. If the options menu is already
2543 * open, this method does nothing.
2544 */
2545 public void openOptionsMenu() {
2546 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2547 }
2548
2549 /**
2550 * Progammatically closes the options menu. If the options menu is already
2551 * closed, this method does nothing.
2552 */
2553 public void closeOptionsMenu() {
2554 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2555 }
2556
2557 /**
2558 * Called when a context menu for the {@code view} is about to be shown.
2559 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2560 * time the context menu is about to be shown and should be populated for
2561 * the view (or item inside the view for {@link AdapterView} subclasses,
2562 * this can be found in the {@code menuInfo})).
2563 * <p>
2564 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2565 * item has been selected.
2566 * <p>
2567 * It is not safe to hold onto the context menu after this method returns.
2568 * {@inheritDoc}
2569 */
2570 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2571 }
2572
2573 /**
2574 * Registers a context menu to be shown for the given view (multiple views
2575 * can show the context menu). This method will set the
2576 * {@link OnCreateContextMenuListener} on the view to this activity, so
2577 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2578 * called when it is time to show the context menu.
2579 *
2580 * @see #unregisterForContextMenu(View)
2581 * @param view The view that should show a context menu.
2582 */
2583 public void registerForContextMenu(View view) {
2584 view.setOnCreateContextMenuListener(this);
2585 }
2586
2587 /**
2588 * Prevents a context menu to be shown for the given view. This method will remove the
2589 * {@link OnCreateContextMenuListener} on the view.
2590 *
2591 * @see #registerForContextMenu(View)
2592 * @param view The view that should stop showing a context menu.
2593 */
2594 public void unregisterForContextMenu(View view) {
2595 view.setOnCreateContextMenuListener(null);
2596 }
2597
2598 /**
2599 * Programmatically opens the context menu for a particular {@code view}.
2600 * The {@code view} should have been added via
2601 * {@link #registerForContextMenu(View)}.
2602 *
2603 * @param view The view to show the context menu for.
2604 */
2605 public void openContextMenu(View view) {
2606 view.showContextMenu();
2607 }
2608
2609 /**
2610 * Programmatically closes the most recently opened context menu, if showing.
2611 */
2612 public void closeContextMenu() {
2613 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2614 }
2615
2616 /**
2617 * This hook is called whenever an item in a context menu is selected. The
2618 * default implementation simply returns false to have the normal processing
2619 * happen (calling the item's Runnable or sending a message to its Handler
2620 * as appropriate). You can use this method for any items for which you
2621 * would like to do processing without those other facilities.
2622 * <p>
2623 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2624 * View that added this menu item.
2625 * <p>
2626 * Derived classes should call through to the base class for it to perform
2627 * the default menu handling.
2628 *
2629 * @param item The context menu item that was selected.
2630 * @return boolean Return false to allow normal context menu processing to
2631 * proceed, true to consume it here.
2632 */
2633 public boolean onContextItemSelected(MenuItem item) {
2634 if (mParent != null) {
2635 return mParent.onContextItemSelected(item);
2636 }
2637 return false;
2638 }
2639
2640 /**
2641 * This hook is called whenever the context menu is being closed (either by
2642 * the user canceling the menu with the back/menu button, or when an item is
2643 * selected).
2644 *
2645 * @param menu The context menu that is being closed.
2646 */
2647 public void onContextMenuClosed(Menu menu) {
2648 if (mParent != null) {
2649 mParent.onContextMenuClosed(menu);
2650 }
2651 }
2652
2653 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002654 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002656 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 protected Dialog onCreateDialog(int id) {
2658 return null;
2659 }
2660
2661 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002662 * Callback for creating dialogs that are managed (saved and restored) for you
2663 * by the activity. The default implementation calls through to
2664 * {@link #onCreateDialog(int)} for compatibility.
2665 *
2666 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2667 * this method the first time, and hang onto it thereafter. Any dialog
2668 * that is created by this method will automatically be saved and restored
2669 * for you, including whether it is showing.
2670 *
2671 * <p>If you would like the activity to manage saving and restoring dialogs
2672 * for you, you should override this method and handle any ids that are
2673 * passed to {@link #showDialog}.
2674 *
2675 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2676 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2677 *
2678 * @param id The id of the dialog.
2679 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2680 * @return The dialog. If you return null, the dialog will not be created.
2681 *
2682 * @see #onPrepareDialog(int, Dialog, Bundle)
2683 * @see #showDialog(int, Bundle)
2684 * @see #dismissDialog(int)
2685 * @see #removeDialog(int)
2686 */
2687 protected Dialog onCreateDialog(int id, Bundle args) {
2688 return onCreateDialog(id);
2689 }
2690
2691 /**
2692 * @deprecated Old no-arguments version of
2693 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2694 */
2695 @Deprecated
2696 protected void onPrepareDialog(int id, Dialog dialog) {
2697 dialog.setOwnerActivity(this);
2698 }
2699
2700 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002702 * shown. The default implementation calls through to
2703 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2704 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 * <p>
2706 * Override this if you need to update a managed dialog based on the state
2707 * of the application each time it is shown. For example, a time picker
2708 * dialog might want to be updated with the current time. You should call
2709 * through to the superclass's implementation. The default implementation
2710 * will set this Activity as the owner activity on the Dialog.
2711 *
2712 * @param id The id of the managed dialog.
2713 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002714 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2715 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 * @see #showDialog(int)
2717 * @see #dismissDialog(int)
2718 * @see #removeDialog(int)
2719 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002720 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2721 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
2723
2724 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002725 * Simple version of {@link #showDialog(int, Bundle)} that does not
2726 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2727 * with null arguments.
2728 */
2729 public final void showDialog(int id) {
2730 showDialog(id, null);
2731 }
2732
2733 /**
2734 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 * will be made with the same id the first time this is called for a given
2736 * id. From thereafter, the dialog will be automatically saved and restored.
2737 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002738 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 * be made to provide an opportunity to do any timely preparation.
2740 *
2741 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002742 * @param args Arguments to pass through to the dialog. These will be saved
2743 * and restored for you. Note that if the dialog is already created,
2744 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2745 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002746 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002747 * @return Returns true if the Dialog was created; false is returned if
2748 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2749 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002750 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002751 * @see #onCreateDialog(int, Bundle)
2752 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 * @see #dismissDialog(int)
2754 * @see #removeDialog(int)
2755 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002756 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002758 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002760 ManagedDialog md = mManagedDialogs.get(id);
2761 if (md == null) {
2762 md = new ManagedDialog();
2763 md.mDialog = createDialog(id, null, args);
2764 if (md.mDialog == null) {
2765 return false;
2766 }
2767 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 }
2769
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002770 md.mArgs = args;
2771 onPrepareDialog(id, md.mDialog, args);
2772 md.mDialog.show();
2773 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 }
2775
2776 /**
2777 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2778 *
2779 * @param id The id of the managed dialog.
2780 *
2781 * @throws IllegalArgumentException if the id was not previously shown via
2782 * {@link #showDialog(int)}.
2783 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002784 * @see #onCreateDialog(int, Bundle)
2785 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 * @see #showDialog(int)
2787 * @see #removeDialog(int)
2788 */
2789 public final void dismissDialog(int id) {
2790 if (mManagedDialogs == null) {
2791 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002793
2794 final ManagedDialog md = mManagedDialogs.get(id);
2795 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 throw missingDialog(id);
2797 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002798 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 }
2800
2801 /**
2802 * Creates an exception to throw if a user passed in a dialog id that is
2803 * unexpected.
2804 */
2805 private IllegalArgumentException missingDialog(int id) {
2806 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2807 + "shown via Activity#showDialog");
2808 }
2809
2810 /**
2811 * Removes any internal references to a dialog managed by this Activity.
2812 * If the dialog is showing, it will dismiss it as part of the clean up.
2813 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002814 * <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 -08002815 * want to avoid the overhead of saving and restoring it in the future.
2816 *
2817 * @param id The id of the managed dialog.
2818 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002819 * @see #onCreateDialog(int, Bundle)
2820 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 * @see #showDialog(int)
2822 * @see #dismissDialog(int)
2823 */
2824 public final void removeDialog(int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 if (mManagedDialogs == null) {
2826 return;
2827 }
2828
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002829 final ManagedDialog md = mManagedDialogs.get(id);
2830 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 return;
2832 }
2833
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002834 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 mManagedDialogs.remove(id);
2836 }
2837
2838 /**
2839 * This hook is called when the user signals the desire to start a search.
2840 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002841 * <p>You can use this function as a simple way to launch the search UI, in response to a
2842 * menu item, search button, or other widgets within your activity. Unless overidden,
2843 * calling this function is the same as calling
2844 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2845 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 *
2847 * <p>You can override this function to force global search, e.g. in response to a dedicated
2848 * search key, or to block search entirely (by simply returning false).
2849 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002850 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2851 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 *
2853 * @see android.app.SearchManager
2854 */
2855 public boolean onSearchRequested() {
2856 startSearch(null, false, null, false);
2857 return true;
2858 }
2859
2860 /**
2861 * This hook is called to launch the search UI.
2862 *
2863 * <p>It is typically called from onSearchRequested(), either directly from
2864 * Activity.onSearchRequested() or from an overridden version in any given
2865 * Activity. If your goal is simply to activate search, it is preferred to call
2866 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2867 * is to inject specific data such as context data, it is preferred to <i>override</i>
2868 * onSearchRequested(), so that any callers to it will benefit from the override.
2869 *
2870 * @param initialQuery Any non-null non-empty string will be inserted as
2871 * pre-entered text in the search query box.
2872 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2873 * any further typing will replace it. This is useful for cases where an entire pre-formed
2874 * query is being inserted. If false, the selection point will be placed at the end of the
2875 * inserted query. This is useful when the inserted query is text that the user entered,
2876 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2877 * if initialQuery is a non-empty string.</i>
2878 * @param appSearchData An application can insert application-specific
2879 * context here, in order to improve quality or specificity of its own
2880 * searches. This data will be returned with SEARCH intent(s). Null if
2881 * no extra data is required.
2882 * @param globalSearch If false, this will only launch the search that has been specifically
2883 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002884 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2886 *
2887 * @see android.app.SearchManager
2888 * @see #onSearchRequested
2889 */
2890 public void startSearch(String initialQuery, boolean selectInitialQuery,
2891 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002892 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002893 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 appSearchData, globalSearch);
2895 }
2896
2897 /**
krosaend2d60142009-08-17 08:56:48 -07002898 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2899 * the search dialog. Made available for testing purposes.
2900 *
2901 * @param query The query to trigger. If empty, the request will be ignored.
2902 * @param appSearchData An application can insert application-specific
2903 * context here, in order to improve quality or specificity of its own
2904 * searches. This data will be returned with SEARCH intent(s). Null if
2905 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002906 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002907 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002908 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002909 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002910 }
2911
2912 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 * Request that key events come to this activity. Use this if your
2914 * activity has no views with focus, but the activity still wants
2915 * a chance to process key events.
2916 *
2917 * @see android.view.Window#takeKeyEvents
2918 */
2919 public void takeKeyEvents(boolean get) {
2920 getWindow().takeKeyEvents(get);
2921 }
2922
2923 /**
2924 * Enable extended window features. This is a convenience for calling
2925 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2926 *
2927 * @param featureId The desired feature as defined in
2928 * {@link android.view.Window}.
2929 * @return Returns true if the requested feature is supported and now
2930 * enabled.
2931 *
2932 * @see android.view.Window#requestFeature
2933 */
2934 public final boolean requestWindowFeature(int featureId) {
2935 return getWindow().requestFeature(featureId);
2936 }
2937
2938 /**
2939 * Convenience for calling
2940 * {@link android.view.Window#setFeatureDrawableResource}.
2941 */
2942 public final void setFeatureDrawableResource(int featureId, int resId) {
2943 getWindow().setFeatureDrawableResource(featureId, resId);
2944 }
2945
2946 /**
2947 * Convenience for calling
2948 * {@link android.view.Window#setFeatureDrawableUri}.
2949 */
2950 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2951 getWindow().setFeatureDrawableUri(featureId, uri);
2952 }
2953
2954 /**
2955 * Convenience for calling
2956 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2957 */
2958 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2959 getWindow().setFeatureDrawable(featureId, drawable);
2960 }
2961
2962 /**
2963 * Convenience for calling
2964 * {@link android.view.Window#setFeatureDrawableAlpha}.
2965 */
2966 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2967 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2968 }
2969
2970 /**
2971 * Convenience for calling
2972 * {@link android.view.Window#getLayoutInflater}.
2973 */
2974 public LayoutInflater getLayoutInflater() {
2975 return getWindow().getLayoutInflater();
2976 }
2977
2978 /**
2979 * Returns a {@link MenuInflater} with this context.
2980 */
2981 public MenuInflater getMenuInflater() {
2982 return new MenuInflater(this);
2983 }
2984
2985 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002986 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2987 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 if (mParent == null) {
2989 super.onApplyThemeResource(theme, resid, first);
2990 } else {
2991 try {
2992 theme.setTo(mParent.getTheme());
2993 } catch (Exception e) {
2994 // Empty
2995 }
2996 theme.applyStyle(resid, false);
2997 }
2998 }
2999
3000 /**
3001 * Launch an activity for which you would like a result when it finished.
3002 * When this activity exits, your
3003 * onActivityResult() method will be called with the given requestCode.
3004 * Using a negative requestCode is the same as calling
3005 * {@link #startActivity} (the activity is not launched as a sub-activity).
3006 *
3007 * <p>Note that this method should only be used with Intent protocols
3008 * that are defined to return a result. In other protocols (such as
3009 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3010 * not get the result when you expect. For example, if the activity you
3011 * are launching uses the singleTask launch mode, it will not run in your
3012 * task and thus you will immediately receive a cancel result.
3013 *
3014 * <p>As a special case, if you call startActivityForResult() with a requestCode
3015 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3016 * activity, then your window will not be displayed until a result is
3017 * returned back from the started activity. This is to avoid visible
3018 * flickering when redirecting to another activity.
3019 *
3020 * <p>This method throws {@link android.content.ActivityNotFoundException}
3021 * if there was no Activity found to run the given Intent.
3022 *
3023 * @param intent The intent to start.
3024 * @param requestCode If >= 0, this code will be returned in
3025 * onActivityResult() when the activity exits.
3026 *
3027 * @throws android.content.ActivityNotFoundException
3028 *
3029 * @see #startActivity
3030 */
3031 public void startActivityForResult(Intent intent, int requestCode) {
3032 if (mParent == null) {
3033 Instrumentation.ActivityResult ar =
3034 mInstrumentation.execStartActivity(
3035 this, mMainThread.getApplicationThread(), mToken, this,
3036 intent, requestCode);
3037 if (ar != null) {
3038 mMainThread.sendActivityResult(
3039 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3040 ar.getResultData());
3041 }
3042 if (requestCode >= 0) {
3043 // If this start is requesting a result, we can avoid making
3044 // the activity visible until the result is received. Setting
3045 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3046 // activity hidden during this time, to avoid flickering.
3047 // This can only be done when a result is requested because
3048 // that guarantees we will get information back when the
3049 // activity is finished, no matter what happens to it.
3050 mStartedActivity = true;
3051 }
3052 } else {
3053 mParent.startActivityFromChild(this, intent, requestCode);
3054 }
3055 }
3056
3057 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003058 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003059 * to use a IntentSender to describe the activity to be started. If
3060 * the IntentSender is for an activity, that activity will be started
3061 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3062 * here; otherwise, its associated action will be executed (such as
3063 * sending a broadcast) as if you had called
3064 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003065 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003066 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003067 * @param requestCode If >= 0, this code will be returned in
3068 * onActivityResult() when the activity exits.
3069 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003070 * intent parameter to {@link IntentSender#sendIntent}.
3071 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003072 * would like to change.
3073 * @param flagsValues Desired values for any bits set in
3074 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003075 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003076 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003077 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3078 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3079 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003080 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003081 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003082 flagsMask, flagsValues, this);
3083 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003084 mParent.startIntentSenderFromChild(this, intent, requestCode,
3085 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003086 }
3087 }
3088
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003089 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003090 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003091 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003092 try {
3093 String resolvedType = null;
3094 if (fillInIntent != null) {
3095 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3096 }
3097 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003098 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003099 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3100 requestCode, flagsMask, flagsValues);
3101 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003102 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003103 }
3104 Instrumentation.checkStartActivityResult(result, null);
3105 } catch (RemoteException e) {
3106 }
3107 if (requestCode >= 0) {
3108 // If this start is requesting a result, we can avoid making
3109 // the activity visible until the result is received. Setting
3110 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3111 // activity hidden during this time, to avoid flickering.
3112 // This can only be done when a result is requested because
3113 // that guarantees we will get information back when the
3114 // activity is finished, no matter what happens to it.
3115 mStartedActivity = true;
3116 }
3117 }
3118
3119 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 * Launch a new activity. You will not receive any information about when
3121 * the activity exits. This implementation overrides the base version,
3122 * providing information about
3123 * the activity performing the launch. Because of this additional
3124 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3125 * required; if not specified, the new activity will be added to the
3126 * task of the caller.
3127 *
3128 * <p>This method throws {@link android.content.ActivityNotFoundException}
3129 * if there was no Activity found to run the given Intent.
3130 *
3131 * @param intent The intent to start.
3132 *
3133 * @throws android.content.ActivityNotFoundException
3134 *
3135 * @see #startActivityForResult
3136 */
3137 @Override
3138 public void startActivity(Intent intent) {
3139 startActivityForResult(intent, -1);
3140 }
3141
3142 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003143 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003144 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003145 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003146 * for more information.
3147 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003148 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003149 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003150 * intent parameter to {@link IntentSender#sendIntent}.
3151 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003152 * would like to change.
3153 * @param flagsValues Desired values for any bits set in
3154 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003155 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003156 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003157 public void startIntentSender(IntentSender intent,
3158 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3159 throws IntentSender.SendIntentException {
3160 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3161 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003162 }
3163
3164 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 * A special variation to launch an activity only if a new activity
3166 * instance is needed to handle the given Intent. In other words, this is
3167 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3168 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3169 * singleTask or singleTop
3170 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3171 * and the activity
3172 * that handles <var>intent</var> is the same as your currently running
3173 * activity, then a new instance is not needed. In this case, instead of
3174 * the normal behavior of calling {@link #onNewIntent} this function will
3175 * return and you can handle the Intent yourself.
3176 *
3177 * <p>This function can only be called from a top-level activity; if it is
3178 * called from a child activity, a runtime exception will be thrown.
3179 *
3180 * @param intent The intent to start.
3181 * @param requestCode If >= 0, this code will be returned in
3182 * onActivityResult() when the activity exits, as described in
3183 * {@link #startActivityForResult}.
3184 *
3185 * @return If a new activity was launched then true is returned; otherwise
3186 * false is returned and you must handle the Intent yourself.
3187 *
3188 * @see #startActivity
3189 * @see #startActivityForResult
3190 */
3191 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3192 if (mParent == null) {
3193 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3194 try {
3195 result = ActivityManagerNative.getDefault()
3196 .startActivity(mMainThread.getApplicationThread(),
3197 intent, intent.resolveTypeIfNeeded(
3198 getContentResolver()),
3199 null, 0,
3200 mToken, mEmbeddedID, requestCode, true, false);
3201 } catch (RemoteException e) {
3202 // Empty
3203 }
3204
3205 Instrumentation.checkStartActivityResult(result, intent);
3206
3207 if (requestCode >= 0) {
3208 // If this start is requesting a result, we can avoid making
3209 // the activity visible until the result is received. Setting
3210 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3211 // activity hidden during this time, to avoid flickering.
3212 // This can only be done when a result is requested because
3213 // that guarantees we will get information back when the
3214 // activity is finished, no matter what happens to it.
3215 mStartedActivity = true;
3216 }
3217 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3218 }
3219
3220 throw new UnsupportedOperationException(
3221 "startActivityIfNeeded can only be called from a top-level activity");
3222 }
3223
3224 /**
3225 * Special version of starting an activity, for use when you are replacing
3226 * other activity components. You can use this to hand the Intent off
3227 * to the next Activity that can handle it. You typically call this in
3228 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3229 *
3230 * @param intent The intent to dispatch to the next activity. For
3231 * correct behavior, this must be the same as the Intent that started
3232 * your own activity; the only changes you can make are to the extras
3233 * inside of it.
3234 *
3235 * @return Returns a boolean indicating whether there was another Activity
3236 * to start: true if there was a next activity to start, false if there
3237 * wasn't. In general, if true is returned you will then want to call
3238 * finish() on yourself.
3239 */
3240 public boolean startNextMatchingActivity(Intent intent) {
3241 if (mParent == null) {
3242 try {
3243 return ActivityManagerNative.getDefault()
3244 .startNextMatchingActivity(mToken, intent);
3245 } catch (RemoteException e) {
3246 // Empty
3247 }
3248 return false;
3249 }
3250
3251 throw new UnsupportedOperationException(
3252 "startNextMatchingActivity can only be called from a top-level activity");
3253 }
3254
3255 /**
3256 * This is called when a child activity of this one calls its
3257 * {@link #startActivity} or {@link #startActivityForResult} method.
3258 *
3259 * <p>This method throws {@link android.content.ActivityNotFoundException}
3260 * if there was no Activity found to run the given Intent.
3261 *
3262 * @param child The activity making the call.
3263 * @param intent The intent to start.
3264 * @param requestCode Reply request code. < 0 if reply is not requested.
3265 *
3266 * @throws android.content.ActivityNotFoundException
3267 *
3268 * @see #startActivity
3269 * @see #startActivityForResult
3270 */
3271 public void startActivityFromChild(Activity child, Intent intent,
3272 int requestCode) {
3273 Instrumentation.ActivityResult ar =
3274 mInstrumentation.execStartActivity(
3275 this, mMainThread.getApplicationThread(), mToken, child,
3276 intent, requestCode);
3277 if (ar != null) {
3278 mMainThread.sendActivityResult(
3279 mToken, child.mEmbeddedID, requestCode,
3280 ar.getResultCode(), ar.getResultData());
3281 }
3282 }
3283
3284 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003285 * This is called when a Fragment in this activity calls its
3286 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3287 * method.
3288 *
3289 * <p>This method throws {@link android.content.ActivityNotFoundException}
3290 * if there was no Activity found to run the given Intent.
3291 *
3292 * @param fragment The fragment making the call.
3293 * @param intent The intent to start.
3294 * @param requestCode Reply request code. < 0 if reply is not requested.
3295 *
3296 * @throws android.content.ActivityNotFoundException
3297 *
3298 * @see Fragment#startActivity
3299 * @see Fragment#startActivityForResult
3300 */
3301 public void startActivityFromFragment(Fragment fragment, Intent intent,
3302 int requestCode) {
3303 Instrumentation.ActivityResult ar =
3304 mInstrumentation.execStartActivity(
3305 this, mMainThread.getApplicationThread(), mToken, fragment,
3306 intent, requestCode);
3307 if (ar != null) {
3308 mMainThread.sendActivityResult(
3309 mToken, fragment.mWho, requestCode,
3310 ar.getResultCode(), ar.getResultData());
3311 }
3312 }
3313
3314 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003315 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003316 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003317 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003318 * for more information.
3319 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003320 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3321 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3322 int extraFlags)
3323 throws IntentSender.SendIntentException {
3324 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003325 flagsMask, flagsValues, child);
3326 }
3327
3328 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003329 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3330 * or {@link #finish} to specify an explicit transition animation to
3331 * perform next.
3332 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003333 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003334 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003335 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003336 */
3337 public void overridePendingTransition(int enterAnim, int exitAnim) {
3338 try {
3339 ActivityManagerNative.getDefault().overridePendingTransition(
3340 mToken, getPackageName(), enterAnim, exitAnim);
3341 } catch (RemoteException e) {
3342 }
3343 }
3344
3345 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 * Call this to set the result that your activity will return to its
3347 * caller.
3348 *
3349 * @param resultCode The result code to propagate back to the originating
3350 * activity, often RESULT_CANCELED or RESULT_OK
3351 *
3352 * @see #RESULT_CANCELED
3353 * @see #RESULT_OK
3354 * @see #RESULT_FIRST_USER
3355 * @see #setResult(int, Intent)
3356 */
3357 public final void setResult(int resultCode) {
3358 synchronized (this) {
3359 mResultCode = resultCode;
3360 mResultData = null;
3361 }
3362 }
3363
3364 /**
3365 * Call this to set the result that your activity will return to its
3366 * caller.
3367 *
3368 * @param resultCode The result code to propagate back to the originating
3369 * activity, often RESULT_CANCELED or RESULT_OK
3370 * @param data The data to propagate back to the originating activity.
3371 *
3372 * @see #RESULT_CANCELED
3373 * @see #RESULT_OK
3374 * @see #RESULT_FIRST_USER
3375 * @see #setResult(int)
3376 */
3377 public final void setResult(int resultCode, Intent data) {
3378 synchronized (this) {
3379 mResultCode = resultCode;
3380 mResultData = data;
3381 }
3382 }
3383
3384 /**
3385 * Return the name of the package that invoked this activity. This is who
3386 * the data in {@link #setResult setResult()} will be sent to. You can
3387 * use this information to validate that the recipient is allowed to
3388 * receive the data.
3389 *
3390 * <p>Note: if the calling activity is not expecting a result (that is it
3391 * did not use the {@link #startActivityForResult}
3392 * form that includes a request code), then the calling package will be
3393 * null.
3394 *
3395 * @return The package of the activity that will receive your
3396 * reply, or null if none.
3397 */
3398 public String getCallingPackage() {
3399 try {
3400 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3401 } catch (RemoteException e) {
3402 return null;
3403 }
3404 }
3405
3406 /**
3407 * Return the name of the activity that invoked this activity. This is
3408 * who the data in {@link #setResult setResult()} will be sent to. You
3409 * can use this information to validate that the recipient is allowed to
3410 * receive the data.
3411 *
3412 * <p>Note: if the calling activity is not expecting a result (that is it
3413 * did not use the {@link #startActivityForResult}
3414 * form that includes a request code), then the calling package will be
3415 * null.
3416 *
3417 * @return String The full name of the activity that will receive your
3418 * reply, or null if none.
3419 */
3420 public ComponentName getCallingActivity() {
3421 try {
3422 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3423 } catch (RemoteException e) {
3424 return null;
3425 }
3426 }
3427
3428 /**
3429 * Control whether this activity's main window is visible. This is intended
3430 * only for the special case of an activity that is not going to show a
3431 * UI itself, but can't just finish prior to onResume() because it needs
3432 * to wait for a service binding or such. Setting this to false allows
3433 * you to prevent your UI from being shown during that time.
3434 *
3435 * <p>The default value for this is taken from the
3436 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3437 */
3438 public void setVisible(boolean visible) {
3439 if (mVisibleFromClient != visible) {
3440 mVisibleFromClient = visible;
3441 if (mVisibleFromServer) {
3442 if (visible) makeVisible();
3443 else mDecor.setVisibility(View.INVISIBLE);
3444 }
3445 }
3446 }
3447
3448 void makeVisible() {
3449 if (!mWindowAdded) {
3450 ViewManager wm = getWindowManager();
3451 wm.addView(mDecor, getWindow().getAttributes());
3452 mWindowAdded = true;
3453 }
3454 mDecor.setVisibility(View.VISIBLE);
3455 }
3456
3457 /**
3458 * Check to see whether this activity is in the process of finishing,
3459 * either because you called {@link #finish} on it or someone else
3460 * has requested that it finished. This is often used in
3461 * {@link #onPause} to determine whether the activity is simply pausing or
3462 * completely finishing.
3463 *
3464 * @return If the activity is finishing, returns true; else returns false.
3465 *
3466 * @see #finish
3467 */
3468 public boolean isFinishing() {
3469 return mFinished;
3470 }
3471
3472 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003473 * Check to see whether this activity is in the process of being destroyed in order to be
3474 * recreated with a new configuration. This is often used in
3475 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3476 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3477 *
3478 * @return If the activity is being torn down in order to be recreated with a new configuration,
3479 * returns true; else returns false.
3480 */
3481 public boolean isChangingConfigurations() {
3482 return mChangingConfigurations;
3483 }
3484
3485 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 * Call this when your activity is done and should be closed. The
3487 * ActivityResult is propagated back to whoever launched you via
3488 * onActivityResult().
3489 */
3490 public void finish() {
3491 if (mParent == null) {
3492 int resultCode;
3493 Intent resultData;
3494 synchronized (this) {
3495 resultCode = mResultCode;
3496 resultData = mResultData;
3497 }
3498 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3499 try {
3500 if (ActivityManagerNative.getDefault()
3501 .finishActivity(mToken, resultCode, resultData)) {
3502 mFinished = true;
3503 }
3504 } catch (RemoteException e) {
3505 // Empty
3506 }
3507 } else {
3508 mParent.finishFromChild(this);
3509 }
3510 }
3511
3512 /**
3513 * This is called when a child activity of this one calls its
3514 * {@link #finish} method. The default implementation simply calls
3515 * finish() on this activity (the parent), finishing the entire group.
3516 *
3517 * @param child The activity making the call.
3518 *
3519 * @see #finish
3520 */
3521 public void finishFromChild(Activity child) {
3522 finish();
3523 }
3524
3525 /**
3526 * Force finish another activity that you had previously started with
3527 * {@link #startActivityForResult}.
3528 *
3529 * @param requestCode The request code of the activity that you had
3530 * given to startActivityForResult(). If there are multiple
3531 * activities started with this request code, they
3532 * will all be finished.
3533 */
3534 public void finishActivity(int requestCode) {
3535 if (mParent == null) {
3536 try {
3537 ActivityManagerNative.getDefault()
3538 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3539 } catch (RemoteException e) {
3540 // Empty
3541 }
3542 } else {
3543 mParent.finishActivityFromChild(this, requestCode);
3544 }
3545 }
3546
3547 /**
3548 * This is called when a child activity of this one calls its
3549 * finishActivity().
3550 *
3551 * @param child The activity making the call.
3552 * @param requestCode Request code that had been used to start the
3553 * activity.
3554 */
3555 public void finishActivityFromChild(Activity child, int requestCode) {
3556 try {
3557 ActivityManagerNative.getDefault()
3558 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3559 } catch (RemoteException e) {
3560 // Empty
3561 }
3562 }
3563
3564 /**
3565 * Called when an activity you launched exits, giving you the requestCode
3566 * you started it with, the resultCode it returned, and any additional
3567 * data from it. The <var>resultCode</var> will be
3568 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3569 * didn't return any result, or crashed during its operation.
3570 *
3571 * <p>You will receive this call immediately before onResume() when your
3572 * activity is re-starting.
3573 *
3574 * @param requestCode The integer request code originally supplied to
3575 * startActivityForResult(), allowing you to identify who this
3576 * result came from.
3577 * @param resultCode The integer result code returned by the child activity
3578 * through its setResult().
3579 * @param data An Intent, which can return result data to the caller
3580 * (various data can be attached to Intent "extras").
3581 *
3582 * @see #startActivityForResult
3583 * @see #createPendingResult
3584 * @see #setResult(int)
3585 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003586 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
3588
3589 /**
3590 * Create a new PendingIntent object which you can hand to others
3591 * for them to use to send result data back to your
3592 * {@link #onActivityResult} callback. The created object will be either
3593 * one-shot (becoming invalid after a result is sent back) or multiple
3594 * (allowing any number of results to be sent through it).
3595 *
3596 * @param requestCode Private request code for the sender that will be
3597 * associated with the result data when it is returned. The sender can not
3598 * modify this value, allowing you to identify incoming results.
3599 * @param data Default data to supply in the result, which may be modified
3600 * by the sender.
3601 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3602 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3603 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3604 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3605 * or any of the flags as supported by
3606 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3607 * of the intent that can be supplied when the actual send happens.
3608 *
3609 * @return Returns an existing or new PendingIntent matching the given
3610 * parameters. May return null only if
3611 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3612 * supplied.
3613 *
3614 * @see PendingIntent
3615 */
3616 public PendingIntent createPendingResult(int requestCode, Intent data,
3617 int flags) {
3618 String packageName = getPackageName();
3619 try {
3620 IIntentSender target =
3621 ActivityManagerNative.getDefault().getIntentSender(
3622 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3623 mParent == null ? mToken : mParent.mToken,
3624 mEmbeddedID, requestCode, data, null, flags);
3625 return target != null ? new PendingIntent(target) : null;
3626 } catch (RemoteException e) {
3627 // Empty
3628 }
3629 return null;
3630 }
3631
3632 /**
3633 * Change the desired orientation of this activity. If the activity
3634 * is currently in the foreground or otherwise impacting the screen
3635 * orientation, the screen will immediately be changed (possibly causing
3636 * the activity to be restarted). Otherwise, this will be used the next
3637 * time the activity is visible.
3638 *
3639 * @param requestedOrientation An orientation constant as used in
3640 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3641 */
3642 public void setRequestedOrientation(int requestedOrientation) {
3643 if (mParent == null) {
3644 try {
3645 ActivityManagerNative.getDefault().setRequestedOrientation(
3646 mToken, requestedOrientation);
3647 } catch (RemoteException e) {
3648 // Empty
3649 }
3650 } else {
3651 mParent.setRequestedOrientation(requestedOrientation);
3652 }
3653 }
3654
3655 /**
3656 * Return the current requested orientation of the activity. This will
3657 * either be the orientation requested in its component's manifest, or
3658 * the last requested orientation given to
3659 * {@link #setRequestedOrientation(int)}.
3660 *
3661 * @return Returns an orientation constant as used in
3662 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3663 */
3664 public int getRequestedOrientation() {
3665 if (mParent == null) {
3666 try {
3667 return ActivityManagerNative.getDefault()
3668 .getRequestedOrientation(mToken);
3669 } catch (RemoteException e) {
3670 // Empty
3671 }
3672 } else {
3673 return mParent.getRequestedOrientation();
3674 }
3675 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3676 }
3677
3678 /**
3679 * Return the identifier of the task this activity is in. This identifier
3680 * will remain the same for the lifetime of the activity.
3681 *
3682 * @return Task identifier, an opaque integer.
3683 */
3684 public int getTaskId() {
3685 try {
3686 return ActivityManagerNative.getDefault()
3687 .getTaskForActivity(mToken, false);
3688 } catch (RemoteException e) {
3689 return -1;
3690 }
3691 }
3692
3693 /**
3694 * Return whether this activity is the root of a task. The root is the
3695 * first activity in a task.
3696 *
3697 * @return True if this is the root activity, else false.
3698 */
3699 public boolean isTaskRoot() {
3700 try {
3701 return ActivityManagerNative.getDefault()
3702 .getTaskForActivity(mToken, true) >= 0;
3703 } catch (RemoteException e) {
3704 return false;
3705 }
3706 }
3707
3708 /**
3709 * Move the task containing this activity to the back of the activity
3710 * stack. The activity's order within the task is unchanged.
3711 *
3712 * @param nonRoot If false then this only works if the activity is the root
3713 * of a task; if true it will work for any activity in
3714 * a task.
3715 *
3716 * @return If the task was moved (or it was already at the
3717 * back) true is returned, else false.
3718 */
3719 public boolean moveTaskToBack(boolean nonRoot) {
3720 try {
3721 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3722 mToken, nonRoot);
3723 } catch (RemoteException e) {
3724 // Empty
3725 }
3726 return false;
3727 }
3728
3729 /**
3730 * Returns class name for this activity with the package prefix removed.
3731 * This is the default name used to read and write settings.
3732 *
3733 * @return The local class name.
3734 */
3735 public String getLocalClassName() {
3736 final String pkg = getPackageName();
3737 final String cls = mComponent.getClassName();
3738 int packageLen = pkg.length();
3739 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3740 || cls.charAt(packageLen) != '.') {
3741 return cls;
3742 }
3743 return cls.substring(packageLen+1);
3744 }
3745
3746 /**
3747 * Returns complete component name of this activity.
3748 *
3749 * @return Returns the complete component name for this activity
3750 */
3751 public ComponentName getComponentName()
3752 {
3753 return mComponent;
3754 }
3755
3756 /**
3757 * Retrieve a {@link SharedPreferences} object for accessing preferences
3758 * that are private to this activity. This simply calls the underlying
3759 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3760 * class name as the preferences name.
3761 *
3762 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3763 * operation, {@link #MODE_WORLD_READABLE} and
3764 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3765 *
3766 * @return Returns the single SharedPreferences instance that can be used
3767 * to retrieve and modify the preference values.
3768 */
3769 public SharedPreferences getPreferences(int mode) {
3770 return getSharedPreferences(getLocalClassName(), mode);
3771 }
3772
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003773 private void ensureSearchManager() {
3774 if (mSearchManager != null) {
3775 return;
3776 }
3777
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003778 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003779 }
3780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 @Override
3782 public Object getSystemService(String name) {
3783 if (getBaseContext() == null) {
3784 throw new IllegalStateException(
3785 "System services not available to Activities before onCreate()");
3786 }
3787
3788 if (WINDOW_SERVICE.equals(name)) {
3789 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003790 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003791 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003792 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 }
3794 return super.getSystemService(name);
3795 }
3796
3797 /**
3798 * Change the title associated with this activity. If this is a
3799 * top-level activity, the title for its window will change. If it
3800 * is an embedded activity, the parent can do whatever it wants
3801 * with it.
3802 */
3803 public void setTitle(CharSequence title) {
3804 mTitle = title;
3805 onTitleChanged(title, mTitleColor);
3806
3807 if (mParent != null) {
3808 mParent.onChildTitleChanged(this, title);
3809 }
3810 }
3811
3812 /**
3813 * Change the title associated with this activity. If this is a
3814 * top-level activity, the title for its window will change. If it
3815 * is an embedded activity, the parent can do whatever it wants
3816 * with it.
3817 */
3818 public void setTitle(int titleId) {
3819 setTitle(getText(titleId));
3820 }
3821
3822 public void setTitleColor(int textColor) {
3823 mTitleColor = textColor;
3824 onTitleChanged(mTitle, textColor);
3825 }
3826
3827 public final CharSequence getTitle() {
3828 return mTitle;
3829 }
3830
3831 public final int getTitleColor() {
3832 return mTitleColor;
3833 }
3834
3835 protected void onTitleChanged(CharSequence title, int color) {
3836 if (mTitleReady) {
3837 final Window win = getWindow();
3838 if (win != null) {
3839 win.setTitle(title);
3840 if (color != 0) {
3841 win.setTitleColor(color);
3842 }
3843 }
3844 }
3845 }
3846
3847 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3848 }
3849
3850 /**
3851 * Sets the visibility of the progress bar in the title.
3852 * <p>
3853 * In order for the progress bar to be shown, the feature must be requested
3854 * via {@link #requestWindowFeature(int)}.
3855 *
3856 * @param visible Whether to show the progress bars in the title.
3857 */
3858 public final void setProgressBarVisibility(boolean visible) {
3859 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3860 Window.PROGRESS_VISIBILITY_OFF);
3861 }
3862
3863 /**
3864 * Sets the visibility of the indeterminate progress bar in the title.
3865 * <p>
3866 * In order for the progress bar to be shown, the feature must be requested
3867 * via {@link #requestWindowFeature(int)}.
3868 *
3869 * @param visible Whether to show the progress bars in the title.
3870 */
3871 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3872 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3873 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3874 }
3875
3876 /**
3877 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3878 * is always indeterminate).
3879 * <p>
3880 * In order for the progress bar to be shown, the feature must be requested
3881 * via {@link #requestWindowFeature(int)}.
3882 *
3883 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3884 */
3885 public final void setProgressBarIndeterminate(boolean indeterminate) {
3886 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3887 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3888 }
3889
3890 /**
3891 * Sets the progress for the progress bars in the title.
3892 * <p>
3893 * In order for the progress bar to be shown, the feature must be requested
3894 * via {@link #requestWindowFeature(int)}.
3895 *
3896 * @param progress The progress for the progress bar. Valid ranges are from
3897 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3898 * bar will be completely filled and will fade out.
3899 */
3900 public final void setProgress(int progress) {
3901 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3902 }
3903
3904 /**
3905 * Sets the secondary progress for the progress bar in the title. This
3906 * progress is drawn between the primary progress (set via
3907 * {@link #setProgress(int)} and the background. It can be ideal for media
3908 * scenarios such as showing the buffering progress while the default
3909 * progress shows the play progress.
3910 * <p>
3911 * In order for the progress bar to be shown, the feature must be requested
3912 * via {@link #requestWindowFeature(int)}.
3913 *
3914 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3915 * 0 to 10000 (both inclusive).
3916 */
3917 public final void setSecondaryProgress(int secondaryProgress) {
3918 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3919 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3920 }
3921
3922 /**
3923 * Suggests an audio stream whose volume should be changed by the hardware
3924 * volume controls.
3925 * <p>
3926 * The suggested audio stream will be tied to the window of this Activity.
3927 * If the Activity is switched, the stream set here is no longer the
3928 * suggested stream. The client does not need to save and restore the old
3929 * suggested stream value in onPause and onResume.
3930 *
3931 * @param streamType The type of the audio stream whose volume should be
3932 * changed by the hardware volume controls. It is not guaranteed that
3933 * the hardware volume controls will always change this stream's
3934 * volume (for example, if a call is in progress, its stream's volume
3935 * may be changed instead). To reset back to the default, use
3936 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3937 */
3938 public final void setVolumeControlStream(int streamType) {
3939 getWindow().setVolumeControlStream(streamType);
3940 }
3941
3942 /**
3943 * Gets the suggested audio stream whose volume should be changed by the
3944 * harwdare volume controls.
3945 *
3946 * @return The suggested audio stream type whose volume should be changed by
3947 * the hardware volume controls.
3948 * @see #setVolumeControlStream(int)
3949 */
3950 public final int getVolumeControlStream() {
3951 return getWindow().getVolumeControlStream();
3952 }
3953
3954 /**
3955 * Runs the specified action on the UI thread. If the current thread is the UI
3956 * thread, then the action is executed immediately. If the current thread is
3957 * not the UI thread, the action is posted to the event queue of the UI thread.
3958 *
3959 * @param action the action to run on the UI thread
3960 */
3961 public final void runOnUiThread(Runnable action) {
3962 if (Thread.currentThread() != mUiThread) {
3963 mHandler.post(action);
3964 } else {
3965 action.run();
3966 }
3967 }
3968
3969 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003970 * Standard implementation of
3971 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
3972 * inflating with the LayoutInflater returned by {@link #getSystemService}.
3973 * This implementation handles <fragment> tags to embed fragments inside
3974 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 *
3976 * @see android.view.LayoutInflater#createView
3977 * @see android.view.Window#getLayoutInflater
3978 */
3979 public View onCreateView(String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003980 if (!"fragment".equals(name)) {
3981 return null;
3982 }
3983
3984 TypedArray a =
3985 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
3986 String fname = a.getString(com.android.internal.R.styleable.Fragment_name);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003987 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, 0);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003988 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
3989 a.recycle();
3990
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003991 if (id == 0) {
3992 throw new IllegalArgumentException(attrs.getPositionDescription()
3993 + ": Must specify unique android:id for " + fname);
3994 }
3995
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003996 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003997 // If we restored from a previous state, we may already have
3998 // instantiated this fragment from the state and should use
3999 // that instance instead of making a new one.
4000 Fragment fragment = mFragments.findFragmentById(id);
Dianne Hackborn5ae74d62010-05-19 19:14:57 -07004001 if (FragmentManager.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4002 + Integer.toHexString(id) + " fname=" + fname
4003 + " existing=" + fragment);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004004 if (fragment == null) {
4005 fragment = Fragment.instantiate(this, fname);
4006 fragment.mFromLayout = true;
4007 fragment.mFragmentId = id;
4008 fragment.mTag = tag;
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004009 fragment.mImmediateActivity = this;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004010 mFragments.addFragment(fragment, true);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004011 }
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004012 // If this fragment is newly instantiated (either right now, or
4013 // from last saved state), then give it the attributes to
4014 // initialize itself.
4015 if (!fragment.mRetaining) {
4016 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
4017 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004018 if (fragment.mView == null) {
4019 throw new IllegalStateException("Fragment " + fname
4020 + " did not create a view.");
4021 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004022 fragment.mView.setId(id);
4023 if (fragment.mView.getTag() == null) {
4024 fragment.mView.setTag(tag);
4025 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004026 return fragment.mView;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004027 } catch (Exception e) {
4028 InflateException ie = new InflateException(attrs.getPositionDescription()
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004029 + ": Error inflating fragment " + fname);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004030 ie.initCause(e);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004031 throw ie;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034
Daniel Sandler69a48172010-06-23 16:29:36 -04004035 /**
4036 * Bit indicating that this activity is "immersive" and should not be
4037 * interrupted by notifications if possible.
4038 *
4039 * This value is initially set by the manifest property
4040 * <code>android:immersive</code> but may be changed at runtime by
4041 * {@link #setImmersive}.
4042 *
4043 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4044 */
4045 public boolean isImmersive() {
4046 try {
4047 return ActivityManagerNative.getDefault().isImmersive(mToken);
4048 } catch (RemoteException e) {
4049 return false;
4050 }
4051 }
4052
4053 /**
4054 * Adjust the current immersive mode setting.
4055 *
4056 * Note that changing this value will have no effect on the activity's
4057 * {@link android.content.pm.ActivityInfo} structure; that is, if
4058 * <code>android:immersive</code> is set to <code>true</code>
4059 * in the application's manifest entry for this activity, the {@link
4060 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4061 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4062 * FLAG_IMMERSIVE} bit set.
4063 *
4064 * @see #isImmersive
4065 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4066 */
4067 public void setImmersive(boolean i) {
4068 try {
4069 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4070 } catch (RemoteException e) {
4071 // pass
4072 }
4073 }
4074
Adam Powell6e346362010-07-23 10:18:23 -07004075 /**
4076 * Start a context mode.
4077 *
4078 * @param callback Callback that will manage lifecycle events for this context mode
4079 * @return The ContextMode that was started, or null if it was canceled
4080 *
4081 * @see ActionMode
4082 */
4083 public ActionMode startContextMode(ActionMode.Callback callback) {
4084 return mWindow.getDecorView().startActionMode(callback);
4085 }
4086
4087 public ActionMode onStartActionMode(ActionMode.Callback callback) {
4088 if (mActionBar != null) {
4089 return mActionBar.startContextMode(callback);
4090 }
4091 return null;
4092 }
4093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 // ------------------ Internal API ------------------
4095
4096 final void setParent(Activity parent) {
4097 mParent = parent;
4098 }
4099
4100 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4101 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004102 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004104 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004105 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 }
4107
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004108 final void attach(Context context, ActivityThread aThread,
4109 Instrumentation instr, IBinder token, int ident,
4110 Application application, Intent intent, ActivityInfo info,
4111 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004112 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004113 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 attachBaseContext(context);
4115
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004116 mFragments.attachActivity(this);
4117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 mWindow = PolicyManager.makeNewWindow(this);
4119 mWindow.setCallback(this);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004120 mWindow.getLayoutInflater().setFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4122 mWindow.setSoftInputMode(info.softInputMode);
4123 }
4124 mUiThread = Thread.currentThread();
4125
4126 mMainThread = aThread;
4127 mInstrumentation = instr;
4128 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004129 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 mApplication = application;
4131 mIntent = intent;
4132 mComponent = intent.getComponent();
4133 mActivityInfo = info;
4134 mTitle = title;
4135 mParent = parent;
4136 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004137 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138
4139 mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
4140 if (mParent != null) {
4141 mWindow.setContainer(mParent.getWindow());
4142 }
4143 mWindowManager = mWindow.getWindowManager();
4144 mCurrentConfig = config;
4145 }
4146
4147 final IBinder getActivityToken() {
4148 return mParent != null ? mParent.getActivityToken() : mToken;
4149 }
4150
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004151 final void performCreate(Bundle icicle) {
4152 onCreate(icicle);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004153 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004154 }
4155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 final void performStart() {
4157 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004158 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 mInstrumentation.callActivityOnStart(this);
4160 if (!mCalled) {
4161 throw new SuperNotCalledException(
4162 "Activity " + mComponent.toShortString() +
4163 " did not call through to super.onStart()");
4164 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004165 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004166 if (mAllLoaderManagers != null) {
4167 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4168 mAllLoaderManagers.valueAt(i).finishRetain();
4169 }
4170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 }
4172
4173 final void performRestart() {
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004174 synchronized (mManagedCursors) {
4175 final int N = mManagedCursors.size();
4176 for (int i=0; i<N; i++) {
4177 ManagedCursor mc = mManagedCursors.get(i);
4178 if (mc.mReleased || mc.mUpdated) {
4179 mc.mCursor.requery();
4180 mc.mReleased = false;
4181 mc.mUpdated = false;
4182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184 }
4185
4186 if (mStopped) {
4187 mStopped = false;
4188 mCalled = false;
4189 mInstrumentation.callActivityOnRestart(this);
4190 if (!mCalled) {
4191 throw new SuperNotCalledException(
4192 "Activity " + mComponent.toShortString() +
4193 " did not call through to super.onRestart()");
4194 }
4195 performStart();
4196 }
4197 }
4198
4199 final void performResume() {
4200 performRestart();
4201
Dianne Hackborn445646c2010-06-25 15:52:59 -07004202 mFragments.execPendingActions();
4203
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004204 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205
4206 // First call onResume() -before- setting mResumed, so we don't
4207 // send out any status bar / menu notifications the client makes.
4208 mCalled = false;
4209 mInstrumentation.callActivityOnResume(this);
4210 if (!mCalled) {
4211 throw new SuperNotCalledException(
4212 "Activity " + mComponent.toShortString() +
4213 " did not call through to super.onResume()");
4214 }
4215
4216 // Now really resume, and install the current status bar and menu.
4217 mResumed = true;
4218 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004219
4220 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004221 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 onPostResume();
4224 if (!mCalled) {
4225 throw new SuperNotCalledException(
4226 "Activity " + mComponent.toShortString() +
4227 " did not call through to super.onPostResume()");
4228 }
4229 }
4230
4231 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004232 mFragments.dispatchPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 onPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
4235
4236 final void performUserLeaving() {
4237 onUserInteraction();
4238 onUserLeaveHint();
4239 }
4240
4241 final void performStop() {
Dianne Hackborn2707d602010-07-09 18:01:20 -07004242 if (mStarted) {
4243 mStarted = false;
4244 if (mLoaderManager != null) {
4245 if (!mChangingConfigurations) {
4246 mLoaderManager.doStop();
4247 } else {
4248 mLoaderManager.doRetain();
4249 }
4250 }
4251 }
4252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 if (!mStopped) {
4254 if (mWindow != null) {
4255 mWindow.closeAllPanels();
4256 }
4257
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004258 mFragments.dispatchStop();
4259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 mCalled = false;
4261 mInstrumentation.callActivityOnStop(this);
4262 if (!mCalled) {
4263 throw new SuperNotCalledException(
4264 "Activity " + mComponent.toShortString() +
4265 " did not call through to super.onStop()");
4266 }
4267
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004268 synchronized (mManagedCursors) {
4269 final int N = mManagedCursors.size();
4270 for (int i=0; i<N; i++) {
4271 ManagedCursor mc = mManagedCursors.get(i);
4272 if (!mc.mReleased) {
4273 mc.mCursor.deactivate();
4274 mc.mReleased = true;
4275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 }
4277 }
4278
4279 mStopped = true;
4280 }
4281 mResumed = false;
4282 }
4283
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004284 final void performDestroy() {
4285 mFragments.dispatchDestroy();
4286 onDestroy();
4287 }
4288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 final boolean isResumed() {
4290 return mResumed;
4291 }
4292
4293 void dispatchActivityResult(String who, int requestCode,
4294 int resultCode, Intent data) {
4295 if (Config.LOGV) Log.v(
4296 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4297 + ", resCode=" + resultCode + ", data=" + data);
4298 if (who == null) {
4299 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004300 } else {
4301 Fragment frag = mFragments.findFragmentByWho(who);
4302 if (frag != null) {
4303 frag.onActivityResult(requestCode, resultCode, data);
4304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 }
4306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307}