blob: c55c07fa9a97a0f5e1c4d18b4c8a713fde4545c8 [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 Hackborn5e0d5952010-08-05 13:45:35 -0700638 boolean mCheckedForLoaderManager;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700639 boolean mStarted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 private boolean mResumed;
641 private boolean mStopped;
642 boolean mFinished;
643 boolean mStartedActivity;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500644 /** true if the activity is being destroyed in order to recreate it with a new configuration */
645 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 /*package*/ int mConfigChangeFlags;
647 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100648 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700650 static final class NonConfigurationInstances {
651 Object activity;
652 HashMap<String, Object> children;
653 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700654 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700655 }
656 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 private Window mWindow;
659
660 private WindowManager mWindowManager;
661 /*package*/ View mDecor = null;
662 /*package*/ boolean mWindowAdded = false;
663 /*package*/ boolean mVisibleFromServer = false;
664 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700665 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 private CharSequence mTitle;
668 private int mTitleColor = 0;
669
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700670 final FragmentManager mFragments = new FragmentManager();
671
Dianne Hackborn4911b782010-07-15 12:54:39 -0700672 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
673 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 private static final class ManagedCursor {
676 ManagedCursor(Cursor cursor) {
677 mCursor = cursor;
678 mReleased = false;
679 mUpdated = false;
680 }
681
682 private final Cursor mCursor;
683 private boolean mReleased;
684 private boolean mUpdated;
685 }
686 private final ArrayList<ManagedCursor> mManagedCursors =
687 new ArrayList<ManagedCursor>();
688
689 // protected by synchronized (this)
690 int mResultCode = RESULT_CANCELED;
691 Intent mResultData = null;
692
693 private boolean mTitleReady = false;
694
695 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
696 private SpannableStringBuilder mDefaultKeySsb = null;
697
698 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
699
700 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700701 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702
Carl Shapiro82fe5642010-02-24 00:14:23 -0800703 // Used for debug only
704 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 public Activity() {
706 ++sInstanceCount;
707 }
708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 @Override
710 protected void finalize() throws Throwable {
711 super.finalize();
712 --sInstanceCount;
713 }
Carl Shapiro82fe5642010-02-24 00:14:23 -0800714 */
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 public static long getInstanceCount() {
717 return sInstanceCount;
718 }
719
720 /** Return the intent that started this activity. */
721 public Intent getIntent() {
722 return mIntent;
723 }
724
725 /**
726 * Change the intent returned by {@link #getIntent}. This holds a
727 * reference to the given intent; it does not copy it. Often used in
728 * conjunction with {@link #onNewIntent}.
729 *
730 * @param newIntent The new Intent object to return from getIntent
731 *
732 * @see #getIntent
733 * @see #onNewIntent
734 */
735 public void setIntent(Intent newIntent) {
736 mIntent = newIntent;
737 }
738
739 /** Return the application that owns this activity. */
740 public final Application getApplication() {
741 return mApplication;
742 }
743
744 /** Is this activity embedded inside of another activity? */
745 public final boolean isChild() {
746 return mParent != null;
747 }
748
749 /** Return the parent activity if this view is an embedded child. */
750 public final Activity getParent() {
751 return mParent;
752 }
753
754 /** Retrieve the window manager for showing custom windows. */
755 public WindowManager getWindowManager() {
756 return mWindowManager;
757 }
758
759 /**
760 * Retrieve the current {@link android.view.Window} for the activity.
761 * This can be used to directly access parts of the Window API that
762 * are not available through Activity/Screen.
763 *
764 * @return Window The current window, or null if the activity is not
765 * visual.
766 */
767 public Window getWindow() {
768 return mWindow;
769 }
770
771 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700772 * Return the LoaderManager for this fragment, creating it if needed.
773 */
774 public LoaderManager getLoaderManager() {
775 if (mLoaderManager != null) {
776 return mLoaderManager;
777 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700778 mCheckedForLoaderManager = true;
779 mLoaderManager = getLoaderManager(-1, mStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700780 return mLoaderManager;
781 }
782
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700783 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700784 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700785 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700786 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700787 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700788 if (lm == null && create) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700789 lm = new LoaderManagerImpl(started);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700790 mAllLoaderManagers.put(index, lm);
791 }
792 return lm;
793 }
794
795 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 * Calls {@link android.view.Window#getCurrentFocus} on the
797 * Window of this Activity to return the currently focused view.
798 *
799 * @return View The current View with focus or null.
800 *
801 * @see #getWindow
802 * @see android.view.Window#getCurrentFocus
803 */
804 public View getCurrentFocus() {
805 return mWindow != null ? mWindow.getCurrentFocus() : null;
806 }
807
808 @Override
809 public int getWallpaperDesiredMinimumWidth() {
810 int width = super.getWallpaperDesiredMinimumWidth();
811 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
812 }
813
814 @Override
815 public int getWallpaperDesiredMinimumHeight() {
816 int height = super.getWallpaperDesiredMinimumHeight();
817 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
818 }
819
820 /**
821 * Called when the activity is starting. This is where most initialization
822 * should go: calling {@link #setContentView(int)} to inflate the
823 * activity's UI, using {@link #findViewById} to programmatically interact
824 * with widgets in the UI, calling
825 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
826 * cursors for data being displayed, etc.
827 *
828 * <p>You can call {@link #finish} from within this function, in
829 * which case onDestroy() will be immediately called without any of the rest
830 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
831 * {@link #onPause}, etc) executing.
832 *
833 * <p><em>Derived classes must call through to the super class's
834 * implementation of this method. If they do not, an exception will be
835 * thrown.</em></p>
836 *
837 * @param savedInstanceState If the activity is being re-initialized after
838 * previously being shut down then this Bundle contains the data it most
839 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
840 *
841 * @see #onStart
842 * @see #onSaveInstanceState
843 * @see #onRestoreInstanceState
844 * @see #onPostCreate
845 */
846 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700847 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
848 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700849 if (mLastNonConfigurationInstances != null) {
850 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
851 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700852 if (savedInstanceState != null) {
853 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
854 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
855 ? mLastNonConfigurationInstances.fragments : null);
856 }
857 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 mCalled = true;
859 }
860
861 /**
862 * The hook for {@link ActivityThread} to restore the state of this activity.
863 *
864 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
865 * {@link #restoreManagedDialogs(android.os.Bundle)}.
866 *
867 * @param savedInstanceState contains the saved state
868 */
869 final void performRestoreInstanceState(Bundle savedInstanceState) {
870 onRestoreInstanceState(savedInstanceState);
871 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
873
874 /**
875 * This method is called after {@link #onStart} when the activity is
876 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800877 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 * to restore their state, but it is sometimes convenient to do it here
879 * after all of the initialization has been done or to allow subclasses to
880 * decide whether to use your default implementation. The default
881 * implementation of this method performs a restore of any view state that
882 * had previously been frozen by {@link #onSaveInstanceState}.
883 *
884 * <p>This method is called between {@link #onStart} and
885 * {@link #onPostCreate}.
886 *
887 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
888 *
889 * @see #onCreate
890 * @see #onPostCreate
891 * @see #onResume
892 * @see #onSaveInstanceState
893 */
894 protected void onRestoreInstanceState(Bundle savedInstanceState) {
895 if (mWindow != null) {
896 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
897 if (windowState != null) {
898 mWindow.restoreHierarchyState(windowState);
899 }
900 }
901 }
902
903 /**
904 * Restore the state of any saved managed dialogs.
905 *
906 * @param savedInstanceState The bundle to restore from.
907 */
908 private void restoreManagedDialogs(Bundle savedInstanceState) {
909 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
910 if (b == null) {
911 return;
912 }
913
914 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
915 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800916 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 for (int i = 0; i < numDialogs; i++) {
918 final Integer dialogId = ids[i];
919 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
920 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700921 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
922 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800923 final ManagedDialog md = new ManagedDialog();
924 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
925 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
926 if (md.mDialog != null) {
927 mManagedDialogs.put(dialogId, md);
928 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
929 md.mDialog.onRestoreInstanceState(dialogState);
930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932 }
933 }
934
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800935 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
936 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700937 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800938 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700939 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700940 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700941 return dialog;
942 }
943
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800944 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 return SAVED_DIALOG_KEY_PREFIX + key;
946 }
947
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800948 private static String savedDialogArgsKeyFor(int key) {
949 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951
952 /**
953 * Called when activity start-up is complete (after {@link #onStart}
954 * and {@link #onRestoreInstanceState} have been called). Applications will
955 * generally not implement this method; it is intended for system
956 * classes to do final initialization after application code has run.
957 *
958 * <p><em>Derived classes must call through to the super class's
959 * implementation of this method. If they do not, an exception will be
960 * thrown.</em></p>
961 *
962 * @param savedInstanceState If the activity is being re-initialized after
963 * previously being shut down then this Bundle contains the data it most
964 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
965 * @see #onCreate
966 */
967 protected void onPostCreate(Bundle savedInstanceState) {
968 if (!isChild()) {
969 mTitleReady = true;
970 onTitleChanged(getTitle(), getTitleColor());
971 }
Adam Powell96675b12010-06-10 18:58:59 -0700972 if (mWindow != null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
973 // Invalidate the action bar menu so that it can initialize properly.
974 mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 mCalled = true;
977 }
978
979 /**
980 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
981 * the activity had been stopped, but is now again being displayed to the
982 * user. It will be followed by {@link #onResume}.
983 *
984 * <p><em>Derived classes must call through to the super class's
985 * implementation of this method. If they do not, an exception will be
986 * thrown.</em></p>
987 *
988 * @see #onCreate
989 * @see #onStop
990 * @see #onResume
991 */
992 protected void onStart() {
993 mCalled = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700994 mStarted = true;
995 if (mLoaderManager != null) {
996 mLoaderManager.doStart();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700997 } else if (!mCheckedForLoaderManager) {
998 mLoaderManager = getLoaderManager(-1, mStarted, false);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700999 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001000 mCheckedForLoaderManager = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002
1003 /**
1004 * Called after {@link #onStop} when the current activity is being
1005 * re-displayed to the user (the user has navigated back to it). It will
1006 * be followed by {@link #onStart} and then {@link #onResume}.
1007 *
1008 * <p>For activities that are using raw {@link Cursor} objects (instead of
1009 * creating them through
1010 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1011 * this is usually the place
1012 * where the cursor should be requeried (because you had deactivated it in
1013 * {@link #onStop}.
1014 *
1015 * <p><em>Derived classes must call through to the super class's
1016 * implementation of this method. If they do not, an exception will be
1017 * thrown.</em></p>
1018 *
1019 * @see #onStop
1020 * @see #onStart
1021 * @see #onResume
1022 */
1023 protected void onRestart() {
1024 mCalled = true;
1025 }
1026
1027 /**
1028 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1029 * {@link #onPause}, for your activity to start interacting with the user.
1030 * This is a good place to begin animations, open exclusive-access devices
1031 * (such as the camera), etc.
1032 *
1033 * <p>Keep in mind that onResume is not the best indicator that your activity
1034 * is visible to the user; a system window such as the keyguard may be in
1035 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1036 * activity is visible to the user (for example, to resume a game).
1037 *
1038 * <p><em>Derived classes must call through to the super class's
1039 * implementation of this method. If they do not, an exception will be
1040 * thrown.</em></p>
1041 *
1042 * @see #onRestoreInstanceState
1043 * @see #onRestart
1044 * @see #onPostResume
1045 * @see #onPause
1046 */
1047 protected void onResume() {
1048 mCalled = true;
1049 }
1050
1051 /**
1052 * Called when activity resume is complete (after {@link #onResume} has
1053 * been called). Applications will generally not implement this method;
1054 * it is intended for system classes to do final setup after application
1055 * resume code has run.
1056 *
1057 * <p><em>Derived classes must call through to the super class's
1058 * implementation of this method. If they do not, an exception will be
1059 * thrown.</em></p>
1060 *
1061 * @see #onResume
1062 */
1063 protected void onPostResume() {
1064 final Window win = getWindow();
1065 if (win != null) win.makeActive();
1066 mCalled = true;
1067 }
1068
1069 /**
1070 * This is called for activities that set launchMode to "singleTop" in
1071 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1072 * flag when calling {@link #startActivity}. In either case, when the
1073 * activity is re-launched while at the top of the activity stack instead
1074 * of a new instance of the activity being started, onNewIntent() will be
1075 * called on the existing instance with the Intent that was used to
1076 * re-launch it.
1077 *
1078 * <p>An activity will always be paused before receiving a new intent, so
1079 * you can count on {@link #onResume} being called after this method.
1080 *
1081 * <p>Note that {@link #getIntent} still returns the original Intent. You
1082 * can use {@link #setIntent} to update it to this new Intent.
1083 *
1084 * @param intent The new intent that was started for the activity.
1085 *
1086 * @see #getIntent
1087 * @see #setIntent
1088 * @see #onResume
1089 */
1090 protected void onNewIntent(Intent intent) {
1091 }
1092
1093 /**
1094 * The hook for {@link ActivityThread} to save the state of this activity.
1095 *
1096 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1097 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1098 *
1099 * @param outState The bundle to save the state to.
1100 */
1101 final void performSaveInstanceState(Bundle outState) {
1102 onSaveInstanceState(outState);
1103 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105
1106 /**
1107 * Called to retrieve per-instance state from an activity before being killed
1108 * so that the state can be restored in {@link #onCreate} or
1109 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1110 * will be passed to both).
1111 *
1112 * <p>This method is called before an activity may be killed so that when it
1113 * comes back some time in the future it can restore its state. For example,
1114 * if activity B is launched in front of activity A, and at some point activity
1115 * A is killed to reclaim resources, activity A will have a chance to save the
1116 * current state of its user interface via this method so that when the user
1117 * returns to activity A, the state of the user interface can be restored
1118 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1119 *
1120 * <p>Do not confuse this method with activity lifecycle callbacks such as
1121 * {@link #onPause}, which is always called when an activity is being placed
1122 * in the background or on its way to destruction, or {@link #onStop} which
1123 * is called before destruction. One example of when {@link #onPause} and
1124 * {@link #onStop} is called and not this method is when a user navigates back
1125 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1126 * on B because that particular instance will never be restored, so the
1127 * system avoids calling it. An example when {@link #onPause} is called and
1128 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1129 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1130 * killed during the lifetime of B since the state of the user interface of
1131 * A will stay intact.
1132 *
1133 * <p>The default implementation takes care of most of the UI per-instance
1134 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1135 * view in the hierarchy that has an id, and by saving the id of the currently
1136 * focused view (all of which is restored by the default implementation of
1137 * {@link #onRestoreInstanceState}). If you override this method to save additional
1138 * information not captured by each individual view, you will likely want to
1139 * call through to the default implementation, otherwise be prepared to save
1140 * all of the state of each view yourself.
1141 *
1142 * <p>If called, this method will occur before {@link #onStop}. There are
1143 * no guarantees about whether it will occur before or after {@link #onPause}.
1144 *
1145 * @param outState Bundle in which to place your saved state.
1146 *
1147 * @see #onCreate
1148 * @see #onRestoreInstanceState
1149 * @see #onPause
1150 */
1151 protected void onSaveInstanceState(Bundle outState) {
1152 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001153 Parcelable p = mFragments.saveAllState();
1154 if (p != null) {
1155 outState.putParcelable(FRAGMENTS_TAG, p);
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158
1159 /**
1160 * Save the state of any managed dialogs.
1161 *
1162 * @param outState place to store the saved state.
1163 */
1164 private void saveManagedDialogs(Bundle outState) {
1165 if (mManagedDialogs == null) {
1166 return;
1167 }
1168
1169 final int numDialogs = mManagedDialogs.size();
1170 if (numDialogs == 0) {
1171 return;
1172 }
1173
1174 Bundle dialogState = new Bundle();
1175
1176 int[] ids = new int[mManagedDialogs.size()];
1177
1178 // save each dialog's bundle, gather the ids
1179 for (int i = 0; i < numDialogs; i++) {
1180 final int key = mManagedDialogs.keyAt(i);
1181 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001182 final ManagedDialog md = mManagedDialogs.valueAt(i);
1183 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1184 if (md.mArgs != null) {
1185 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188
1189 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1190 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1191 }
1192
1193
1194 /**
1195 * Called as part of the activity lifecycle when an activity is going into
1196 * the background, but has not (yet) been killed. The counterpart to
1197 * {@link #onResume}.
1198 *
1199 * <p>When activity B is launched in front of activity A, this callback will
1200 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1201 * so be sure to not do anything lengthy here.
1202 *
1203 * <p>This callback is mostly used for saving any persistent state the
1204 * activity is editing, to present a "edit in place" model to the user and
1205 * making sure nothing is lost if there are not enough resources to start
1206 * the new activity without first killing this one. This is also a good
1207 * place to do things like stop animations and other things that consume a
1208 * noticeable mount of CPU in order to make the switch to the next activity
1209 * as fast as possible, or to close resources that are exclusive access
1210 * such as the camera.
1211 *
1212 * <p>In situations where the system needs more memory it may kill paused
1213 * processes to reclaim resources. Because of this, you should be sure
1214 * that all of your state is saved by the time you return from
1215 * this function. In general {@link #onSaveInstanceState} is used to save
1216 * per-instance state in the activity and this method is used to store
1217 * global persistent data (in content providers, files, etc.)
1218 *
1219 * <p>After receiving this call you will usually receive a following call
1220 * to {@link #onStop} (after the next activity has been resumed and
1221 * displayed), however in some cases there will be a direct call back to
1222 * {@link #onResume} without going through the stopped state.
1223 *
1224 * <p><em>Derived classes must call through to the super class's
1225 * implementation of this method. If they do not, an exception will be
1226 * thrown.</em></p>
1227 *
1228 * @see #onResume
1229 * @see #onSaveInstanceState
1230 * @see #onStop
1231 */
1232 protected void onPause() {
1233 mCalled = true;
1234 }
1235
1236 /**
1237 * Called as part of the activity lifecycle when an activity is about to go
1238 * into the background as the result of user choice. For example, when the
1239 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1240 * when an incoming phone call causes the in-call Activity to be automatically
1241 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1242 * the activity being interrupted. In cases when it is invoked, this method
1243 * is called right before the activity's {@link #onPause} callback.
1244 *
1245 * <p>This callback and {@link #onUserInteraction} are intended to help
1246 * activities manage status bar notifications intelligently; specifically,
1247 * for helping activities determine the proper time to cancel a notfication.
1248 *
1249 * @see #onUserInteraction()
1250 */
1251 protected void onUserLeaveHint() {
1252 }
1253
1254 /**
1255 * Generate a new thumbnail for this activity. This method is called before
1256 * pausing the activity, and should draw into <var>outBitmap</var> the
1257 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1258 * can use the given <var>canvas</var>, which is configured to draw into the
1259 * bitmap, for rendering if desired.
1260 *
1261 * <p>The default implementation renders the Screen's current view
1262 * hierarchy into the canvas to generate a thumbnail.
1263 *
1264 * <p>If you return false, the bitmap will be filled with a default
1265 * thumbnail.
1266 *
1267 * @param outBitmap The bitmap to contain the thumbnail.
1268 * @param canvas Can be used to render into the bitmap.
1269 *
1270 * @return Return true if you have drawn into the bitmap; otherwise after
1271 * you return it will be filled with a default thumbnail.
1272 *
1273 * @see #onCreateDescription
1274 * @see #onSaveInstanceState
1275 * @see #onPause
1276 */
1277 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Jim Miller0b2a6d02010-07-13 18:01:29 -07001278 if (mDecor == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 return false;
1280 }
1281
Jim Miller0b2a6d02010-07-13 18:01:29 -07001282 int paddingLeft = 0;
1283 int paddingRight = 0;
1284 int paddingTop = 0;
1285 int paddingBottom = 0;
1286
1287 // Find System window and use padding so we ignore space reserved for decorations
1288 // like the status bar and such.
1289 final FrameLayout top = (FrameLayout) mDecor;
1290 for (int i = 0; i < top.getChildCount(); i++) {
1291 View child = top.getChildAt(i);
1292 if (child.isFitsSystemWindowsFlagSet()) {
1293 paddingLeft = child.getPaddingLeft();
1294 paddingRight = child.getPaddingRight();
1295 paddingTop = child.getPaddingTop();
1296 paddingBottom = child.getPaddingBottom();
1297 break;
1298 }
1299 }
1300
1301 final int visibleWidth = mDecor.getWidth() - paddingLeft - paddingRight;
1302 final int visibleHeight = mDecor.getHeight() - paddingTop - paddingBottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303
1304 canvas.save();
Jim Miller0b2a6d02010-07-13 18:01:29 -07001305 canvas.scale( (float) outBitmap.getWidth() / visibleWidth,
1306 (float) outBitmap.getHeight() / visibleHeight);
1307 canvas.translate(-paddingLeft, -paddingTop);
1308 mDecor.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 canvas.restore();
1310
1311 return true;
1312 }
1313
1314 /**
1315 * Generate a new description for this activity. This method is called
1316 * before pausing the activity and can, if desired, return some textual
1317 * description of its current state to be displayed to the user.
1318 *
1319 * <p>The default implementation returns null, which will cause you to
1320 * inherit the description from the previous activity. If all activities
1321 * return null, generally the label of the top activity will be used as the
1322 * description.
1323 *
1324 * @return A description of what the user is doing. It should be short and
1325 * sweet (only a few words).
1326 *
1327 * @see #onCreateThumbnail
1328 * @see #onSaveInstanceState
1329 * @see #onPause
1330 */
1331 public CharSequence onCreateDescription() {
1332 return null;
1333 }
1334
1335 /**
1336 * Called when you are no longer visible to the user. You will next
1337 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1338 * depending on later user activity.
1339 *
1340 * <p>Note that this method may never be called, in low memory situations
1341 * where the system does not have enough memory to keep your activity's
1342 * process running after its {@link #onPause} method is called.
1343 *
1344 * <p><em>Derived classes must call through to the super class's
1345 * implementation of this method. If they do not, an exception will be
1346 * thrown.</em></p>
1347 *
1348 * @see #onRestart
1349 * @see #onResume
1350 * @see #onSaveInstanceState
1351 * @see #onDestroy
1352 */
1353 protected void onStop() {
1354 mCalled = true;
1355 }
1356
1357 /**
1358 * Perform any final cleanup before an activity is destroyed. This can
1359 * happen either because the activity is finishing (someone called
1360 * {@link #finish} on it, or because the system is temporarily destroying
1361 * this instance of the activity to save space. You can distinguish
1362 * between these two scenarios with the {@link #isFinishing} method.
1363 *
1364 * <p><em>Note: do not count on this method being called as a place for
1365 * saving data! For example, if an activity is editing data in a content
1366 * provider, those edits should be committed in either {@link #onPause} or
1367 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1368 * free resources like threads that are associated with an activity, so
1369 * that a destroyed activity does not leave such things around while the
1370 * rest of its application is still running. There are situations where
1371 * the system will simply kill the activity's hosting process without
1372 * calling this method (or any others) in it, so it should not be used to
1373 * do things that are intended to remain around after the process goes
1374 * away.
1375 *
1376 * <p><em>Derived classes must call through to the super class's
1377 * implementation of this method. If they do not, an exception will be
1378 * thrown.</em></p>
1379 *
1380 * @see #onPause
1381 * @see #onStop
1382 * @see #finish
1383 * @see #isFinishing
1384 */
1385 protected void onDestroy() {
1386 mCalled = true;
1387
1388 // dismiss any dialogs we are managing.
1389 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 final int numDialogs = mManagedDialogs.size();
1391 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001392 final ManagedDialog md = mManagedDialogs.valueAt(i);
1393 if (md.mDialog.isShowing()) {
1394 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001397 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399
1400 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001401 synchronized (mManagedCursors) {
1402 int numCursors = mManagedCursors.size();
1403 for (int i = 0; i < numCursors; i++) {
1404 ManagedCursor c = mManagedCursors.get(i);
1405 if (c != null) {
1406 c.mCursor.close();
1407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001409 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
Amith Yamasani49860442010-03-17 20:54:10 -07001411
1412 // Close any open search dialog
1413 if (mSearchManager != null) {
1414 mSearchManager.stopSearch();
1415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
1418 /**
1419 * Called by the system when the device configuration changes while your
1420 * activity is running. Note that this will <em>only</em> be called if
1421 * you have selected configurations you would like to handle with the
1422 * {@link android.R.attr#configChanges} attribute in your manifest. If
1423 * any configuration change occurs that is not selected to be reported
1424 * by that attribute, then instead of reporting it the system will stop
1425 * and restart the activity (to have it launched with the new
1426 * configuration).
1427 *
1428 * <p>At the time that this function has been called, your Resources
1429 * object will have been updated to return resource values matching the
1430 * new configuration.
1431 *
1432 * @param newConfig The new device configuration.
1433 */
1434 public void onConfigurationChanged(Configuration newConfig) {
1435 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (mWindow != null) {
1438 // Pass the configuration changed event to the window
1439 mWindow.onConfigurationChanged(newConfig);
1440 }
1441 }
1442
1443 /**
1444 * If this activity is being destroyed because it can not handle a
1445 * configuration parameter being changed (and thus its
1446 * {@link #onConfigurationChanged(Configuration)} method is
1447 * <em>not</em> being called), then you can use this method to discover
1448 * the set of changes that have occurred while in the process of being
1449 * destroyed. Note that there is no guarantee that these will be
1450 * accurate (other changes could have happened at any time), so you should
1451 * only use this as an optimization hint.
1452 *
1453 * @return Returns a bit field of the configuration parameters that are
1454 * changing, as defined by the {@link android.content.res.Configuration}
1455 * class.
1456 */
1457 public int getChangingConfigurations() {
1458 return mConfigChangeFlags;
1459 }
1460
1461 /**
1462 * Retrieve the non-configuration instance data that was previously
1463 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1464 * be available from the initial {@link #onCreate} and
1465 * {@link #onStart} calls to the new instance, allowing you to extract
1466 * any useful dynamic state from the previous instance.
1467 *
1468 * <p>Note that the data you retrieve here should <em>only</em> be used
1469 * as an optimization for handling configuration changes. You should always
1470 * be able to handle getting a null pointer back, and an activity must
1471 * still be able to restore itself to its previous state (through the
1472 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1473 * function returns null.
1474 *
1475 * @return Returns the object previously returned by
1476 * {@link #onRetainNonConfigurationInstance()}.
1477 */
1478 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001479 return mLastNonConfigurationInstances != null
1480 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482
1483 /**
1484 * Called by the system, as part of destroying an
1485 * activity due to a configuration change, when it is known that a new
1486 * instance will immediately be created for the new configuration. You
1487 * can return any object you like here, including the activity instance
1488 * itself, which can later be retrieved by calling
1489 * {@link #getLastNonConfigurationInstance()} in the new activity
1490 * instance.
1491 *
1492 * <p>This function is called purely as an optimization, and you must
1493 * not rely on it being called. When it is called, a number of guarantees
1494 * will be made to help optimize configuration switching:
1495 * <ul>
1496 * <li> The function will be called between {@link #onStop} and
1497 * {@link #onDestroy}.
1498 * <li> A new instance of the activity will <em>always</em> be immediately
1499 * created after this one's {@link #onDestroy()} is called.
1500 * <li> The object you return here will <em>always</em> be available from
1501 * the {@link #getLastNonConfigurationInstance()} method of the following
1502 * activity instance as described there.
1503 * </ul>
1504 *
1505 * <p>These guarantees are designed so that an activity can use this API
1506 * to propagate extensive state from the old to new activity instance, from
1507 * loaded bitmaps, to network connections, to evenly actively running
1508 * threads. Note that you should <em>not</em> propagate any data that
1509 * may change based on the configuration, including any data loaded from
1510 * resources such as strings, layouts, or drawables.
1511 *
1512 * @return Return any Object holding the desired state to propagate to the
1513 * next activity instance.
1514 */
1515 public Object onRetainNonConfigurationInstance() {
1516 return null;
1517 }
1518
1519 /**
1520 * Retrieve the non-configuration instance data that was previously
1521 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1522 * be available from the initial {@link #onCreate} and
1523 * {@link #onStart} calls to the new instance, allowing you to extract
1524 * any useful dynamic state from the previous instance.
1525 *
1526 * <p>Note that the data you retrieve here should <em>only</em> be used
1527 * as an optimization for handling configuration changes. You should always
1528 * be able to handle getting a null pointer back, and an activity must
1529 * still be able to restore itself to its previous state (through the
1530 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1531 * function returns null.
1532 *
1533 * @return Returns the object previously returned by
1534 * {@link #onRetainNonConfigurationChildInstances()}
1535 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001536 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1537 return mLastNonConfigurationInstances != null
1538 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
1541 /**
1542 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1543 * it should return either a mapping from child activity id strings to arbitrary objects,
1544 * or null. This method is intended to be used by Activity framework subclasses that control a
1545 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1546 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1547 */
1548 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1549 return null;
1550 }
1551
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001552 NonConfigurationInstances retainNonConfigurationInstances() {
1553 Object activity = onRetainNonConfigurationInstance();
1554 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1555 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001556 boolean retainLoaders = false;
1557 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001558 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001559 // have nothing useful to retain.
1560 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001561 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001562 if (lm.mRetaining) {
1563 retainLoaders = true;
1564 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001565 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001566 mAllLoaderManagers.removeAt(i);
1567 }
1568 }
1569 }
1570 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001571 return null;
1572 }
1573
1574 NonConfigurationInstances nci = new NonConfigurationInstances();
1575 nci.activity = activity;
1576 nci.children = children;
1577 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001578 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001579 return nci;
1580 }
1581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 public void onLowMemory() {
1583 mCalled = true;
1584 }
1585
1586 /**
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001587 * Start a series of edit operations on the Fragments associated with
1588 * this activity.
1589 */
1590 public FragmentTransaction openFragmentTransaction() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001591 return new BackStackEntry(mFragments);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001592 }
1593
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001594 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001595 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001596 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001597 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1598 if (lm != null) {
1599 lm.doDestroy();
1600 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001601 mAllLoaderManagers.remove(index);
1602 }
1603 }
1604
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001605 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001606 * Called when a Fragment is being attached to this activity, immediately
1607 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1608 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1609 */
1610 public void onAttachFragment(Fragment fragment) {
1611 }
1612
1613 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 * Wrapper around
1615 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1616 * that gives the resulting {@link Cursor} to call
1617 * {@link #startManagingCursor} so that the activity will manage its
1618 * lifecycle for you.
1619 *
1620 * @param uri The URI of the content provider to query.
1621 * @param projection List of columns to return.
1622 * @param selection SQL WHERE clause.
1623 * @param sortOrder SQL ORDER BY clause.
1624 *
1625 * @return The Cursor that was returned by query().
1626 *
1627 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1628 * @see #startManagingCursor
1629 * @hide
1630 */
1631 public final Cursor managedQuery(Uri uri,
1632 String[] projection,
1633 String selection,
1634 String sortOrder)
1635 {
1636 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1637 if (c != null) {
1638 startManagingCursor(c);
1639 }
1640 return c;
1641 }
1642
1643 /**
1644 * Wrapper around
1645 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1646 * that gives the resulting {@link Cursor} to call
1647 * {@link #startManagingCursor} so that the activity will manage its
1648 * lifecycle for you.
1649 *
1650 * @param uri The URI of the content provider to query.
1651 * @param projection List of columns to return.
1652 * @param selection SQL WHERE clause.
1653 * @param selectionArgs The arguments to selection, if any ?s are pesent
1654 * @param sortOrder SQL ORDER BY clause.
1655 *
1656 * @return The Cursor that was returned by query().
1657 *
1658 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1659 * @see #startManagingCursor
1660 */
1661 public final Cursor managedQuery(Uri uri,
1662 String[] projection,
1663 String selection,
1664 String[] selectionArgs,
1665 String sortOrder)
1666 {
1667 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1668 if (c != null) {
1669 startManagingCursor(c);
1670 }
1671 return c;
1672 }
1673
1674 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 * This method allows the activity to take care of managing the given
1676 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1677 * That is, when the activity is stopped it will automatically call
1678 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1679 * it will call {@link Cursor#requery} for you. When the activity is
1680 * destroyed, all managed Cursors will be closed automatically.
1681 *
1682 * @param c The Cursor to be managed.
1683 *
1684 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1685 * @see #stopManagingCursor
1686 */
1687 public void startManagingCursor(Cursor c) {
1688 synchronized (mManagedCursors) {
1689 mManagedCursors.add(new ManagedCursor(c));
1690 }
1691 }
1692
1693 /**
1694 * Given a Cursor that was previously given to
1695 * {@link #startManagingCursor}, stop the activity's management of that
1696 * cursor.
1697 *
1698 * @param c The Cursor that was being managed.
1699 *
1700 * @see #startManagingCursor
1701 */
1702 public void stopManagingCursor(Cursor c) {
1703 synchronized (mManagedCursors) {
1704 final int N = mManagedCursors.size();
1705 for (int i=0; i<N; i++) {
1706 ManagedCursor mc = mManagedCursors.get(i);
1707 if (mc.mCursor == c) {
1708 mManagedCursors.remove(i);
1709 break;
1710 }
1711 }
1712 }
1713 }
1714
1715 /**
1716 * Control whether this activity is required to be persistent. By default
1717 * activities are not persistent; setting this to true will prevent the
1718 * system from stopping this activity or its process when running low on
1719 * resources.
1720 *
1721 * <p><em>You should avoid using this method</em>, it has severe negative
1722 * consequences on how well the system can manage its resources. A better
1723 * approach is to implement an application service that you control with
1724 * {@link Context#startService} and {@link Context#stopService}.
1725 *
1726 * @param isPersistent Control whether the current activity must be
1727 * persistent, true if so, false for the normal
1728 * behavior.
1729 */
1730 public void setPersistent(boolean isPersistent) {
1731 if (mParent == null) {
1732 try {
1733 ActivityManagerNative.getDefault()
1734 .setPersistent(mToken, isPersistent);
1735 } catch (RemoteException e) {
1736 // Empty
1737 }
1738 } else {
1739 throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1740 }
1741 }
1742
1743 /**
1744 * Finds a view that was identified by the id attribute from the XML that
1745 * was processed in {@link #onCreate}.
1746 *
1747 * @return The view if found or null otherwise.
1748 */
1749 public View findViewById(int id) {
1750 return getWindow().findViewById(id);
1751 }
Adam Powell33b97432010-04-20 10:01:14 -07001752
1753 /**
1754 * Retrieve a reference to this activity's ActionBar.
1755 *
1756 * <p><em>Note:</em> The ActionBar is initialized when a content view
1757 * is set. This function will return null if called before {@link #setContentView}
1758 * or {@link #addContentView}.
1759 * @return The Activity's ActionBar, or null if it does not have one.
1760 */
1761 public ActionBar getActionBar() {
1762 return mActionBar;
1763 }
1764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 /**
Adam Powell33b97432010-04-20 10:01:14 -07001766 * Creates a new ActionBar, locates the inflated ActionBarView,
1767 * initializes the ActionBar with the view, and sets mActionBar.
1768 */
1769 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001770 Window window = getWindow();
Adam Powell661c9082010-07-02 10:09:44 -07001771 if (!window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001772 return;
1773 }
1774
Adam Powell661c9082010-07-02 10:09:44 -07001775 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001776 }
1777
1778 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001779 * Finds a fragment that was identified by the given id either when inflated
1780 * from XML or as the container ID when added in a transaction. This only
1781 * returns fragments that are currently added to the activity's content.
1782 * @return The fragment if found or null otherwise.
1783 */
1784 public Fragment findFragmentById(int id) {
1785 return mFragments.findFragmentById(id);
1786 }
1787
1788 /**
1789 * Finds a fragment that was identified by the given tag either when inflated
1790 * from XML or as supplied when added in a transaction. This only
1791 * returns fragments that are currently added to the activity's content.
1792 * @return The fragment if found or null otherwise.
1793 */
1794 public Fragment findFragmentByTag(String tag) {
1795 return mFragments.findFragmentByTag(tag);
1796 }
1797
1798 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 * Set the activity content from a layout resource. The resource will be
1800 * inflated, adding all top-level views to the activity.
1801 *
1802 * @param layoutResID Resource ID to be inflated.
1803 */
1804 public void setContentView(int layoutResID) {
1805 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001806 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808
1809 /**
1810 * Set the activity content to an explicit view. This view is placed
1811 * directly into the activity's view hierarchy. It can itself be a complex
1812 * view hierarhcy.
1813 *
1814 * @param view The desired content to display.
1815 */
1816 public void setContentView(View view) {
1817 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001818 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
1820
1821 /**
1822 * Set the activity content to an explicit view. This view is placed
1823 * directly into the activity's view hierarchy. It can itself be a complex
1824 * view hierarhcy.
1825 *
1826 * @param view The desired content to display.
1827 * @param params Layout parameters for the view.
1828 */
1829 public void setContentView(View view, ViewGroup.LayoutParams params) {
1830 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001831 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
1833
1834 /**
1835 * Add an additional content view to the activity. Added after any existing
1836 * ones in the activity -- existing views are NOT removed.
1837 *
1838 * @param view The desired content to display.
1839 * @param params Layout parameters for the view.
1840 */
1841 public void addContentView(View view, ViewGroup.LayoutParams params) {
1842 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001843 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845
1846 /**
1847 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1848 * keys.
1849 *
1850 * @see #setDefaultKeyMode
1851 */
1852 static public final int DEFAULT_KEYS_DISABLE = 0;
1853 /**
1854 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1855 * key handling.
1856 *
1857 * @see #setDefaultKeyMode
1858 */
1859 static public final int DEFAULT_KEYS_DIALER = 1;
1860 /**
1861 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1862 * default key handling.
1863 *
1864 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1865 *
1866 * @see #setDefaultKeyMode
1867 */
1868 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1869 /**
1870 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1871 * will start an application-defined search. (If the application or activity does not
1872 * actually define a search, the the keys will be ignored.)
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_LOCAL = 3;
1879
1880 /**
1881 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1882 * will start a global search (typically web search, but some platforms may define alternate
1883 * methods for global search)
1884 *
1885 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1886 *
1887 * @see #setDefaultKeyMode
1888 */
1889 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1890
1891 /**
1892 * Select the default key handling for this activity. This controls what
1893 * will happen to key events that are not otherwise handled. The default
1894 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1895 * floor. Other modes allow you to launch the dialer
1896 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1897 * menu without requiring the menu key be held down
1898 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1899 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1900 *
1901 * <p>Note that the mode selected here does not impact the default
1902 * handling of system keys, such as the "back" and "menu" keys, and your
1903 * activity and its views always get a first chance to receive and handle
1904 * all application keys.
1905 *
1906 * @param mode The desired default key mode constant.
1907 *
1908 * @see #DEFAULT_KEYS_DISABLE
1909 * @see #DEFAULT_KEYS_DIALER
1910 * @see #DEFAULT_KEYS_SHORTCUT
1911 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1912 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1913 * @see #onKeyDown
1914 */
1915 public final void setDefaultKeyMode(int mode) {
1916 mDefaultKeyMode = mode;
1917
1918 // Some modes use a SpannableStringBuilder to track & dispatch input events
1919 // This list must remain in sync with the switch in onKeyDown()
1920 switch (mode) {
1921 case DEFAULT_KEYS_DISABLE:
1922 case DEFAULT_KEYS_SHORTCUT:
1923 mDefaultKeySsb = null; // not used in these modes
1924 break;
1925 case DEFAULT_KEYS_DIALER:
1926 case DEFAULT_KEYS_SEARCH_LOCAL:
1927 case DEFAULT_KEYS_SEARCH_GLOBAL:
1928 mDefaultKeySsb = new SpannableStringBuilder();
1929 Selection.setSelection(mDefaultKeySsb,0);
1930 break;
1931 default:
1932 throw new IllegalArgumentException();
1933 }
1934 }
1935
1936 /**
1937 * Called when a key was pressed down and not handled by any of the views
1938 * inside of the activity. So, for example, key presses while the cursor
1939 * is inside a TextView will not trigger the event (unless it is a navigation
1940 * to another object) because TextView handles its own key presses.
1941 *
1942 * <p>If the focused view didn't want this event, this method is called.
1943 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001944 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1945 * by calling {@link #onBackPressed()}, though the behavior varies based
1946 * on the application compatibility mode: for
1947 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1948 * it will set up the dispatch to call {@link #onKeyUp} where the action
1949 * will be performed; for earlier applications, it will perform the
1950 * action immediately in on-down, as those versions of the platform
1951 * behaved.
1952 *
1953 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001954 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 *
1956 * @return Return <code>true</code> to prevent this event from being propagated
1957 * further, or <code>false</code> to indicate that you have not handled
1958 * this event and it should continue to be propagated.
1959 * @see #onKeyUp
1960 * @see android.view.KeyEvent
1961 */
1962 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001963 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001964 if (getApplicationInfo().targetSdkVersion
1965 >= Build.VERSION_CODES.ECLAIR) {
1966 event.startTracking();
1967 } else {
1968 onBackPressed();
1969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 return true;
1971 }
1972
1973 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1974 return false;
1975 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001976 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1977 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1978 return true;
1979 }
1980 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 } else {
1982 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1983 boolean clearSpannable = false;
1984 boolean handled;
1985 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1986 clearSpannable = true;
1987 handled = false;
1988 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001989 handled = TextKeyListener.getInstance().onKeyDown(
1990 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if (handled && mDefaultKeySsb.length() > 0) {
1992 // something useable has been typed - dispatch it now.
1993
1994 final String str = mDefaultKeySsb.toString();
1995 clearSpannable = true;
1996
1997 switch (mDefaultKeyMode) {
1998 case DEFAULT_KEYS_DIALER:
1999 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2000 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2001 startActivity(intent);
2002 break;
2003 case DEFAULT_KEYS_SEARCH_LOCAL:
2004 startSearch(str, false, null, false);
2005 break;
2006 case DEFAULT_KEYS_SEARCH_GLOBAL:
2007 startSearch(str, false, null, true);
2008 break;
2009 }
2010 }
2011 }
2012 if (clearSpannable) {
2013 mDefaultKeySsb.clear();
2014 mDefaultKeySsb.clearSpans();
2015 Selection.setSelection(mDefaultKeySsb,0);
2016 }
2017 return handled;
2018 }
2019 }
2020
2021 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002022 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2023 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2024 * the event).
2025 */
2026 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2027 return false;
2028 }
2029
2030 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 * Called when a key was released and not handled by any of the views
2032 * inside of the activity. So, for example, key presses while the cursor
2033 * is inside a TextView will not trigger the event (unless it is a navigation
2034 * to another object) because TextView handles its own key presses.
2035 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002036 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2037 * and go back.
2038 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 * @return Return <code>true</code> to prevent this event from being propagated
2040 * further, or <code>false</code> to indicate that you have not handled
2041 * this event and it should continue to be propagated.
2042 * @see #onKeyDown
2043 * @see KeyEvent
2044 */
2045 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002046 if (getApplicationInfo().targetSdkVersion
2047 >= Build.VERSION_CODES.ECLAIR) {
2048 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2049 && !event.isCanceled()) {
2050 onBackPressed();
2051 return true;
2052 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 return false;
2055 }
2056
2057 /**
2058 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2059 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2060 * the event).
2061 */
2062 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2063 return false;
2064 }
2065
2066 /**
Dianne Hackborndd913a52010-07-22 12:17:04 -07002067 * Flag for {@link #popBackStack(String, int)}
2068 * and {@link #popBackStack(int, int)}: If set, and the name or ID of
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -07002069 * a back stack entry has been supplied, then all matching entries will
2070 * be consumed until one that doesn't match is found or the bottom of
2071 * the stack is reached. Otherwise, all entries up to but not including that entry
2072 * will be removed.
Dianne Hackborndd913a52010-07-22 12:17:04 -07002073 */
Jean-Baptiste Queru005cb6d2010-07-27 10:54:51 -07002074 public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
Dianne Hackborndd913a52010-07-22 12:17:04 -07002075
2076 /**
2077 * Pop the top state off the back stack. Returns true if there was one
2078 * to pop, else false.
2079 */
2080 public boolean popBackStack() {
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -07002081 return popBackStack(null, -1);
Dianne Hackborndd913a52010-07-22 12:17:04 -07002082 }
2083
2084 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002085 * Pop the last fragment transition from the local activity's fragment
2086 * back stack. If there is nothing to pop, false is returned.
Dianne Hackbornf121be72010-05-06 14:10:32 -07002087 * @param name If non-null, this is the name of a previous back state
Dianne Hackborndd913a52010-07-22 12:17:04 -07002088 * to look for; if found, all states up to that state will be popped. The
2089 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2090 * the named state itself is popped. If null, only the top state is popped.
2091 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002092 */
Dianne Hackborndd913a52010-07-22 12:17:04 -07002093 public boolean popBackStack(String name, int flags) {
2094 return mFragments.popBackStackState(mHandler, name, flags);
2095 }
2096
2097 /**
2098 * Pop all back stack states up to the one with the given identifier.
2099 * @param id Identifier of the stated to be popped. If no identifier exists,
2100 * false is returned.
2101 * The identifier is the number returned by
2102 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The
2103 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2104 * the named state itself is popped.
2105 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
2106 */
2107 public boolean popBackStack(int id, int flags) {
2108 return mFragments.popBackStackState(mHandler, id, flags);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002109 }
2110
2111 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002112 * Called when the activity has detected the user's press of the back
2113 * key. The default implementation simply finishes the current activity,
2114 * but you can override this to do whatever you want.
2115 */
2116 public void onBackPressed() {
Dianne Hackborndd913a52010-07-22 12:17:04 -07002117 if (!popBackStack()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002118 finish();
2119 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002120 }
2121
2122 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 * Called when a touch screen event was not handled by any of the views
2124 * under it. This is most useful to process touch events that happen
2125 * outside of your window bounds, where there is no view to receive it.
2126 *
2127 * @param event The touch screen event being processed.
2128 *
2129 * @return Return true if you have consumed the event, false if you haven't.
2130 * The default implementation always returns false.
2131 */
2132 public boolean onTouchEvent(MotionEvent event) {
2133 return false;
2134 }
2135
2136 /**
2137 * Called when the trackball was moved and not handled by any of the
2138 * views inside of the activity. So, for example, if the trackball moves
2139 * while focus is on a button, you will receive a call here because
2140 * buttons do not normally do anything with trackball events. The call
2141 * here happens <em>before</em> trackball movements are converted to
2142 * DPAD key events, which then get sent back to the view hierarchy, and
2143 * will be processed at the point for things like focus navigation.
2144 *
2145 * @param event The trackball event being processed.
2146 *
2147 * @return Return true if you have consumed the event, false if you haven't.
2148 * The default implementation always returns false.
2149 */
2150 public boolean onTrackballEvent(MotionEvent event) {
2151 return false;
2152 }
2153
2154 /**
2155 * Called whenever a key, touch, or trackball event is dispatched to the
2156 * activity. Implement this method if you wish to know that the user has
2157 * interacted with the device in some way while your activity is running.
2158 * This callback and {@link #onUserLeaveHint} are intended to help
2159 * activities manage status bar notifications intelligently; specifically,
2160 * for helping activities determine the proper time to cancel a notfication.
2161 *
2162 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2163 * be accompanied by calls to {@link #onUserInteraction}. This
2164 * ensures that your activity will be told of relevant user activity such
2165 * as pulling down the notification pane and touching an item there.
2166 *
2167 * <p>Note that this callback will be invoked for the touch down action
2168 * that begins a touch gesture, but may not be invoked for the touch-moved
2169 * and touch-up actions that follow.
2170 *
2171 * @see #onUserLeaveHint()
2172 */
2173 public void onUserInteraction() {
2174 }
2175
2176 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2177 // Update window manager if: we have a view, that view is
2178 // attached to its parent (which will be a RootView), and
2179 // this activity is not embedded.
2180 if (mParent == null) {
2181 View decor = mDecor;
2182 if (decor != null && decor.getParent() != null) {
2183 getWindowManager().updateViewLayout(decor, params);
2184 }
2185 }
2186 }
2187
2188 public void onContentChanged() {
2189 }
2190
2191 /**
2192 * Called when the current {@link Window} of the activity gains or loses
2193 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002194 * to the user. The default implementation clears the key tracking
2195 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002197 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 * is managed independently of activity lifecycles. As such, while focus
2199 * changes will generally have some relation to lifecycle changes (an
2200 * activity that is stopped will not generally get window focus), you
2201 * should not rely on any particular order between the callbacks here and
2202 * those in the other lifecycle methods such as {@link #onResume}.
2203 *
2204 * <p>As a general rule, however, a resumed activity will have window
2205 * focus... unless it has displayed other dialogs or popups that take
2206 * input focus, in which case the activity itself will not have focus
2207 * when the other windows have it. Likewise, the system may display
2208 * system-level windows (such as the status bar notification panel or
2209 * a system alert) which will temporarily take window input focus without
2210 * pausing the foreground activity.
2211 *
2212 * @param hasFocus Whether the window of this activity has focus.
2213 *
2214 * @see #hasWindowFocus()
2215 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002216 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 */
2218 public void onWindowFocusChanged(boolean hasFocus) {
2219 }
2220
2221 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002222 * Called when the main window associated with the activity has been
2223 * attached to the window manager.
2224 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2225 * for more information.
2226 * @see View#onAttachedToWindow
2227 */
2228 public void onAttachedToWindow() {
2229 }
2230
2231 /**
2232 * Called when the main window associated with the activity has been
2233 * detached from the window manager.
2234 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2235 * for more information.
2236 * @see View#onDetachedFromWindow
2237 */
2238 public void onDetachedFromWindow() {
2239 }
2240
2241 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 * Returns true if this activity's <em>main</em> window currently has window focus.
2243 * Note that this is not the same as the view itself having focus.
2244 *
2245 * @return True if this activity's main window currently has window focus.
2246 *
2247 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2248 */
2249 public boolean hasWindowFocus() {
2250 Window w = getWindow();
2251 if (w != null) {
2252 View d = w.getDecorView();
2253 if (d != null) {
2254 return d.hasWindowFocus();
2255 }
2256 }
2257 return false;
2258 }
2259
2260 /**
2261 * Called to process key events. You can override this to intercept all
2262 * key events before they are dispatched to the window. Be sure to call
2263 * this implementation for key events that should be handled normally.
2264 *
2265 * @param event The key event.
2266 *
2267 * @return boolean Return true if this event was consumed.
2268 */
2269 public boolean dispatchKeyEvent(KeyEvent event) {
2270 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002271 Window win = getWindow();
2272 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 return true;
2274 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002275 View decor = mDecor;
2276 if (decor == null) decor = win.getDecorView();
2277 return event.dispatch(this, decor != null
2278 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280
2281 /**
2282 * Called to process touch screen events. You can override this to
2283 * intercept all touch screen events before they are dispatched to the
2284 * window. Be sure to call this implementation for touch screen events
2285 * that should be handled normally.
2286 *
2287 * @param ev The touch screen event.
2288 *
2289 * @return boolean Return true if this event was consumed.
2290 */
2291 public boolean dispatchTouchEvent(MotionEvent ev) {
2292 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2293 onUserInteraction();
2294 }
2295 if (getWindow().superDispatchTouchEvent(ev)) {
2296 return true;
2297 }
2298 return onTouchEvent(ev);
2299 }
2300
2301 /**
2302 * Called to process trackball events. You can override this to
2303 * intercept all trackball events before they are dispatched to the
2304 * window. Be sure to call this implementation for trackball events
2305 * that should be handled normally.
2306 *
2307 * @param ev The trackball event.
2308 *
2309 * @return boolean Return true if this event was consumed.
2310 */
2311 public boolean dispatchTrackballEvent(MotionEvent ev) {
2312 onUserInteraction();
2313 if (getWindow().superDispatchTrackballEvent(ev)) {
2314 return true;
2315 }
2316 return onTrackballEvent(ev);
2317 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002318
2319 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2320 event.setClassName(getClass().getName());
2321 event.setPackageName(getPackageName());
2322
2323 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002324 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2325 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002326 event.setFullScreen(isFullScreen);
2327
2328 CharSequence title = getTitle();
2329 if (!TextUtils.isEmpty(title)) {
2330 event.getText().add(title);
2331 }
2332
2333 return true;
2334 }
2335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 /**
2337 * Default implementation of
2338 * {@link android.view.Window.Callback#onCreatePanelView}
2339 * for activities. This
2340 * simply returns null so that all panel sub-windows will have the default
2341 * menu behavior.
2342 */
2343 public View onCreatePanelView(int featureId) {
2344 return null;
2345 }
2346
2347 /**
2348 * Default implementation of
2349 * {@link android.view.Window.Callback#onCreatePanelMenu}
2350 * for activities. This calls through to the new
2351 * {@link #onCreateOptionsMenu} method for the
2352 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2353 * so that subclasses of Activity don't need to deal with feature codes.
2354 */
2355 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2356 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002357 boolean show = onCreateOptionsMenu(menu);
2358 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2359 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 }
2361 return false;
2362 }
2363
2364 /**
2365 * Default implementation of
2366 * {@link android.view.Window.Callback#onPreparePanel}
2367 * for activities. This
2368 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2369 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2370 * panel, so that subclasses of
2371 * Activity don't need to deal with feature codes.
2372 */
2373 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2374 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2375 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002376 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 return goforit && menu.hasVisibleItems();
2378 }
2379 return true;
2380 }
2381
2382 /**
2383 * {@inheritDoc}
2384 *
2385 * @return The default implementation returns true.
2386 */
2387 public boolean onMenuOpened(int featureId, Menu menu) {
2388 return true;
2389 }
2390
2391 /**
2392 * Default implementation of
2393 * {@link android.view.Window.Callback#onMenuItemSelected}
2394 * for activities. This calls through to the new
2395 * {@link #onOptionsItemSelected} method for the
2396 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2397 * panel, so that subclasses of
2398 * Activity don't need to deal with feature codes.
2399 */
2400 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2401 switch (featureId) {
2402 case Window.FEATURE_OPTIONS_PANEL:
2403 // Put event logging here so it gets called even if subclass
2404 // doesn't call through to superclass's implmeentation of each
2405 // of these methods below
2406 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002407 if (onOptionsItemSelected(item)) {
2408 return true;
2409 }
2410 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411
2412 case Window.FEATURE_CONTEXT_MENU:
2413 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002414 if (onContextItemSelected(item)) {
2415 return true;
2416 }
2417 return mFragments.dispatchContextItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418
2419 default:
2420 return false;
2421 }
2422 }
2423
2424 /**
2425 * Default implementation of
2426 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2427 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2428 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2429 * so that subclasses of Activity don't need to deal with feature codes.
2430 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2431 * {@link #onContextMenuClosed(Menu)} will be called.
2432 */
2433 public void onPanelClosed(int featureId, Menu menu) {
2434 switch (featureId) {
2435 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002436 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 onOptionsMenuClosed(menu);
2438 break;
2439
2440 case Window.FEATURE_CONTEXT_MENU:
2441 onContextMenuClosed(menu);
2442 break;
2443 }
2444 }
2445
2446 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002447 * Declare that the options menu has changed, so should be recreated.
2448 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2449 * time it needs to be displayed.
2450 */
2451 public void invalidateOptionsMenu() {
2452 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2453 }
2454
2455 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 * Initialize the contents of the Activity's standard options menu. You
2457 * should place your menu items in to <var>menu</var>.
2458 *
2459 * <p>This is only called once, the first time the options menu is
2460 * displayed. To update the menu every time it is displayed, see
2461 * {@link #onPrepareOptionsMenu}.
2462 *
2463 * <p>The default implementation populates the menu with standard system
2464 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2465 * they will be correctly ordered with application-defined menu items.
2466 * Deriving classes should always call through to the base implementation.
2467 *
2468 * <p>You can safely hold on to <var>menu</var> (and any items created
2469 * from it), making modifications to it as desired, until the next
2470 * time onCreateOptionsMenu() is called.
2471 *
2472 * <p>When you add items to the menu, you can implement the Activity's
2473 * {@link #onOptionsItemSelected} method to handle them there.
2474 *
2475 * @param menu The options menu in which you place your items.
2476 *
2477 * @return You must return true for the menu to be displayed;
2478 * if you return false it will not be shown.
2479 *
2480 * @see #onPrepareOptionsMenu
2481 * @see #onOptionsItemSelected
2482 */
2483 public boolean onCreateOptionsMenu(Menu menu) {
2484 if (mParent != null) {
2485 return mParent.onCreateOptionsMenu(menu);
2486 }
2487 return true;
2488 }
2489
2490 /**
2491 * Prepare the Screen's standard options menu to be displayed. This is
2492 * called right before the menu is shown, every time it is shown. You can
2493 * use this method to efficiently enable/disable items or otherwise
2494 * dynamically modify the contents.
2495 *
2496 * <p>The default implementation updates the system menu items based on the
2497 * activity's state. Deriving classes should always call through to the
2498 * base class implementation.
2499 *
2500 * @param menu The options menu as last shown or first initialized by
2501 * onCreateOptionsMenu().
2502 *
2503 * @return You must return true for the menu to be displayed;
2504 * if you return false it will not be shown.
2505 *
2506 * @see #onCreateOptionsMenu
2507 */
2508 public boolean onPrepareOptionsMenu(Menu menu) {
2509 if (mParent != null) {
2510 return mParent.onPrepareOptionsMenu(menu);
2511 }
2512 return true;
2513 }
2514
2515 /**
2516 * This hook is called whenever an item in your options menu is selected.
2517 * The default implementation simply returns false to have the normal
2518 * processing happen (calling the item's Runnable or sending a message to
2519 * its Handler as appropriate). You can use this method for any items
2520 * for which you would like to do processing without those other
2521 * facilities.
2522 *
2523 * <p>Derived classes should call through to the base class for it to
2524 * perform the default menu handling.
2525 *
2526 * @param item The menu item that was selected.
2527 *
2528 * @return boolean Return false to allow normal menu processing to
2529 * proceed, true to consume it here.
2530 *
2531 * @see #onCreateOptionsMenu
2532 */
2533 public boolean onOptionsItemSelected(MenuItem item) {
2534 if (mParent != null) {
2535 return mParent.onOptionsItemSelected(item);
2536 }
2537 return false;
2538 }
2539
2540 /**
2541 * This hook is called whenever the options menu is being closed (either by the user canceling
2542 * the menu with the back/menu button, or when an item is selected).
2543 *
2544 * @param menu The options menu as last shown or first initialized by
2545 * onCreateOptionsMenu().
2546 */
2547 public void onOptionsMenuClosed(Menu menu) {
2548 if (mParent != null) {
2549 mParent.onOptionsMenuClosed(menu);
2550 }
2551 }
2552
2553 /**
2554 * Programmatically opens the options menu. If the options menu is already
2555 * open, this method does nothing.
2556 */
2557 public void openOptionsMenu() {
2558 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2559 }
2560
2561 /**
2562 * Progammatically closes the options menu. If the options menu is already
2563 * closed, this method does nothing.
2564 */
2565 public void closeOptionsMenu() {
2566 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2567 }
2568
2569 /**
2570 * Called when a context menu for the {@code view} is about to be shown.
2571 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2572 * time the context menu is about to be shown and should be populated for
2573 * the view (or item inside the view for {@link AdapterView} subclasses,
2574 * this can be found in the {@code menuInfo})).
2575 * <p>
2576 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2577 * item has been selected.
2578 * <p>
2579 * It is not safe to hold onto the context menu after this method returns.
2580 * {@inheritDoc}
2581 */
2582 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2583 }
2584
2585 /**
2586 * Registers a context menu to be shown for the given view (multiple views
2587 * can show the context menu). This method will set the
2588 * {@link OnCreateContextMenuListener} on the view to this activity, so
2589 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2590 * called when it is time to show the context menu.
2591 *
2592 * @see #unregisterForContextMenu(View)
2593 * @param view The view that should show a context menu.
2594 */
2595 public void registerForContextMenu(View view) {
2596 view.setOnCreateContextMenuListener(this);
2597 }
2598
2599 /**
2600 * Prevents a context menu to be shown for the given view. This method will remove the
2601 * {@link OnCreateContextMenuListener} on the view.
2602 *
2603 * @see #registerForContextMenu(View)
2604 * @param view The view that should stop showing a context menu.
2605 */
2606 public void unregisterForContextMenu(View view) {
2607 view.setOnCreateContextMenuListener(null);
2608 }
2609
2610 /**
2611 * Programmatically opens the context menu for a particular {@code view}.
2612 * The {@code view} should have been added via
2613 * {@link #registerForContextMenu(View)}.
2614 *
2615 * @param view The view to show the context menu for.
2616 */
2617 public void openContextMenu(View view) {
2618 view.showContextMenu();
2619 }
2620
2621 /**
2622 * Programmatically closes the most recently opened context menu, if showing.
2623 */
2624 public void closeContextMenu() {
2625 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2626 }
2627
2628 /**
2629 * This hook is called whenever an item in a context menu is selected. The
2630 * default implementation simply returns false to have the normal processing
2631 * happen (calling the item's Runnable or sending a message to its Handler
2632 * as appropriate). You can use this method for any items for which you
2633 * would like to do processing without those other facilities.
2634 * <p>
2635 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2636 * View that added this menu item.
2637 * <p>
2638 * Derived classes should call through to the base class for it to perform
2639 * the default menu handling.
2640 *
2641 * @param item The context menu item that was selected.
2642 * @return boolean Return false to allow normal context menu processing to
2643 * proceed, true to consume it here.
2644 */
2645 public boolean onContextItemSelected(MenuItem item) {
2646 if (mParent != null) {
2647 return mParent.onContextItemSelected(item);
2648 }
2649 return false;
2650 }
2651
2652 /**
2653 * This hook is called whenever the context menu is being closed (either by
2654 * the user canceling the menu with the back/menu button, or when an item is
2655 * selected).
2656 *
2657 * @param menu The context menu that is being closed.
2658 */
2659 public void onContextMenuClosed(Menu menu) {
2660 if (mParent != null) {
2661 mParent.onContextMenuClosed(menu);
2662 }
2663 }
2664
2665 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002666 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002668 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 protected Dialog onCreateDialog(int id) {
2670 return null;
2671 }
2672
2673 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002674 * Callback for creating dialogs that are managed (saved and restored) for you
2675 * by the activity. The default implementation calls through to
2676 * {@link #onCreateDialog(int)} for compatibility.
2677 *
2678 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2679 * this method the first time, and hang onto it thereafter. Any dialog
2680 * that is created by this method will automatically be saved and restored
2681 * for you, including whether it is showing.
2682 *
2683 * <p>If you would like the activity to manage saving and restoring dialogs
2684 * for you, you should override this method and handle any ids that are
2685 * passed to {@link #showDialog}.
2686 *
2687 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2688 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2689 *
2690 * @param id The id of the dialog.
2691 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2692 * @return The dialog. If you return null, the dialog will not be created.
2693 *
2694 * @see #onPrepareDialog(int, Dialog, Bundle)
2695 * @see #showDialog(int, Bundle)
2696 * @see #dismissDialog(int)
2697 * @see #removeDialog(int)
2698 */
2699 protected Dialog onCreateDialog(int id, Bundle args) {
2700 return onCreateDialog(id);
2701 }
2702
2703 /**
2704 * @deprecated Old no-arguments version of
2705 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2706 */
2707 @Deprecated
2708 protected void onPrepareDialog(int id, Dialog dialog) {
2709 dialog.setOwnerActivity(this);
2710 }
2711
2712 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002714 * shown. The default implementation calls through to
2715 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2716 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 * <p>
2718 * Override this if you need to update a managed dialog based on the state
2719 * of the application each time it is shown. For example, a time picker
2720 * dialog might want to be updated with the current time. You should call
2721 * through to the superclass's implementation. The default implementation
2722 * will set this Activity as the owner activity on the Dialog.
2723 *
2724 * @param id The id of the managed dialog.
2725 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002726 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2727 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 * @see #showDialog(int)
2729 * @see #dismissDialog(int)
2730 * @see #removeDialog(int)
2731 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002732 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2733 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735
2736 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002737 * Simple version of {@link #showDialog(int, Bundle)} that does not
2738 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2739 * with null arguments.
2740 */
2741 public final void showDialog(int id) {
2742 showDialog(id, null);
2743 }
2744
2745 /**
2746 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 * will be made with the same id the first time this is called for a given
2748 * id. From thereafter, the dialog will be automatically saved and restored.
2749 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002750 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 * be made to provide an opportunity to do any timely preparation.
2752 *
2753 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002754 * @param args Arguments to pass through to the dialog. These will be saved
2755 * and restored for you. Note that if the dialog is already created,
2756 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2757 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002758 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002759 * @return Returns true if the Dialog was created; false is returned if
2760 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2761 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002762 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002763 * @see #onCreateDialog(int, Bundle)
2764 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 * @see #dismissDialog(int)
2766 * @see #removeDialog(int)
2767 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002768 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002770 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002772 ManagedDialog md = mManagedDialogs.get(id);
2773 if (md == null) {
2774 md = new ManagedDialog();
2775 md.mDialog = createDialog(id, null, args);
2776 if (md.mDialog == null) {
2777 return false;
2778 }
2779 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002782 md.mArgs = args;
2783 onPrepareDialog(id, md.mDialog, args);
2784 md.mDialog.show();
2785 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
2787
2788 /**
2789 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2790 *
2791 * @param id The id of the managed dialog.
2792 *
2793 * @throws IllegalArgumentException if the id was not previously shown via
2794 * {@link #showDialog(int)}.
2795 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002796 * @see #onCreateDialog(int, Bundle)
2797 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 * @see #showDialog(int)
2799 * @see #removeDialog(int)
2800 */
2801 public final void dismissDialog(int id) {
2802 if (mManagedDialogs == null) {
2803 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002805
2806 final ManagedDialog md = mManagedDialogs.get(id);
2807 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 throw missingDialog(id);
2809 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002810 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 }
2812
2813 /**
2814 * Creates an exception to throw if a user passed in a dialog id that is
2815 * unexpected.
2816 */
2817 private IllegalArgumentException missingDialog(int id) {
2818 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2819 + "shown via Activity#showDialog");
2820 }
2821
2822 /**
2823 * Removes any internal references to a dialog managed by this Activity.
2824 * If the dialog is showing, it will dismiss it as part of the clean up.
2825 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002826 * <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 -08002827 * want to avoid the overhead of saving and restoring it in the future.
2828 *
2829 * @param id The id of the managed dialog.
2830 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002831 * @see #onCreateDialog(int, Bundle)
2832 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 * @see #showDialog(int)
2834 * @see #dismissDialog(int)
2835 */
2836 public final void removeDialog(int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 if (mManagedDialogs == null) {
2838 return;
2839 }
2840
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002841 final ManagedDialog md = mManagedDialogs.get(id);
2842 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 return;
2844 }
2845
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002846 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 mManagedDialogs.remove(id);
2848 }
2849
2850 /**
2851 * This hook is called when the user signals the desire to start a search.
2852 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002853 * <p>You can use this function as a simple way to launch the search UI, in response to a
2854 * menu item, search button, or other widgets within your activity. Unless overidden,
2855 * calling this function is the same as calling
2856 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2857 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 *
2859 * <p>You can override this function to force global search, e.g. in response to a dedicated
2860 * search key, or to block search entirely (by simply returning false).
2861 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002862 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2863 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 *
2865 * @see android.app.SearchManager
2866 */
2867 public boolean onSearchRequested() {
2868 startSearch(null, false, null, false);
2869 return true;
2870 }
2871
2872 /**
2873 * This hook is called to launch the search UI.
2874 *
2875 * <p>It is typically called from onSearchRequested(), either directly from
2876 * Activity.onSearchRequested() or from an overridden version in any given
2877 * Activity. If your goal is simply to activate search, it is preferred to call
2878 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2879 * is to inject specific data such as context data, it is preferred to <i>override</i>
2880 * onSearchRequested(), so that any callers to it will benefit from the override.
2881 *
2882 * @param initialQuery Any non-null non-empty string will be inserted as
2883 * pre-entered text in the search query box.
2884 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2885 * any further typing will replace it. This is useful for cases where an entire pre-formed
2886 * query is being inserted. If false, the selection point will be placed at the end of the
2887 * inserted query. This is useful when the inserted query is text that the user entered,
2888 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2889 * if initialQuery is a non-empty string.</i>
2890 * @param appSearchData An application can insert application-specific
2891 * context here, in order to improve quality or specificity of its own
2892 * searches. This data will be returned with SEARCH intent(s). Null if
2893 * no extra data is required.
2894 * @param globalSearch If false, this will only launch the search that has been specifically
2895 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002896 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2898 *
2899 * @see android.app.SearchManager
2900 * @see #onSearchRequested
2901 */
2902 public void startSearch(String initialQuery, boolean selectInitialQuery,
2903 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002904 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002905 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 appSearchData, globalSearch);
2907 }
2908
2909 /**
krosaend2d60142009-08-17 08:56:48 -07002910 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2911 * the search dialog. Made available for testing purposes.
2912 *
2913 * @param query The query to trigger. If empty, the request will be ignored.
2914 * @param appSearchData An application can insert application-specific
2915 * context here, in order to improve quality or specificity of its own
2916 * searches. This data will be returned with SEARCH intent(s). Null if
2917 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002918 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002919 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002920 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002921 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002922 }
2923
2924 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 * Request that key events come to this activity. Use this if your
2926 * activity has no views with focus, but the activity still wants
2927 * a chance to process key events.
2928 *
2929 * @see android.view.Window#takeKeyEvents
2930 */
2931 public void takeKeyEvents(boolean get) {
2932 getWindow().takeKeyEvents(get);
2933 }
2934
2935 /**
2936 * Enable extended window features. This is a convenience for calling
2937 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2938 *
2939 * @param featureId The desired feature as defined in
2940 * {@link android.view.Window}.
2941 * @return Returns true if the requested feature is supported and now
2942 * enabled.
2943 *
2944 * @see android.view.Window#requestFeature
2945 */
2946 public final boolean requestWindowFeature(int featureId) {
2947 return getWindow().requestFeature(featureId);
2948 }
2949
2950 /**
2951 * Convenience for calling
2952 * {@link android.view.Window#setFeatureDrawableResource}.
2953 */
2954 public final void setFeatureDrawableResource(int featureId, int resId) {
2955 getWindow().setFeatureDrawableResource(featureId, resId);
2956 }
2957
2958 /**
2959 * Convenience for calling
2960 * {@link android.view.Window#setFeatureDrawableUri}.
2961 */
2962 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2963 getWindow().setFeatureDrawableUri(featureId, uri);
2964 }
2965
2966 /**
2967 * Convenience for calling
2968 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2969 */
2970 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2971 getWindow().setFeatureDrawable(featureId, drawable);
2972 }
2973
2974 /**
2975 * Convenience for calling
2976 * {@link android.view.Window#setFeatureDrawableAlpha}.
2977 */
2978 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2979 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2980 }
2981
2982 /**
2983 * Convenience for calling
2984 * {@link android.view.Window#getLayoutInflater}.
2985 */
2986 public LayoutInflater getLayoutInflater() {
2987 return getWindow().getLayoutInflater();
2988 }
2989
2990 /**
2991 * Returns a {@link MenuInflater} with this context.
2992 */
2993 public MenuInflater getMenuInflater() {
2994 return new MenuInflater(this);
2995 }
2996
2997 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002998 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2999 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 if (mParent == null) {
3001 super.onApplyThemeResource(theme, resid, first);
3002 } else {
3003 try {
3004 theme.setTo(mParent.getTheme());
3005 } catch (Exception e) {
3006 // Empty
3007 }
3008 theme.applyStyle(resid, false);
3009 }
3010 }
3011
3012 /**
3013 * Launch an activity for which you would like a result when it finished.
3014 * When this activity exits, your
3015 * onActivityResult() method will be called with the given requestCode.
3016 * Using a negative requestCode is the same as calling
3017 * {@link #startActivity} (the activity is not launched as a sub-activity).
3018 *
3019 * <p>Note that this method should only be used with Intent protocols
3020 * that are defined to return a result. In other protocols (such as
3021 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3022 * not get the result when you expect. For example, if the activity you
3023 * are launching uses the singleTask launch mode, it will not run in your
3024 * task and thus you will immediately receive a cancel result.
3025 *
3026 * <p>As a special case, if you call startActivityForResult() with a requestCode
3027 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3028 * activity, then your window will not be displayed until a result is
3029 * returned back from the started activity. This is to avoid visible
3030 * flickering when redirecting to another activity.
3031 *
3032 * <p>This method throws {@link android.content.ActivityNotFoundException}
3033 * if there was no Activity found to run the given Intent.
3034 *
3035 * @param intent The intent to start.
3036 * @param requestCode If >= 0, this code will be returned in
3037 * onActivityResult() when the activity exits.
3038 *
3039 * @throws android.content.ActivityNotFoundException
3040 *
3041 * @see #startActivity
3042 */
3043 public void startActivityForResult(Intent intent, int requestCode) {
3044 if (mParent == null) {
3045 Instrumentation.ActivityResult ar =
3046 mInstrumentation.execStartActivity(
3047 this, mMainThread.getApplicationThread(), mToken, this,
3048 intent, requestCode);
3049 if (ar != null) {
3050 mMainThread.sendActivityResult(
3051 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3052 ar.getResultData());
3053 }
3054 if (requestCode >= 0) {
3055 // If this start is requesting a result, we can avoid making
3056 // the activity visible until the result is received. Setting
3057 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3058 // activity hidden during this time, to avoid flickering.
3059 // This can only be done when a result is requested because
3060 // that guarantees we will get information back when the
3061 // activity is finished, no matter what happens to it.
3062 mStartedActivity = true;
3063 }
3064 } else {
3065 mParent.startActivityFromChild(this, intent, requestCode);
3066 }
3067 }
3068
3069 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003070 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003071 * to use a IntentSender to describe the activity to be started. If
3072 * the IntentSender is for an activity, that activity will be started
3073 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3074 * here; otherwise, its associated action will be executed (such as
3075 * sending a broadcast) as if you had called
3076 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003077 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003078 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003079 * @param requestCode If >= 0, this code will be returned in
3080 * onActivityResult() when the activity exits.
3081 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003082 * intent parameter to {@link IntentSender#sendIntent}.
3083 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003084 * would like to change.
3085 * @param flagsValues Desired values for any bits set in
3086 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003087 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003088 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003089 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3090 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3091 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003092 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003093 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003094 flagsMask, flagsValues, this);
3095 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003096 mParent.startIntentSenderFromChild(this, intent, requestCode,
3097 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003098 }
3099 }
3100
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003101 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003102 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003103 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003104 try {
3105 String resolvedType = null;
3106 if (fillInIntent != null) {
3107 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3108 }
3109 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003110 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003111 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3112 requestCode, flagsMask, flagsValues);
3113 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003114 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003115 }
3116 Instrumentation.checkStartActivityResult(result, null);
3117 } catch (RemoteException e) {
3118 }
3119 if (requestCode >= 0) {
3120 // If this start is requesting a result, we can avoid making
3121 // the activity visible until the result is received. Setting
3122 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3123 // activity hidden during this time, to avoid flickering.
3124 // This can only be done when a result is requested because
3125 // that guarantees we will get information back when the
3126 // activity is finished, no matter what happens to it.
3127 mStartedActivity = true;
3128 }
3129 }
3130
3131 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 * Launch a new activity. You will not receive any information about when
3133 * the activity exits. This implementation overrides the base version,
3134 * providing information about
3135 * the activity performing the launch. Because of this additional
3136 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3137 * required; if not specified, the new activity will be added to the
3138 * task of the caller.
3139 *
3140 * <p>This method throws {@link android.content.ActivityNotFoundException}
3141 * if there was no Activity found to run the given Intent.
3142 *
3143 * @param intent The intent to start.
3144 *
3145 * @throws android.content.ActivityNotFoundException
3146 *
3147 * @see #startActivityForResult
3148 */
3149 @Override
3150 public void startActivity(Intent intent) {
3151 startActivityForResult(intent, -1);
3152 }
3153
3154 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003155 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003156 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003157 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003158 * for more information.
3159 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003160 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003161 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003162 * intent parameter to {@link IntentSender#sendIntent}.
3163 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003164 * would like to change.
3165 * @param flagsValues Desired values for any bits set in
3166 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003167 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003168 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003169 public void startIntentSender(IntentSender intent,
3170 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3171 throws IntentSender.SendIntentException {
3172 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3173 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003174 }
3175
3176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 * A special variation to launch an activity only if a new activity
3178 * instance is needed to handle the given Intent. In other words, this is
3179 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3180 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3181 * singleTask or singleTop
3182 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3183 * and the activity
3184 * that handles <var>intent</var> is the same as your currently running
3185 * activity, then a new instance is not needed. In this case, instead of
3186 * the normal behavior of calling {@link #onNewIntent} this function will
3187 * return and you can handle the Intent yourself.
3188 *
3189 * <p>This function can only be called from a top-level activity; if it is
3190 * called from a child activity, a runtime exception will be thrown.
3191 *
3192 * @param intent The intent to start.
3193 * @param requestCode If >= 0, this code will be returned in
3194 * onActivityResult() when the activity exits, as described in
3195 * {@link #startActivityForResult}.
3196 *
3197 * @return If a new activity was launched then true is returned; otherwise
3198 * false is returned and you must handle the Intent yourself.
3199 *
3200 * @see #startActivity
3201 * @see #startActivityForResult
3202 */
3203 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3204 if (mParent == null) {
3205 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3206 try {
3207 result = ActivityManagerNative.getDefault()
3208 .startActivity(mMainThread.getApplicationThread(),
3209 intent, intent.resolveTypeIfNeeded(
3210 getContentResolver()),
3211 null, 0,
3212 mToken, mEmbeddedID, requestCode, true, false);
3213 } catch (RemoteException e) {
3214 // Empty
3215 }
3216
3217 Instrumentation.checkStartActivityResult(result, intent);
3218
3219 if (requestCode >= 0) {
3220 // If this start is requesting a result, we can avoid making
3221 // the activity visible until the result is received. Setting
3222 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3223 // activity hidden during this time, to avoid flickering.
3224 // This can only be done when a result is requested because
3225 // that guarantees we will get information back when the
3226 // activity is finished, no matter what happens to it.
3227 mStartedActivity = true;
3228 }
3229 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3230 }
3231
3232 throw new UnsupportedOperationException(
3233 "startActivityIfNeeded can only be called from a top-level activity");
3234 }
3235
3236 /**
3237 * Special version of starting an activity, for use when you are replacing
3238 * other activity components. You can use this to hand the Intent off
3239 * to the next Activity that can handle it. You typically call this in
3240 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3241 *
3242 * @param intent The intent to dispatch to the next activity. For
3243 * correct behavior, this must be the same as the Intent that started
3244 * your own activity; the only changes you can make are to the extras
3245 * inside of it.
3246 *
3247 * @return Returns a boolean indicating whether there was another Activity
3248 * to start: true if there was a next activity to start, false if there
3249 * wasn't. In general, if true is returned you will then want to call
3250 * finish() on yourself.
3251 */
3252 public boolean startNextMatchingActivity(Intent intent) {
3253 if (mParent == null) {
3254 try {
3255 return ActivityManagerNative.getDefault()
3256 .startNextMatchingActivity(mToken, intent);
3257 } catch (RemoteException e) {
3258 // Empty
3259 }
3260 return false;
3261 }
3262
3263 throw new UnsupportedOperationException(
3264 "startNextMatchingActivity can only be called from a top-level activity");
3265 }
3266
3267 /**
3268 * This is called when a child activity of this one calls its
3269 * {@link #startActivity} or {@link #startActivityForResult} method.
3270 *
3271 * <p>This method throws {@link android.content.ActivityNotFoundException}
3272 * if there was no Activity found to run the given Intent.
3273 *
3274 * @param child The activity making the call.
3275 * @param intent The intent to start.
3276 * @param requestCode Reply request code. < 0 if reply is not requested.
3277 *
3278 * @throws android.content.ActivityNotFoundException
3279 *
3280 * @see #startActivity
3281 * @see #startActivityForResult
3282 */
3283 public void startActivityFromChild(Activity child, Intent intent,
3284 int requestCode) {
3285 Instrumentation.ActivityResult ar =
3286 mInstrumentation.execStartActivity(
3287 this, mMainThread.getApplicationThread(), mToken, child,
3288 intent, requestCode);
3289 if (ar != null) {
3290 mMainThread.sendActivityResult(
3291 mToken, child.mEmbeddedID, requestCode,
3292 ar.getResultCode(), ar.getResultData());
3293 }
3294 }
3295
3296 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003297 * This is called when a Fragment in this activity calls its
3298 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3299 * method.
3300 *
3301 * <p>This method throws {@link android.content.ActivityNotFoundException}
3302 * if there was no Activity found to run the given Intent.
3303 *
3304 * @param fragment The fragment making the call.
3305 * @param intent The intent to start.
3306 * @param requestCode Reply request code. < 0 if reply is not requested.
3307 *
3308 * @throws android.content.ActivityNotFoundException
3309 *
3310 * @see Fragment#startActivity
3311 * @see Fragment#startActivityForResult
3312 */
3313 public void startActivityFromFragment(Fragment fragment, Intent intent,
3314 int requestCode) {
3315 Instrumentation.ActivityResult ar =
3316 mInstrumentation.execStartActivity(
3317 this, mMainThread.getApplicationThread(), mToken, fragment,
3318 intent, requestCode);
3319 if (ar != null) {
3320 mMainThread.sendActivityResult(
3321 mToken, fragment.mWho, requestCode,
3322 ar.getResultCode(), ar.getResultData());
3323 }
3324 }
3325
3326 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003327 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003328 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003329 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003330 * for more information.
3331 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003332 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3333 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3334 int extraFlags)
3335 throws IntentSender.SendIntentException {
3336 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003337 flagsMask, flagsValues, child);
3338 }
3339
3340 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003341 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3342 * or {@link #finish} to specify an explicit transition animation to
3343 * perform next.
3344 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003345 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003346 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003347 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003348 */
3349 public void overridePendingTransition(int enterAnim, int exitAnim) {
3350 try {
3351 ActivityManagerNative.getDefault().overridePendingTransition(
3352 mToken, getPackageName(), enterAnim, exitAnim);
3353 } catch (RemoteException e) {
3354 }
3355 }
3356
3357 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 * Call this to set the result that your activity will return to its
3359 * caller.
3360 *
3361 * @param resultCode The result code to propagate back to the originating
3362 * activity, often RESULT_CANCELED or RESULT_OK
3363 *
3364 * @see #RESULT_CANCELED
3365 * @see #RESULT_OK
3366 * @see #RESULT_FIRST_USER
3367 * @see #setResult(int, Intent)
3368 */
3369 public final void setResult(int resultCode) {
3370 synchronized (this) {
3371 mResultCode = resultCode;
3372 mResultData = null;
3373 }
3374 }
3375
3376 /**
3377 * Call this to set the result that your activity will return to its
3378 * caller.
3379 *
3380 * @param resultCode The result code to propagate back to the originating
3381 * activity, often RESULT_CANCELED or RESULT_OK
3382 * @param data The data to propagate back to the originating activity.
3383 *
3384 * @see #RESULT_CANCELED
3385 * @see #RESULT_OK
3386 * @see #RESULT_FIRST_USER
3387 * @see #setResult(int)
3388 */
3389 public final void setResult(int resultCode, Intent data) {
3390 synchronized (this) {
3391 mResultCode = resultCode;
3392 mResultData = data;
3393 }
3394 }
3395
3396 /**
3397 * Return the name of the package that invoked this activity. This is who
3398 * the data in {@link #setResult setResult()} will be sent to. You can
3399 * use this information to validate that the recipient is allowed to
3400 * receive the data.
3401 *
3402 * <p>Note: if the calling activity is not expecting a result (that is it
3403 * did not use the {@link #startActivityForResult}
3404 * form that includes a request code), then the calling package will be
3405 * null.
3406 *
3407 * @return The package of the activity that will receive your
3408 * reply, or null if none.
3409 */
3410 public String getCallingPackage() {
3411 try {
3412 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3413 } catch (RemoteException e) {
3414 return null;
3415 }
3416 }
3417
3418 /**
3419 * Return the name of the activity that invoked this activity. This is
3420 * who the data in {@link #setResult setResult()} will be sent to. You
3421 * can use this information to validate that the recipient is allowed to
3422 * receive the data.
3423 *
3424 * <p>Note: if the calling activity is not expecting a result (that is it
3425 * did not use the {@link #startActivityForResult}
3426 * form that includes a request code), then the calling package will be
3427 * null.
3428 *
3429 * @return String The full name of the activity that will receive your
3430 * reply, or null if none.
3431 */
3432 public ComponentName getCallingActivity() {
3433 try {
3434 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3435 } catch (RemoteException e) {
3436 return null;
3437 }
3438 }
3439
3440 /**
3441 * Control whether this activity's main window is visible. This is intended
3442 * only for the special case of an activity that is not going to show a
3443 * UI itself, but can't just finish prior to onResume() because it needs
3444 * to wait for a service binding or such. Setting this to false allows
3445 * you to prevent your UI from being shown during that time.
3446 *
3447 * <p>The default value for this is taken from the
3448 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3449 */
3450 public void setVisible(boolean visible) {
3451 if (mVisibleFromClient != visible) {
3452 mVisibleFromClient = visible;
3453 if (mVisibleFromServer) {
3454 if (visible) makeVisible();
3455 else mDecor.setVisibility(View.INVISIBLE);
3456 }
3457 }
3458 }
3459
3460 void makeVisible() {
3461 if (!mWindowAdded) {
3462 ViewManager wm = getWindowManager();
3463 wm.addView(mDecor, getWindow().getAttributes());
3464 mWindowAdded = true;
3465 }
3466 mDecor.setVisibility(View.VISIBLE);
3467 }
3468
3469 /**
3470 * Check to see whether this activity is in the process of finishing,
3471 * either because you called {@link #finish} on it or someone else
3472 * has requested that it finished. This is often used in
3473 * {@link #onPause} to determine whether the activity is simply pausing or
3474 * completely finishing.
3475 *
3476 * @return If the activity is finishing, returns true; else returns false.
3477 *
3478 * @see #finish
3479 */
3480 public boolean isFinishing() {
3481 return mFinished;
3482 }
3483
3484 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003485 * Check to see whether this activity is in the process of being destroyed in order to be
3486 * recreated with a new configuration. This is often used in
3487 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3488 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3489 *
3490 * @return If the activity is being torn down in order to be recreated with a new configuration,
3491 * returns true; else returns false.
3492 */
3493 public boolean isChangingConfigurations() {
3494 return mChangingConfigurations;
3495 }
3496
3497 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 * Call this when your activity is done and should be closed. The
3499 * ActivityResult is propagated back to whoever launched you via
3500 * onActivityResult().
3501 */
3502 public void finish() {
3503 if (mParent == null) {
3504 int resultCode;
3505 Intent resultData;
3506 synchronized (this) {
3507 resultCode = mResultCode;
3508 resultData = mResultData;
3509 }
3510 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3511 try {
3512 if (ActivityManagerNative.getDefault()
3513 .finishActivity(mToken, resultCode, resultData)) {
3514 mFinished = true;
3515 }
3516 } catch (RemoteException e) {
3517 // Empty
3518 }
3519 } else {
3520 mParent.finishFromChild(this);
3521 }
3522 }
3523
3524 /**
3525 * This is called when a child activity of this one calls its
3526 * {@link #finish} method. The default implementation simply calls
3527 * finish() on this activity (the parent), finishing the entire group.
3528 *
3529 * @param child The activity making the call.
3530 *
3531 * @see #finish
3532 */
3533 public void finishFromChild(Activity child) {
3534 finish();
3535 }
3536
3537 /**
3538 * Force finish another activity that you had previously started with
3539 * {@link #startActivityForResult}.
3540 *
3541 * @param requestCode The request code of the activity that you had
3542 * given to startActivityForResult(). If there are multiple
3543 * activities started with this request code, they
3544 * will all be finished.
3545 */
3546 public void finishActivity(int requestCode) {
3547 if (mParent == null) {
3548 try {
3549 ActivityManagerNative.getDefault()
3550 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3551 } catch (RemoteException e) {
3552 // Empty
3553 }
3554 } else {
3555 mParent.finishActivityFromChild(this, requestCode);
3556 }
3557 }
3558
3559 /**
3560 * This is called when a child activity of this one calls its
3561 * finishActivity().
3562 *
3563 * @param child The activity making the call.
3564 * @param requestCode Request code that had been used to start the
3565 * activity.
3566 */
3567 public void finishActivityFromChild(Activity child, int requestCode) {
3568 try {
3569 ActivityManagerNative.getDefault()
3570 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3571 } catch (RemoteException e) {
3572 // Empty
3573 }
3574 }
3575
3576 /**
3577 * Called when an activity you launched exits, giving you the requestCode
3578 * you started it with, the resultCode it returned, and any additional
3579 * data from it. The <var>resultCode</var> will be
3580 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3581 * didn't return any result, or crashed during its operation.
3582 *
3583 * <p>You will receive this call immediately before onResume() when your
3584 * activity is re-starting.
3585 *
3586 * @param requestCode The integer request code originally supplied to
3587 * startActivityForResult(), allowing you to identify who this
3588 * result came from.
3589 * @param resultCode The integer result code returned by the child activity
3590 * through its setResult().
3591 * @param data An Intent, which can return result data to the caller
3592 * (various data can be attached to Intent "extras").
3593 *
3594 * @see #startActivityForResult
3595 * @see #createPendingResult
3596 * @see #setResult(int)
3597 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003598 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 }
3600
3601 /**
3602 * Create a new PendingIntent object which you can hand to others
3603 * for them to use to send result data back to your
3604 * {@link #onActivityResult} callback. The created object will be either
3605 * one-shot (becoming invalid after a result is sent back) or multiple
3606 * (allowing any number of results to be sent through it).
3607 *
3608 * @param requestCode Private request code for the sender that will be
3609 * associated with the result data when it is returned. The sender can not
3610 * modify this value, allowing you to identify incoming results.
3611 * @param data Default data to supply in the result, which may be modified
3612 * by the sender.
3613 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3614 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3615 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3616 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3617 * or any of the flags as supported by
3618 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3619 * of the intent that can be supplied when the actual send happens.
3620 *
3621 * @return Returns an existing or new PendingIntent matching the given
3622 * parameters. May return null only if
3623 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3624 * supplied.
3625 *
3626 * @see PendingIntent
3627 */
3628 public PendingIntent createPendingResult(int requestCode, Intent data,
3629 int flags) {
3630 String packageName = getPackageName();
3631 try {
3632 IIntentSender target =
3633 ActivityManagerNative.getDefault().getIntentSender(
3634 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3635 mParent == null ? mToken : mParent.mToken,
3636 mEmbeddedID, requestCode, data, null, flags);
3637 return target != null ? new PendingIntent(target) : null;
3638 } catch (RemoteException e) {
3639 // Empty
3640 }
3641 return null;
3642 }
3643
3644 /**
3645 * Change the desired orientation of this activity. If the activity
3646 * is currently in the foreground or otherwise impacting the screen
3647 * orientation, the screen will immediately be changed (possibly causing
3648 * the activity to be restarted). Otherwise, this will be used the next
3649 * time the activity is visible.
3650 *
3651 * @param requestedOrientation An orientation constant as used in
3652 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3653 */
3654 public void setRequestedOrientation(int requestedOrientation) {
3655 if (mParent == null) {
3656 try {
3657 ActivityManagerNative.getDefault().setRequestedOrientation(
3658 mToken, requestedOrientation);
3659 } catch (RemoteException e) {
3660 // Empty
3661 }
3662 } else {
3663 mParent.setRequestedOrientation(requestedOrientation);
3664 }
3665 }
3666
3667 /**
3668 * Return the current requested orientation of the activity. This will
3669 * either be the orientation requested in its component's manifest, or
3670 * the last requested orientation given to
3671 * {@link #setRequestedOrientation(int)}.
3672 *
3673 * @return Returns an orientation constant as used in
3674 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3675 */
3676 public int getRequestedOrientation() {
3677 if (mParent == null) {
3678 try {
3679 return ActivityManagerNative.getDefault()
3680 .getRequestedOrientation(mToken);
3681 } catch (RemoteException e) {
3682 // Empty
3683 }
3684 } else {
3685 return mParent.getRequestedOrientation();
3686 }
3687 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3688 }
3689
3690 /**
3691 * Return the identifier of the task this activity is in. This identifier
3692 * will remain the same for the lifetime of the activity.
3693 *
3694 * @return Task identifier, an opaque integer.
3695 */
3696 public int getTaskId() {
3697 try {
3698 return ActivityManagerNative.getDefault()
3699 .getTaskForActivity(mToken, false);
3700 } catch (RemoteException e) {
3701 return -1;
3702 }
3703 }
3704
3705 /**
3706 * Return whether this activity is the root of a task. The root is the
3707 * first activity in a task.
3708 *
3709 * @return True if this is the root activity, else false.
3710 */
3711 public boolean isTaskRoot() {
3712 try {
3713 return ActivityManagerNative.getDefault()
3714 .getTaskForActivity(mToken, true) >= 0;
3715 } catch (RemoteException e) {
3716 return false;
3717 }
3718 }
3719
3720 /**
3721 * Move the task containing this activity to the back of the activity
3722 * stack. The activity's order within the task is unchanged.
3723 *
3724 * @param nonRoot If false then this only works if the activity is the root
3725 * of a task; if true it will work for any activity in
3726 * a task.
3727 *
3728 * @return If the task was moved (or it was already at the
3729 * back) true is returned, else false.
3730 */
3731 public boolean moveTaskToBack(boolean nonRoot) {
3732 try {
3733 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3734 mToken, nonRoot);
3735 } catch (RemoteException e) {
3736 // Empty
3737 }
3738 return false;
3739 }
3740
3741 /**
3742 * Returns class name for this activity with the package prefix removed.
3743 * This is the default name used to read and write settings.
3744 *
3745 * @return The local class name.
3746 */
3747 public String getLocalClassName() {
3748 final String pkg = getPackageName();
3749 final String cls = mComponent.getClassName();
3750 int packageLen = pkg.length();
3751 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3752 || cls.charAt(packageLen) != '.') {
3753 return cls;
3754 }
3755 return cls.substring(packageLen+1);
3756 }
3757
3758 /**
3759 * Returns complete component name of this activity.
3760 *
3761 * @return Returns the complete component name for this activity
3762 */
3763 public ComponentName getComponentName()
3764 {
3765 return mComponent;
3766 }
3767
3768 /**
3769 * Retrieve a {@link SharedPreferences} object for accessing preferences
3770 * that are private to this activity. This simply calls the underlying
3771 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3772 * class name as the preferences name.
3773 *
3774 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3775 * operation, {@link #MODE_WORLD_READABLE} and
3776 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3777 *
3778 * @return Returns the single SharedPreferences instance that can be used
3779 * to retrieve and modify the preference values.
3780 */
3781 public SharedPreferences getPreferences(int mode) {
3782 return getSharedPreferences(getLocalClassName(), mode);
3783 }
3784
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003785 private void ensureSearchManager() {
3786 if (mSearchManager != null) {
3787 return;
3788 }
3789
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003790 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003791 }
3792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 @Override
3794 public Object getSystemService(String name) {
3795 if (getBaseContext() == null) {
3796 throw new IllegalStateException(
3797 "System services not available to Activities before onCreate()");
3798 }
3799
3800 if (WINDOW_SERVICE.equals(name)) {
3801 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003802 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003803 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003804 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
3806 return super.getSystemService(name);
3807 }
3808
3809 /**
3810 * Change the title associated with this activity. If this is a
3811 * top-level activity, the title for its window will change. If it
3812 * is an embedded activity, the parent can do whatever it wants
3813 * with it.
3814 */
3815 public void setTitle(CharSequence title) {
3816 mTitle = title;
3817 onTitleChanged(title, mTitleColor);
3818
3819 if (mParent != null) {
3820 mParent.onChildTitleChanged(this, title);
3821 }
3822 }
3823
3824 /**
3825 * Change the title associated with this activity. If this is a
3826 * top-level activity, the title for its window will change. If it
3827 * is an embedded activity, the parent can do whatever it wants
3828 * with it.
3829 */
3830 public void setTitle(int titleId) {
3831 setTitle(getText(titleId));
3832 }
3833
3834 public void setTitleColor(int textColor) {
3835 mTitleColor = textColor;
3836 onTitleChanged(mTitle, textColor);
3837 }
3838
3839 public final CharSequence getTitle() {
3840 return mTitle;
3841 }
3842
3843 public final int getTitleColor() {
3844 return mTitleColor;
3845 }
3846
3847 protected void onTitleChanged(CharSequence title, int color) {
3848 if (mTitleReady) {
3849 final Window win = getWindow();
3850 if (win != null) {
3851 win.setTitle(title);
3852 if (color != 0) {
3853 win.setTitleColor(color);
3854 }
3855 }
3856 }
3857 }
3858
3859 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3860 }
3861
3862 /**
3863 * Sets the visibility of the progress bar in the title.
3864 * <p>
3865 * In order for the progress bar to be shown, the feature must be requested
3866 * via {@link #requestWindowFeature(int)}.
3867 *
3868 * @param visible Whether to show the progress bars in the title.
3869 */
3870 public final void setProgressBarVisibility(boolean visible) {
3871 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3872 Window.PROGRESS_VISIBILITY_OFF);
3873 }
3874
3875 /**
3876 * Sets the visibility of the indeterminate progress bar in the title.
3877 * <p>
3878 * In order for the progress bar to be shown, the feature must be requested
3879 * via {@link #requestWindowFeature(int)}.
3880 *
3881 * @param visible Whether to show the progress bars in the title.
3882 */
3883 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3884 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3885 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3886 }
3887
3888 /**
3889 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3890 * is always indeterminate).
3891 * <p>
3892 * In order for the progress bar to be shown, the feature must be requested
3893 * via {@link #requestWindowFeature(int)}.
3894 *
3895 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3896 */
3897 public final void setProgressBarIndeterminate(boolean indeterminate) {
3898 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3899 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3900 }
3901
3902 /**
3903 * Sets the progress for the progress bars in the title.
3904 * <p>
3905 * In order for the progress bar to be shown, the feature must be requested
3906 * via {@link #requestWindowFeature(int)}.
3907 *
3908 * @param progress The progress for the progress bar. Valid ranges are from
3909 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3910 * bar will be completely filled and will fade out.
3911 */
3912 public final void setProgress(int progress) {
3913 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3914 }
3915
3916 /**
3917 * Sets the secondary progress for the progress bar in the title. This
3918 * progress is drawn between the primary progress (set via
3919 * {@link #setProgress(int)} and the background. It can be ideal for media
3920 * scenarios such as showing the buffering progress while the default
3921 * progress shows the play progress.
3922 * <p>
3923 * In order for the progress bar to be shown, the feature must be requested
3924 * via {@link #requestWindowFeature(int)}.
3925 *
3926 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3927 * 0 to 10000 (both inclusive).
3928 */
3929 public final void setSecondaryProgress(int secondaryProgress) {
3930 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3931 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3932 }
3933
3934 /**
3935 * Suggests an audio stream whose volume should be changed by the hardware
3936 * volume controls.
3937 * <p>
3938 * The suggested audio stream will be tied to the window of this Activity.
3939 * If the Activity is switched, the stream set here is no longer the
3940 * suggested stream. The client does not need to save and restore the old
3941 * suggested stream value in onPause and onResume.
3942 *
3943 * @param streamType The type of the audio stream whose volume should be
3944 * changed by the hardware volume controls. It is not guaranteed that
3945 * the hardware volume controls will always change this stream's
3946 * volume (for example, if a call is in progress, its stream's volume
3947 * may be changed instead). To reset back to the default, use
3948 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3949 */
3950 public final void setVolumeControlStream(int streamType) {
3951 getWindow().setVolumeControlStream(streamType);
3952 }
3953
3954 /**
3955 * Gets the suggested audio stream whose volume should be changed by the
3956 * harwdare volume controls.
3957 *
3958 * @return The suggested audio stream type whose volume should be changed by
3959 * the hardware volume controls.
3960 * @see #setVolumeControlStream(int)
3961 */
3962 public final int getVolumeControlStream() {
3963 return getWindow().getVolumeControlStream();
3964 }
3965
3966 /**
3967 * Runs the specified action on the UI thread. If the current thread is the UI
3968 * thread, then the action is executed immediately. If the current thread is
3969 * not the UI thread, the action is posted to the event queue of the UI thread.
3970 *
3971 * @param action the action to run on the UI thread
3972 */
3973 public final void runOnUiThread(Runnable action) {
3974 if (Thread.currentThread() != mUiThread) {
3975 mHandler.post(action);
3976 } else {
3977 action.run();
3978 }
3979 }
3980
3981 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003982 * Standard implementation of
3983 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
3984 * inflating with the LayoutInflater returned by {@link #getSystemService}.
3985 * This implementation handles <fragment> tags to embed fragments inside
3986 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 *
3988 * @see android.view.LayoutInflater#createView
3989 * @see android.view.Window#getLayoutInflater
3990 */
3991 public View onCreateView(String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003992 if (!"fragment".equals(name)) {
3993 return null;
3994 }
3995
3996 TypedArray a =
3997 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
3998 String fname = a.getString(com.android.internal.R.styleable.Fragment_name);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003999 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, 0);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004000 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4001 a.recycle();
4002
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004003 if (id == 0) {
4004 throw new IllegalArgumentException(attrs.getPositionDescription()
4005 + ": Must specify unique android:id for " + fname);
4006 }
4007
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004008 try {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004009 // If we restored from a previous state, we may already have
4010 // instantiated this fragment from the state and should use
4011 // that instance instead of making a new one.
4012 Fragment fragment = mFragments.findFragmentById(id);
Dianne Hackborn5ae74d62010-05-19 19:14:57 -07004013 if (FragmentManager.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4014 + Integer.toHexString(id) + " fname=" + fname
4015 + " existing=" + fragment);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004016 if (fragment == null) {
4017 fragment = Fragment.instantiate(this, fname);
4018 fragment.mFromLayout = true;
4019 fragment.mFragmentId = id;
4020 fragment.mTag = tag;
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004021 fragment.mImmediateActivity = this;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004022 mFragments.addFragment(fragment, true);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004023 }
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004024 // If this fragment is newly instantiated (either right now, or
4025 // from last saved state), then give it the attributes to
4026 // initialize itself.
4027 if (!fragment.mRetaining) {
4028 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
4029 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004030 if (fragment.mView == null) {
4031 throw new IllegalStateException("Fragment " + fname
4032 + " did not create a view.");
4033 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004034 fragment.mView.setId(id);
4035 if (fragment.mView.getTag() == null) {
4036 fragment.mView.setTag(tag);
4037 }
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004038 return fragment.mView;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004039 } catch (Exception e) {
4040 InflateException ie = new InflateException(attrs.getPositionDescription()
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004041 + ": Error inflating fragment " + fname);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004042 ie.initCause(e);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004043 throw ie;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 }
4046
Daniel Sandler69a48172010-06-23 16:29:36 -04004047 /**
4048 * Bit indicating that this activity is "immersive" and should not be
4049 * interrupted by notifications if possible.
4050 *
4051 * This value is initially set by the manifest property
4052 * <code>android:immersive</code> but may be changed at runtime by
4053 * {@link #setImmersive}.
4054 *
4055 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4056 */
4057 public boolean isImmersive() {
4058 try {
4059 return ActivityManagerNative.getDefault().isImmersive(mToken);
4060 } catch (RemoteException e) {
4061 return false;
4062 }
4063 }
4064
4065 /**
4066 * Adjust the current immersive mode setting.
4067 *
4068 * Note that changing this value will have no effect on the activity's
4069 * {@link android.content.pm.ActivityInfo} structure; that is, if
4070 * <code>android:immersive</code> is set to <code>true</code>
4071 * in the application's manifest entry for this activity, the {@link
4072 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4073 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4074 * FLAG_IMMERSIVE} bit set.
4075 *
4076 * @see #isImmersive
4077 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4078 */
4079 public void setImmersive(boolean i) {
4080 try {
4081 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4082 } catch (RemoteException e) {
4083 // pass
4084 }
4085 }
4086
Adam Powell6e346362010-07-23 10:18:23 -07004087 /**
4088 * Start a context mode.
4089 *
4090 * @param callback Callback that will manage lifecycle events for this context mode
4091 * @return The ContextMode that was started, or null if it was canceled
4092 *
4093 * @see ActionMode
4094 */
Adam Powell5d279772010-07-27 16:34:07 -07004095 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004096 return mWindow.getDecorView().startActionMode(callback);
4097 }
4098
4099 public ActionMode onStartActionMode(ActionMode.Callback callback) {
4100 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004101 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004102 }
4103 return null;
4104 }
4105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 // ------------------ Internal API ------------------
4107
4108 final void setParent(Activity parent) {
4109 mParent = parent;
4110 }
4111
4112 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4113 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004114 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004116 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004117 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 }
4119
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004120 final void attach(Context context, ActivityThread aThread,
4121 Instrumentation instr, IBinder token, int ident,
4122 Application application, Intent intent, ActivityInfo info,
4123 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004124 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004125 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 attachBaseContext(context);
4127
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004128 mFragments.attachActivity(this);
4129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 mWindow = PolicyManager.makeNewWindow(this);
4131 mWindow.setCallback(this);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004132 mWindow.getLayoutInflater().setFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4134 mWindow.setSoftInputMode(info.softInputMode);
4135 }
4136 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 mMainThread = aThread;
4139 mInstrumentation = instr;
4140 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004141 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 mApplication = application;
4143 mIntent = intent;
4144 mComponent = intent.getComponent();
4145 mActivityInfo = info;
4146 mTitle = title;
4147 mParent = parent;
4148 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004149 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150
Romain Guy529b60a2010-08-03 18:05:47 -07004151 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4152 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 if (mParent != null) {
4154 mWindow.setContainer(mParent.getWindow());
4155 }
4156 mWindowManager = mWindow.getWindowManager();
4157 mCurrentConfig = config;
4158 }
4159
4160 final IBinder getActivityToken() {
4161 return mParent != null ? mParent.getActivityToken() : mToken;
4162 }
4163
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004164 final void performCreate(Bundle icicle) {
4165 onCreate(icicle);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004166 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004167 }
4168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 final void performStart() {
4170 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004171 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 mInstrumentation.callActivityOnStart(this);
4173 if (!mCalled) {
4174 throw new SuperNotCalledException(
4175 "Activity " + mComponent.toShortString() +
4176 " did not call through to super.onStart()");
4177 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004178 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004179 if (mAllLoaderManagers != null) {
4180 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4181 mAllLoaderManagers.valueAt(i).finishRetain();
4182 }
4183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 }
4185
4186 final void performRestart() {
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004187 synchronized (mManagedCursors) {
4188 final int N = mManagedCursors.size();
4189 for (int i=0; i<N; i++) {
4190 ManagedCursor mc = mManagedCursors.get(i);
4191 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004192 if (!mc.mCursor.requery()) {
4193 throw new IllegalStateException(
4194 "trying to requery an already closed cursor");
4195 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004196 mc.mReleased = false;
4197 mc.mUpdated = false;
4198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 }
4200 }
4201
4202 if (mStopped) {
4203 mStopped = false;
4204 mCalled = false;
4205 mInstrumentation.callActivityOnRestart(this);
4206 if (!mCalled) {
4207 throw new SuperNotCalledException(
4208 "Activity " + mComponent.toShortString() +
4209 " did not call through to super.onRestart()");
4210 }
4211 performStart();
4212 }
4213 }
4214
4215 final void performResume() {
4216 performRestart();
4217
Dianne Hackborn445646c2010-06-25 15:52:59 -07004218 mFragments.execPendingActions();
4219
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004220 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221
4222 // First call onResume() -before- setting mResumed, so we don't
4223 // send out any status bar / menu notifications the client makes.
4224 mCalled = false;
4225 mInstrumentation.callActivityOnResume(this);
4226 if (!mCalled) {
4227 throw new SuperNotCalledException(
4228 "Activity " + mComponent.toShortString() +
4229 " did not call through to super.onResume()");
4230 }
4231
4232 // Now really resume, and install the current status bar and menu.
4233 mResumed = true;
4234 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004235
4236 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004237 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 onPostResume();
4240 if (!mCalled) {
4241 throw new SuperNotCalledException(
4242 "Activity " + mComponent.toShortString() +
4243 " did not call through to super.onPostResume()");
4244 }
4245 }
4246
4247 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004248 mFragments.dispatchPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 onPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251
4252 final void performUserLeaving() {
4253 onUserInteraction();
4254 onUserLeaveHint();
4255 }
4256
4257 final void performStop() {
Dianne Hackborn2707d602010-07-09 18:01:20 -07004258 if (mStarted) {
4259 mStarted = false;
4260 if (mLoaderManager != null) {
4261 if (!mChangingConfigurations) {
4262 mLoaderManager.doStop();
4263 } else {
4264 mLoaderManager.doRetain();
4265 }
4266 }
4267 }
4268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 if (!mStopped) {
4270 if (mWindow != null) {
4271 mWindow.closeAllPanels();
4272 }
4273
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004274 mFragments.dispatchStop();
4275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 mCalled = false;
4277 mInstrumentation.callActivityOnStop(this);
4278 if (!mCalled) {
4279 throw new SuperNotCalledException(
4280 "Activity " + mComponent.toShortString() +
4281 " did not call through to super.onStop()");
4282 }
4283
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004284 synchronized (mManagedCursors) {
4285 final int N = mManagedCursors.size();
4286 for (int i=0; i<N; i++) {
4287 ManagedCursor mc = mManagedCursors.get(i);
4288 if (!mc.mReleased) {
4289 mc.mCursor.deactivate();
4290 mc.mReleased = true;
4291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
4293 }
4294
4295 mStopped = true;
4296 }
4297 mResumed = false;
4298 }
4299
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004300 final void performDestroy() {
4301 mFragments.dispatchDestroy();
4302 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004303 if (mLoaderManager != null) {
4304 mLoaderManager.doDestroy();
4305 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004306 }
4307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 final boolean isResumed() {
4309 return mResumed;
4310 }
4311
4312 void dispatchActivityResult(String who, int requestCode,
4313 int resultCode, Intent data) {
4314 if (Config.LOGV) Log.v(
4315 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4316 + ", resCode=" + resultCode + ", data=" + data);
4317 if (who == null) {
4318 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004319 } else {
4320 Fragment frag = mFragments.findFragmentByWho(who);
4321 if (frag != null) {
4322 frag.onActivityResult(requestCode, resultCode, data);
4323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 }
4325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326}