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