blob: 378a8bdb1ca22eb7a6436c585add3bb88a1cfc93 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Adam Powell6e346362010-07-23 10:18:23 -070019import com.android.internal.app.ActionBarImpl;
20import com.android.internal.policy.PolicyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ComponentCallbacks;
23import android.content.ComponentName;
24import android.content.ContentResolver;
25import android.content.Context;
Jason parks6ed50de2010-08-25 10:18:50 -050026import android.content.CursorLoader;
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 Powell6e346362010-07-23 10:18:23 -070056import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070058import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.ContextThemeWrapper;
60import android.view.KeyEvent;
61import android.view.LayoutInflater;
62import android.view.Menu;
63import android.view.MenuInflater;
64import android.view.MenuItem;
65import android.view.MotionEvent;
66import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -070067import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070069import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.ViewManager;
71import android.view.Window;
72import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070073import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.widget.AdapterView;
Jim Miller0b2a6d02010-07-13 18:01:29 -070075import android.widget.FrameLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
Dianne Hackborn625ac272010-09-17 18:29:22 -070077import java.io.FileDescriptor;
78import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070079import java.util.ArrayList;
80import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82/**
83 * An activity is a single, focused thing that the user can do. Almost all
84 * activities interact with the user, so the Activity class takes care of
85 * creating a window for you in which you can place your UI with
86 * {@link #setContentView}. While activities are often presented to the user
87 * as full-screen windows, they can also be used in other ways: as floating
88 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
89 * or embedded inside of another activity (using {@link ActivityGroup}).
90 *
91 * There are two methods almost all subclasses of Activity will implement:
92 *
93 * <ul>
94 * <li> {@link #onCreate} is where you initialize your activity. Most
95 * importantly, here you will usually call {@link #setContentView(int)}
96 * with a layout resource defining your UI, and using {@link #findViewById}
97 * to retrieve the widgets in that UI that you need to interact with
98 * programmatically.
99 *
100 * <li> {@link #onPause} is where you deal with the user leaving your
101 * activity. Most importantly, any changes made by the user should at this
102 * point be committed (usually to the
103 * {@link android.content.ContentProvider} holding the data).
104 * </ul>
105 *
106 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
107 * activity classes must have a corresponding
108 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
109 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
110 *
111 * <p>The Activity class is an important part of an application's overall lifecycle,
112 * and the way activities are launched and put together is a fundamental
113 * part of the platform's application model. For a detailed perspective on the structure of
114 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
115 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
116 *
117 * <p>Topics covered here:
118 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700119 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
121 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
122 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
123 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
124 * <li><a href="#Permissions">Permissions</a>
125 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
126 * </ol>
127 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700128 * <a name="Fragments"></a>
129 * <h3>Fragments</h3>
130 *
131 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
132 * implementations can make use of the {@link Fragment} class to better
133 * modularize their code, build more sophisticated user interfaces for larger
134 * screens, and help scale their application between small and large screens.
135 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 * <a name="ActivityLifecycle"></a>
137 * <h3>Activity Lifecycle</h3>
138 *
139 * <p>Activities in the system are managed as an <em>activity stack</em>.
140 * When a new activity is started, it is placed on the top of the stack
141 * and becomes the running activity -- the previous activity always remains
142 * below it in the stack, and will not come to the foreground again until
143 * the new activity exits.</p>
144 *
145 * <p>An activity has essentially four states:</p>
146 * <ul>
147 * <li> If an activity in the foreground of the screen (at the top of
148 * the stack),
149 * it is <em>active</em> or <em>running</em>. </li>
150 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
151 * or transparent activity has focus on top of your activity), it
152 * is <em>paused</em>. A paused activity is completely alive (it
153 * maintains all state and member information and remains attached to
154 * the window manager), but can be killed by the system in extreme
155 * low memory situations.
156 * <li>If an activity is completely obscured by another activity,
157 * it is <em>stopped</em>. It still retains all state and member information,
158 * however, it is no longer visible to the user so its window is hidden
159 * and it will often be killed by the system when memory is needed
160 * elsewhere.</li>
161 * <li>If an activity is paused or stopped, the system can drop the activity
162 * from memory by either asking it to finish, or simply killing its
163 * process. When it is displayed again to the user, it must be
164 * completely restarted and restored to its previous state.</li>
165 * </ul>
166 *
167 * <p>The following diagram shows the important state paths of an Activity.
168 * The square rectangles represent callback methods you can implement to
169 * perform operations when the Activity moves between states. The colored
170 * ovals are major states the Activity can be in.</p>
171 *
172 * <p><img src="../../../images/activity_lifecycle.png"
173 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
174 *
175 * <p>There are three key loops you may be interested in monitoring within your
176 * activity:
177 *
178 * <ul>
179 * <li>The <b>entire lifetime</b> of an activity happens between the first call
180 * to {@link android.app.Activity#onCreate} through to a single final call
181 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
182 * of "global" state in onCreate(), and release all remaining resources in
183 * onDestroy(). For example, if it has a thread running in the background
184 * to download data from the network, it may create that thread in onCreate()
185 * and then stop the thread in onDestroy().
186 *
187 * <li>The <b>visible lifetime</b> of an activity happens between a call to
188 * {@link android.app.Activity#onStart} until a corresponding call to
189 * {@link android.app.Activity#onStop}. During this time the user can see the
190 * activity on-screen, though it may not be in the foreground and interacting
191 * with the user. Between these two methods you can maintain resources that
192 * are needed to show the activity to the user. For example, you can register
193 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
194 * that impact your UI, and unregister it in onStop() when the user an no
195 * longer see what you are displaying. The onStart() and onStop() methods
196 * can be called multiple times, as the activity becomes visible and hidden
197 * to the user.
198 *
199 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
200 * {@link android.app.Activity#onResume} until a corresponding call to
201 * {@link android.app.Activity#onPause}. During this time the activity is
202 * in front of all other activities and interacting with the user. An activity
203 * can frequently go between the resumed and paused states -- for example when
204 * the device goes to sleep, when an activity result is delivered, when a new
205 * intent is delivered -- so the code in these methods should be fairly
206 * lightweight.
207 * </ul>
208 *
209 * <p>The entire lifecycle of an activity is defined by the following
210 * Activity methods. All of these are hooks that you can override
211 * to do appropriate work when the activity changes state. All
212 * activities will implement {@link android.app.Activity#onCreate}
213 * to do their initial setup; many will also implement
214 * {@link android.app.Activity#onPause} to commit changes to data and
215 * otherwise prepare to stop interacting with the user. You should always
216 * call up to your superclass when implementing these methods.</p>
217 *
218 * </p>
219 * <pre class="prettyprint">
220 * public class Activity extends ApplicationContext {
221 * protected void onCreate(Bundle savedInstanceState);
222 *
223 * protected void onStart();
224 *
225 * protected void onRestart();
226 *
227 * protected void onResume();
228 *
229 * protected void onPause();
230 *
231 * protected void onStop();
232 *
233 * protected void onDestroy();
234 * }
235 * </pre>
236 *
237 * <p>In general the movement through an activity's lifecycle looks like
238 * this:</p>
239 *
240 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
241 * <colgroup align="left" span="3" />
242 * <colgroup align="left" />
243 * <colgroup align="center" />
244 * <colgroup align="center" />
245 *
246 * <thead>
247 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
248 * </thead>
249 *
250 * <tbody>
251 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
252 * <td>Called when the activity is first created.
253 * This is where you should do all of your normal static set up:
254 * create views, bind data to lists, etc. This method also
255 * provides you with a Bundle containing the activity's previously
256 * frozen state, if there was one.
257 * <p>Always followed by <code>onStart()</code>.</td>
258 * <td align="center">No</td>
259 * <td align="center"><code>onStart()</code></td>
260 * </tr>
261 *
262 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
263 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
264 * <td>Called after your activity has been stopped, prior to it being
265 * started again.
266 * <p>Always followed by <code>onStart()</code></td>
267 * <td align="center">No</td>
268 * <td align="center"><code>onStart()</code></td>
269 * </tr>
270 *
271 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
272 * <td>Called when the activity is becoming visible to the user.
273 * <p>Followed by <code>onResume()</code> if the activity comes
274 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
275 * <td align="center">No</td>
276 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
277 * </tr>
278 *
279 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
280 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
281 * <td>Called when the activity will start
282 * interacting with the user. At this point your activity is at
283 * the top of the activity stack, with user input going to it.
284 * <p>Always followed by <code>onPause()</code>.</td>
285 * <td align="center">No</td>
286 * <td align="center"><code>onPause()</code></td>
287 * </tr>
288 *
289 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
290 * <td>Called when the system is about to start resuming a previous
291 * activity. This is typically used to commit unsaved changes to
292 * persistent data, stop animations and other things that may be consuming
293 * CPU, etc. Implementations of this method must be very quick because
294 * the next activity will not be resumed until this method returns.
295 * <p>Followed by either <code>onResume()</code> if the activity
296 * returns back to the front, or <code>onStop()</code> if it becomes
297 * invisible to the user.</td>
298 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
299 * <td align="center"><code>onResume()</code> or<br>
300 * <code>onStop()</code></td>
301 * </tr>
302 *
303 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
304 * <td>Called when the activity is no longer visible to the user, because
305 * another activity has been resumed and is covering this one. This
306 * may happen either because a new activity is being started, an existing
307 * one is being brought in front of this one, or this one is being
308 * destroyed.
309 * <p>Followed by either <code>onRestart()</code> if
310 * this activity is coming back to interact with the user, or
311 * <code>onDestroy()</code> if this activity is going away.</td>
312 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
313 * <td align="center"><code>onRestart()</code> or<br>
314 * <code>onDestroy()</code></td>
315 * </tr>
316 *
317 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
318 * <td>The final call you receive before your
319 * activity is destroyed. This can happen either because the
320 * activity is finishing (someone called {@link Activity#finish} on
321 * it, or because the system is temporarily destroying this
322 * instance of the activity to save space. You can distinguish
323 * between these two scenarios with the {@link
324 * Activity#isFinishing} method.</td>
325 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
326 * <td align="center"><em>nothing</em></td>
327 * </tr>
328 * </tbody>
329 * </table>
330 *
331 * <p>Note the "Killable" column in the above table -- for those methods that
332 * are marked as being killable, after that method returns the process hosting the
333 * activity may killed by the system <em>at any time</em> without another line
334 * of its code being executed. Because of this, you should use the
335 * {@link #onPause} method to write any persistent data (such as user edits)
336 * to storage. In addition, the method
337 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
338 * in such a background state, allowing you to save away any dynamic instance
339 * state in your activity into the given Bundle, to be later received in
340 * {@link #onCreate} if the activity needs to be re-created.
341 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
342 * section for more information on how the lifecycle of a process is tied
343 * to the activities it is hosting. Note that it is important to save
344 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
345 * because the later is not part of the lifecycle callbacks, so will not
346 * be called in every situation as described in its documentation.</p>
347 *
348 * <p>For those methods that are not marked as being killable, the activity's
349 * process will not be killed by the system starting from the time the method
350 * is called and continuing after it returns. Thus an activity is in the killable
351 * state, for example, between after <code>onPause()</code> to the start of
352 * <code>onResume()</code>.</p>
353 *
354 * <a name="ConfigurationChanges"></a>
355 * <h3>Configuration Changes</h3>
356 *
357 * <p>If the configuration of the device (as defined by the
358 * {@link Configuration Resources.Configuration} class) changes,
359 * then anything displaying a user interface will need to update to match that
360 * configuration. Because Activity is the primary mechanism for interacting
361 * with the user, it includes special support for handling configuration
362 * changes.</p>
363 *
364 * <p>Unless you specify otherwise, a configuration change (such as a change
365 * in screen orientation, language, input devices, etc) will cause your
366 * current activity to be <em>destroyed</em>, going through the normal activity
367 * lifecycle process of {@link #onPause},
368 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
369 * had been in the foreground or visible to the user, once {@link #onDestroy} is
370 * called in that instance then a new instance of the activity will be
371 * created, with whatever savedInstanceState the previous instance had generated
372 * from {@link #onSaveInstanceState}.</p>
373 *
374 * <p>This is done because any application resource,
375 * including layout files, can change based on any configuration value. Thus
376 * the only safe way to handle a configuration change is to re-retrieve all
377 * resources, including layouts, drawables, and strings. Because activities
378 * must already know how to save their state and re-create themselves from
379 * that state, this is a convenient way to have an activity restart itself
380 * with a new configuration.</p>
381 *
382 * <p>In some special cases, you may want to bypass restarting of your
383 * activity based on one or more types of configuration changes. This is
384 * done with the {@link android.R.attr#configChanges android:configChanges}
385 * attribute in its manifest. For any types of configuration changes you say
386 * that you handle there, you will receive a call to your current activity's
387 * {@link #onConfigurationChanged} method instead of being restarted. If
388 * a configuration change involves any that you do not handle, however, the
389 * activity will still be restarted and {@link #onConfigurationChanged}
390 * will not be called.</p>
391 *
392 * <a name="StartingActivities"></a>
393 * <h3>Starting Activities and Getting Results</h3>
394 *
395 * <p>The {@link android.app.Activity#startActivity}
396 * method is used to start a
397 * new activity, which will be placed at the top of the activity stack. It
398 * takes a single argument, an {@link android.content.Intent Intent},
399 * which describes the activity
400 * to be executed.</p>
401 *
402 * <p>Sometimes you want to get a result back from an activity when it
403 * ends. For example, you may start an activity that lets the user pick
404 * a person in a list of contacts; when it ends, it returns the person
405 * that was selected. To do this, you call the
406 * {@link android.app.Activity#startActivityForResult(Intent, int)}
407 * version with a second integer parameter identifying the call. The result
408 * will come back through your {@link android.app.Activity#onActivityResult}
409 * method.</p>
410 *
411 * <p>When an activity exits, it can call
412 * {@link android.app.Activity#setResult(int)}
413 * to return data back to its parent. It must always supply a result code,
414 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
415 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
416 * return back an Intent containing any additional data it wants. All of this
417 * information appears back on the
418 * parent's <code>Activity.onActivityResult()</code>, along with the integer
419 * identifier it originally supplied.</p>
420 *
421 * <p>If a child activity fails for any reason (such as crashing), the parent
422 * activity will receive a result with the code RESULT_CANCELED.</p>
423 *
424 * <pre class="prettyprint">
425 * public class MyActivity extends Activity {
426 * ...
427 *
428 * static final int PICK_CONTACT_REQUEST = 0;
429 *
430 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
431 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
432 * // When the user center presses, let them pick a contact.
433 * startActivityForResult(
434 * new Intent(Intent.ACTION_PICK,
435 * new Uri("content://contacts")),
436 * PICK_CONTACT_REQUEST);
437 * return true;
438 * }
439 * return false;
440 * }
441 *
442 * protected void onActivityResult(int requestCode, int resultCode,
443 * Intent data) {
444 * if (requestCode == PICK_CONTACT_REQUEST) {
445 * if (resultCode == RESULT_OK) {
446 * // A contact was picked. Here we will just display it
447 * // to the user.
448 * startActivity(new Intent(Intent.ACTION_VIEW, data));
449 * }
450 * }
451 * }
452 * }
453 * </pre>
454 *
455 * <a name="SavingPersistentState"></a>
456 * <h3>Saving Persistent State</h3>
457 *
458 * <p>There are generally two kinds of persistent state than an activity
459 * will deal with: shared document-like data (typically stored in a SQLite
460 * database using a {@linkplain android.content.ContentProvider content provider})
461 * and internal state such as user preferences.</p>
462 *
463 * <p>For content provider data, we suggest that activities use a
464 * "edit in place" user model. That is, any edits a user makes are effectively
465 * made immediately without requiring an additional confirmation step.
466 * Supporting this model is generally a simple matter of following two rules:</p>
467 *
468 * <ul>
469 * <li> <p>When creating a new document, the backing database entry or file for
470 * it is created immediately. For example, if the user chooses to write
471 * a new e-mail, a new entry for that e-mail is created as soon as they
472 * start entering data, so that if they go to any other activity after
473 * that point this e-mail will now appear in the list of drafts.</p>
474 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
475 * commit to the backing content provider or file any changes the user
476 * has made. This ensures that those changes will be seen by any other
477 * activity that is about to run. You will probably want to commit
478 * your data even more aggressively at key times during your
479 * activity's lifecycle: for example before starting a new
480 * activity, before finishing your own activity, when the user
481 * switches between input fields, etc.</p>
482 * </ul>
483 *
484 * <p>This model is designed to prevent data loss when a user is navigating
485 * between activities, and allows the system to safely kill an activity (because
486 * system resources are needed somewhere else) at any time after it has been
487 * paused. Note this implies
488 * that the user pressing BACK from your activity does <em>not</em>
489 * mean "cancel" -- it means to leave the activity with its current contents
490 * saved away. Cancelling edits in an activity must be provided through
491 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
492 *
493 * <p>See the {@linkplain android.content.ContentProvider content package} for
494 * more information about content providers. These are a key aspect of how
495 * different activities invoke and propagate data between themselves.</p>
496 *
497 * <p>The Activity class also provides an API for managing internal persistent state
498 * associated with an activity. This can be used, for example, to remember
499 * the user's preferred initial display in a calendar (day view or week view)
500 * or the user's default home page in a web browser.</p>
501 *
502 * <p>Activity persistent state is managed
503 * with the method {@link #getPreferences},
504 * allowing you to retrieve and
505 * modify a set of name/value pairs associated with the activity. To use
506 * preferences that are shared across multiple application components
507 * (activities, receivers, services, providers), you can use the underlying
508 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
509 * to retrieve a preferences
510 * object stored under a specific name.
511 * (Note that it is not possible to share settings data across application
512 * packages -- for that you will need a content provider.)</p>
513 *
514 * <p>Here is an excerpt from a calendar activity that stores the user's
515 * preferred view mode in its persistent settings:</p>
516 *
517 * <pre class="prettyprint">
518 * public class CalendarActivity extends Activity {
519 * ...
520 *
521 * static final int DAY_VIEW_MODE = 0;
522 * static final int WEEK_VIEW_MODE = 1;
523 *
524 * private SharedPreferences mPrefs;
525 * private int mCurViewMode;
526 *
527 * protected void onCreate(Bundle savedInstanceState) {
528 * super.onCreate(savedInstanceState);
529 *
530 * SharedPreferences mPrefs = getSharedPreferences();
531 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
532 * }
533 *
534 * protected void onPause() {
535 * super.onPause();
536 *
537 * SharedPreferences.Editor ed = mPrefs.edit();
538 * ed.putInt("view_mode", mCurViewMode);
539 * ed.commit();
540 * }
541 * }
542 * </pre>
543 *
544 * <a name="Permissions"></a>
545 * <h3>Permissions</h3>
546 *
547 * <p>The ability to start a particular Activity can be enforced when it is
548 * declared in its
549 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
550 * tag. By doing so, other applications will need to declare a corresponding
551 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
552 * element in their own manifest to be able to start that activity.
553 *
554 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
555 * document for more information on permissions and security in general.
556 *
557 * <a name="ProcessLifecycle"></a>
558 * <h3>Process Lifecycle</h3>
559 *
560 * <p>The Android system attempts to keep application process around for as
561 * long as possible, but eventually will need to remove old processes when
562 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
563 * Lifecycle</a>, the decision about which process to remove is intimately
564 * tied to the state of the user's interaction with it. In general, there
565 * are four states a process can be in based on the activities running in it,
566 * listed here in order of importance. The system will kill less important
567 * processes (the last ones) before it resorts to killing more important
568 * processes (the first ones).
569 *
570 * <ol>
571 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
572 * that the user is currently interacting with) is considered the most important.
573 * Its process will only be killed as a last resort, if it uses more memory
574 * than is available on the device. Generally at this point the device has
575 * reached a memory paging state, so this is required in order to keep the user
576 * interface responsive.
577 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
578 * but not in the foreground, such as one sitting behind a foreground dialog)
579 * is considered extremely important and will not be killed unless that is
580 * required to keep the foreground activity running.
581 * <li> <p>A <b>background activity</b> (an activity that is not visible to
582 * the user and has been paused) is no longer critical, so the system may
583 * safely kill its process to reclaim memory for other foreground or
584 * visible processes. If its process needs to be killed, when the user navigates
585 * back to the activity (making it visible on the screen again), its
586 * {@link #onCreate} method will be called with the savedInstanceState it had previously
587 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
588 * state as the user last left it.
589 * <li> <p>An <b>empty process</b> is one hosting no activities or other
590 * application components (such as {@link Service} or
591 * {@link android.content.BroadcastReceiver} classes). These are killed very
592 * quickly by the system as memory becomes low. For this reason, any
593 * background operation you do outside of an activity must be executed in the
594 * context of an activity BroadcastReceiver or Service to ensure that the system
595 * knows it needs to keep your process around.
596 * </ol>
597 *
598 * <p>Sometimes an Activity may need to do a long-running operation that exists
599 * independently of the activity lifecycle itself. An example may be a camera
600 * application that allows you to upload a picture to a web site. The upload
601 * may take a long time, and the application should allow the user to leave
602 * the application will it is executing. To accomplish this, your Activity
603 * should start a {@link Service} in which the upload takes place. This allows
604 * the system to properly prioritize your process (considering it to be more
605 * important than other non-visible applications) for the duration of the
606 * upload, independent of whether the original activity is paused, stopped,
607 * or finished.
608 */
609public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700610 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 Window.Callback, KeyEvent.Callback,
612 OnCreateContextMenuListener, ComponentCallbacks {
613 private static final String TAG = "Activity";
614
615 /** Standard activity result: operation canceled. */
616 public static final int RESULT_CANCELED = 0;
617 /** Standard activity result: operation succeeded. */
618 public static final int RESULT_OK = -1;
619 /** Start of user-defined activity results. */
620 public static final int RESULT_FIRST_USER = 1;
621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700623 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
625 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
626 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800627 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800629 private static class ManagedDialog {
630 Dialog mDialog;
631 Bundle mArgs;
632 }
633 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634
635 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
636 private Instrumentation mInstrumentation;
637 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700638 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 /*package*/ String mEmbeddedID;
640 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700641 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 private ComponentName mComponent;
643 /*package*/ ActivityInfo mActivityInfo;
644 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 Activity mParent;
646 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700647 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700648 boolean mLoadersStarted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 private boolean mResumed;
650 private boolean mStopped;
651 boolean mFinished;
652 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700653 /** true if the activity is going through a transient pause */
654 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500655 /** true if the activity is being destroyed in order to recreate it with a new configuration */
656 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 /*package*/ int mConfigChangeFlags;
658 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100659 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700661 static final class NonConfigurationInstances {
662 Object activity;
663 HashMap<String, Object> children;
664 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700665 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700666 }
667 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 private Window mWindow;
670
671 private WindowManager mWindowManager;
672 /*package*/ View mDecor = null;
673 /*package*/ boolean mWindowAdded = false;
674 /*package*/ boolean mVisibleFromServer = false;
675 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700676 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
678 private CharSequence mTitle;
679 private int mTitleColor = 0;
680
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700681 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700682
Dianne Hackborn4911b782010-07-15 12:54:39 -0700683 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
684 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 private static final class ManagedCursor {
687 ManagedCursor(Cursor cursor) {
688 mCursor = cursor;
689 mReleased = false;
690 mUpdated = false;
691 }
692
693 private final Cursor mCursor;
694 private boolean mReleased;
695 private boolean mUpdated;
696 }
697 private final ArrayList<ManagedCursor> mManagedCursors =
698 new ArrayList<ManagedCursor>();
699
700 // protected by synchronized (this)
701 int mResultCode = RESULT_CANCELED;
702 Intent mResultData = null;
703
704 private boolean mTitleReady = false;
705
706 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
707 private SpannableStringBuilder mDefaultKeySsb = null;
708
709 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
710
711 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700712 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 /** Return the intent that started this activity. */
715 public Intent getIntent() {
716 return mIntent;
717 }
718
719 /**
720 * Change the intent returned by {@link #getIntent}. This holds a
721 * reference to the given intent; it does not copy it. Often used in
722 * conjunction with {@link #onNewIntent}.
723 *
724 * @param newIntent The new Intent object to return from getIntent
725 *
726 * @see #getIntent
727 * @see #onNewIntent
728 */
729 public void setIntent(Intent newIntent) {
730 mIntent = newIntent;
731 }
732
733 /** Return the application that owns this activity. */
734 public final Application getApplication() {
735 return mApplication;
736 }
737
738 /** Is this activity embedded inside of another activity? */
739 public final boolean isChild() {
740 return mParent != null;
741 }
742
743 /** Return the parent activity if this view is an embedded child. */
744 public final Activity getParent() {
745 return mParent;
746 }
747
748 /** Retrieve the window manager for showing custom windows. */
749 public WindowManager getWindowManager() {
750 return mWindowManager;
751 }
752
753 /**
754 * Retrieve the current {@link android.view.Window} for the activity.
755 * This can be used to directly access parts of the Window API that
756 * are not available through Activity/Screen.
757 *
758 * @return Window The current window, or null if the activity is not
759 * visual.
760 */
761 public Window getWindow() {
762 return mWindow;
763 }
764
765 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700766 * Return the LoaderManager for this fragment, creating it if needed.
767 */
768 public LoaderManager getLoaderManager() {
769 if (mLoaderManager != null) {
770 return mLoaderManager;
771 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700772 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700773 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700774 return mLoaderManager;
775 }
776
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700777 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700778 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700779 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700780 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700781 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700782 if (lm == null) {
783 if (create) {
784 lm = new LoaderManagerImpl(this, started);
785 mAllLoaderManagers.put(index, lm);
786 }
787 } else {
788 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700789 }
790 return lm;
791 }
792
793 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 * Calls {@link android.view.Window#getCurrentFocus} on the
795 * Window of this Activity to return the currently focused view.
796 *
797 * @return View The current View with focus or null.
798 *
799 * @see #getWindow
800 * @see android.view.Window#getCurrentFocus
801 */
802 public View getCurrentFocus() {
803 return mWindow != null ? mWindow.getCurrentFocus() : null;
804 }
805
806 @Override
807 public int getWallpaperDesiredMinimumWidth() {
808 int width = super.getWallpaperDesiredMinimumWidth();
809 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
810 }
811
812 @Override
813 public int getWallpaperDesiredMinimumHeight() {
814 int height = super.getWallpaperDesiredMinimumHeight();
815 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
816 }
817
818 /**
819 * Called when the activity is starting. This is where most initialization
820 * should go: calling {@link #setContentView(int)} to inflate the
821 * activity's UI, using {@link #findViewById} to programmatically interact
822 * with widgets in the UI, calling
823 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
824 * cursors for data being displayed, etc.
825 *
826 * <p>You can call {@link #finish} from within this function, in
827 * which case onDestroy() will be immediately called without any of the rest
828 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
829 * {@link #onPause}, etc) executing.
830 *
831 * <p><em>Derived classes must call through to the super class's
832 * implementation of this method. If they do not, an exception will be
833 * thrown.</em></p>
834 *
835 * @param savedInstanceState If the activity is being re-initialized after
836 * previously being shut down then this Bundle contains the data it most
837 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
838 *
839 * @see #onStart
840 * @see #onSaveInstanceState
841 * @see #onRestoreInstanceState
842 * @see #onPostCreate
843 */
844 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700845 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
846 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackborn2707d602010-07-09 18:01:20 -0700847 if (mLastNonConfigurationInstances != null) {
848 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
849 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700850 if (savedInstanceState != null) {
851 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
852 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
853 ? mLastNonConfigurationInstances.fragments : null);
854 }
855 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 mCalled = true;
857 }
858
859 /**
860 * The hook for {@link ActivityThread} to restore the state of this activity.
861 *
862 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
863 * {@link #restoreManagedDialogs(android.os.Bundle)}.
864 *
865 * @param savedInstanceState contains the saved state
866 */
867 final void performRestoreInstanceState(Bundle savedInstanceState) {
868 onRestoreInstanceState(savedInstanceState);
869 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
872 /**
873 * This method is called after {@link #onStart} when the activity is
874 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800875 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 * to restore their state, but it is sometimes convenient to do it here
877 * after all of the initialization has been done or to allow subclasses to
878 * decide whether to use your default implementation. The default
879 * implementation of this method performs a restore of any view state that
880 * had previously been frozen by {@link #onSaveInstanceState}.
881 *
882 * <p>This method is called between {@link #onStart} and
883 * {@link #onPostCreate}.
884 *
885 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
886 *
887 * @see #onCreate
888 * @see #onPostCreate
889 * @see #onResume
890 * @see #onSaveInstanceState
891 */
892 protected void onRestoreInstanceState(Bundle savedInstanceState) {
893 if (mWindow != null) {
894 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
895 if (windowState != null) {
896 mWindow.restoreHierarchyState(windowState);
897 }
898 }
899 }
900
901 /**
902 * Restore the state of any saved managed dialogs.
903 *
904 * @param savedInstanceState The bundle to restore from.
905 */
906 private void restoreManagedDialogs(Bundle savedInstanceState) {
907 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
908 if (b == null) {
909 return;
910 }
911
912 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
913 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800914 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 for (int i = 0; i < numDialogs; i++) {
916 final Integer dialogId = ids[i];
917 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
918 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700919 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
920 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800921 final ManagedDialog md = new ManagedDialog();
922 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
923 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
924 if (md.mDialog != null) {
925 mManagedDialogs.put(dialogId, md);
926 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
927 md.mDialog.onRestoreInstanceState(dialogState);
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930 }
931 }
932
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800933 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
934 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700935 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800936 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700937 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700938 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700939 return dialog;
940 }
941
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800942 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 return SAVED_DIALOG_KEY_PREFIX + key;
944 }
945
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800946 private static String savedDialogArgsKeyFor(int key) {
947 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949
950 /**
951 * Called when activity start-up is complete (after {@link #onStart}
952 * and {@link #onRestoreInstanceState} have been called). Applications will
953 * generally not implement this method; it is intended for system
954 * classes to do final initialization after application code has run.
955 *
956 * <p><em>Derived classes must call through to the super class's
957 * implementation of this method. If they do not, an exception will be
958 * thrown.</em></p>
959 *
960 * @param savedInstanceState If the activity is being re-initialized after
961 * previously being shut down then this Bundle contains the data it most
962 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
963 * @see #onCreate
964 */
965 protected void onPostCreate(Bundle savedInstanceState) {
966 if (!isChild()) {
967 mTitleReady = true;
968 onTitleChanged(getTitle(), getTitleColor());
969 }
970 mCalled = true;
971 }
972
973 /**
974 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
975 * the activity had been stopped, but is now again being displayed to the
976 * user. It will be followed by {@link #onResume}.
977 *
978 * <p><em>Derived classes must call through to the super class's
979 * implementation of this method. If they do not, an exception will be
980 * thrown.</em></p>
981 *
982 * @see #onCreate
983 * @see #onStop
984 * @see #onResume
985 */
986 protected void onStart() {
987 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700988
989 if (!mLoadersStarted) {
990 mLoadersStarted = true;
991 if (mLoaderManager != null) {
992 mLoaderManager.doStart();
993 } else if (!mCheckedForLoaderManager) {
994 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
995 }
996 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -0700997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999
1000 /**
1001 * Called after {@link #onStop} when the current activity is being
1002 * re-displayed to the user (the user has navigated back to it). It will
1003 * be followed by {@link #onStart} and then {@link #onResume}.
1004 *
1005 * <p>For activities that are using raw {@link Cursor} objects (instead of
1006 * creating them through
1007 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1008 * this is usually the place
1009 * where the cursor should be requeried (because you had deactivated it in
1010 * {@link #onStop}.
1011 *
1012 * <p><em>Derived classes must call through to the super class's
1013 * implementation of this method. If they do not, an exception will be
1014 * thrown.</em></p>
1015 *
1016 * @see #onStop
1017 * @see #onStart
1018 * @see #onResume
1019 */
1020 protected void onRestart() {
1021 mCalled = true;
1022 }
1023
1024 /**
1025 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1026 * {@link #onPause}, for your activity to start interacting with the user.
1027 * This is a good place to begin animations, open exclusive-access devices
1028 * (such as the camera), etc.
1029 *
1030 * <p>Keep in mind that onResume is not the best indicator that your activity
1031 * is visible to the user; a system window such as the keyguard may be in
1032 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1033 * activity is visible to the user (for example, to resume a game).
1034 *
1035 * <p><em>Derived classes must call through to the super class's
1036 * implementation of this method. If they do not, an exception will be
1037 * thrown.</em></p>
1038 *
1039 * @see #onRestoreInstanceState
1040 * @see #onRestart
1041 * @see #onPostResume
1042 * @see #onPause
1043 */
1044 protected void onResume() {
1045 mCalled = true;
1046 }
1047
1048 /**
1049 * Called when activity resume is complete (after {@link #onResume} has
1050 * been called). Applications will generally not implement this method;
1051 * it is intended for system classes to do final setup after application
1052 * resume code has run.
1053 *
1054 * <p><em>Derived classes must call through to the super class's
1055 * implementation of this method. If they do not, an exception will be
1056 * thrown.</em></p>
1057 *
1058 * @see #onResume
1059 */
1060 protected void onPostResume() {
1061 final Window win = getWindow();
1062 if (win != null) win.makeActive();
1063 mCalled = true;
1064 }
1065
1066 /**
1067 * This is called for activities that set launchMode to "singleTop" in
1068 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1069 * flag when calling {@link #startActivity}. In either case, when the
1070 * activity is re-launched while at the top of the activity stack instead
1071 * of a new instance of the activity being started, onNewIntent() will be
1072 * called on the existing instance with the Intent that was used to
1073 * re-launch it.
1074 *
1075 * <p>An activity will always be paused before receiving a new intent, so
1076 * you can count on {@link #onResume} being called after this method.
1077 *
1078 * <p>Note that {@link #getIntent} still returns the original Intent. You
1079 * can use {@link #setIntent} to update it to this new Intent.
1080 *
1081 * @param intent The new intent that was started for the activity.
1082 *
1083 * @see #getIntent
1084 * @see #setIntent
1085 * @see #onResume
1086 */
1087 protected void onNewIntent(Intent intent) {
1088 }
1089
1090 /**
1091 * The hook for {@link ActivityThread} to save the state of this activity.
1092 *
1093 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1094 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1095 *
1096 * @param outState The bundle to save the state to.
1097 */
1098 final void performSaveInstanceState(Bundle outState) {
1099 onSaveInstanceState(outState);
1100 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 }
1102
1103 /**
1104 * Called to retrieve per-instance state from an activity before being killed
1105 * so that the state can be restored in {@link #onCreate} or
1106 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1107 * will be passed to both).
1108 *
1109 * <p>This method is called before an activity may be killed so that when it
1110 * comes back some time in the future it can restore its state. For example,
1111 * if activity B is launched in front of activity A, and at some point activity
1112 * A is killed to reclaim resources, activity A will have a chance to save the
1113 * current state of its user interface via this method so that when the user
1114 * returns to activity A, the state of the user interface can be restored
1115 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1116 *
1117 * <p>Do not confuse this method with activity lifecycle callbacks such as
1118 * {@link #onPause}, which is always called when an activity is being placed
1119 * in the background or on its way to destruction, or {@link #onStop} which
1120 * is called before destruction. One example of when {@link #onPause} and
1121 * {@link #onStop} is called and not this method is when a user navigates back
1122 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1123 * on B because that particular instance will never be restored, so the
1124 * system avoids calling it. An example when {@link #onPause} is called and
1125 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1126 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1127 * killed during the lifetime of B since the state of the user interface of
1128 * A will stay intact.
1129 *
1130 * <p>The default implementation takes care of most of the UI per-instance
1131 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1132 * view in the hierarchy that has an id, and by saving the id of the currently
1133 * focused view (all of which is restored by the default implementation of
1134 * {@link #onRestoreInstanceState}). If you override this method to save additional
1135 * information not captured by each individual view, you will likely want to
1136 * call through to the default implementation, otherwise be prepared to save
1137 * all of the state of each view yourself.
1138 *
1139 * <p>If called, this method will occur before {@link #onStop}. There are
1140 * no guarantees about whether it will occur before or after {@link #onPause}.
1141 *
1142 * @param outState Bundle in which to place your saved state.
1143 *
1144 * @see #onCreate
1145 * @see #onRestoreInstanceState
1146 * @see #onPause
1147 */
1148 protected void onSaveInstanceState(Bundle outState) {
1149 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001150 Parcelable p = mFragments.saveAllState();
1151 if (p != null) {
1152 outState.putParcelable(FRAGMENTS_TAG, p);
1153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155
1156 /**
1157 * Save the state of any managed dialogs.
1158 *
1159 * @param outState place to store the saved state.
1160 */
1161 private void saveManagedDialogs(Bundle outState) {
1162 if (mManagedDialogs == null) {
1163 return;
1164 }
1165
1166 final int numDialogs = mManagedDialogs.size();
1167 if (numDialogs == 0) {
1168 return;
1169 }
1170
1171 Bundle dialogState = new Bundle();
1172
1173 int[] ids = new int[mManagedDialogs.size()];
1174
1175 // save each dialog's bundle, gather the ids
1176 for (int i = 0; i < numDialogs; i++) {
1177 final int key = mManagedDialogs.keyAt(i);
1178 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001179 final ManagedDialog md = mManagedDialogs.valueAt(i);
1180 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1181 if (md.mArgs != null) {
1182 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
1186 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1187 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1188 }
1189
1190
1191 /**
1192 * Called as part of the activity lifecycle when an activity is going into
1193 * the background, but has not (yet) been killed. The counterpart to
1194 * {@link #onResume}.
1195 *
1196 * <p>When activity B is launched in front of activity A, this callback will
1197 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1198 * so be sure to not do anything lengthy here.
1199 *
1200 * <p>This callback is mostly used for saving any persistent state the
1201 * activity is editing, to present a "edit in place" model to the user and
1202 * making sure nothing is lost if there are not enough resources to start
1203 * the new activity without first killing this one. This is also a good
1204 * place to do things like stop animations and other things that consume a
1205 * noticeable mount of CPU in order to make the switch to the next activity
1206 * as fast as possible, or to close resources that are exclusive access
1207 * such as the camera.
1208 *
1209 * <p>In situations where the system needs more memory it may kill paused
1210 * processes to reclaim resources. Because of this, you should be sure
1211 * that all of your state is saved by the time you return from
1212 * this function. In general {@link #onSaveInstanceState} is used to save
1213 * per-instance state in the activity and this method is used to store
1214 * global persistent data (in content providers, files, etc.)
1215 *
1216 * <p>After receiving this call you will usually receive a following call
1217 * to {@link #onStop} (after the next activity has been resumed and
1218 * displayed), however in some cases there will be a direct call back to
1219 * {@link #onResume} without going through the stopped state.
1220 *
1221 * <p><em>Derived classes must call through to the super class's
1222 * implementation of this method. If they do not, an exception will be
1223 * thrown.</em></p>
1224 *
1225 * @see #onResume
1226 * @see #onSaveInstanceState
1227 * @see #onStop
1228 */
1229 protected void onPause() {
1230 mCalled = true;
Brad Fitzpatrick333b8cb2010-08-26 12:04:57 -07001231 QueuedWork.waitToFinish();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233
1234 /**
1235 * Called as part of the activity lifecycle when an activity is about to go
1236 * into the background as the result of user choice. For example, when the
1237 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1238 * when an incoming phone call causes the in-call Activity to be automatically
1239 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1240 * the activity being interrupted. In cases when it is invoked, this method
1241 * is called right before the activity's {@link #onPause} callback.
1242 *
1243 * <p>This callback and {@link #onUserInteraction} are intended to help
1244 * activities manage status bar notifications intelligently; specifically,
1245 * for helping activities determine the proper time to cancel a notfication.
1246 *
1247 * @see #onUserInteraction()
1248 */
1249 protected void onUserLeaveHint() {
1250 }
1251
1252 /**
1253 * Generate a new thumbnail for this activity. This method is called before
1254 * pausing the activity, and should draw into <var>outBitmap</var> the
1255 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1256 * can use the given <var>canvas</var>, which is configured to draw into the
1257 * bitmap, for rendering if desired.
1258 *
1259 * <p>The default implementation renders the Screen's current view
1260 * hierarchy into the canvas to generate a thumbnail.
1261 *
1262 * <p>If you return false, the bitmap will be filled with a default
1263 * thumbnail.
1264 *
1265 * @param outBitmap The bitmap to contain the thumbnail.
1266 * @param canvas Can be used to render into the bitmap.
1267 *
1268 * @return Return true if you have drawn into the bitmap; otherwise after
1269 * you return it will be filled with a default thumbnail.
1270 *
1271 * @see #onCreateDescription
1272 * @see #onSaveInstanceState
1273 * @see #onPause
1274 */
1275 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Jim Miller0b2a6d02010-07-13 18:01:29 -07001276 if (mDecor == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 return false;
1278 }
1279
Jim Miller0b2a6d02010-07-13 18:01:29 -07001280 int paddingLeft = 0;
1281 int paddingRight = 0;
1282 int paddingTop = 0;
1283 int paddingBottom = 0;
1284
1285 // Find System window and use padding so we ignore space reserved for decorations
1286 // like the status bar and such.
1287 final FrameLayout top = (FrameLayout) mDecor;
1288 for (int i = 0; i < top.getChildCount(); i++) {
1289 View child = top.getChildAt(i);
1290 if (child.isFitsSystemWindowsFlagSet()) {
1291 paddingLeft = child.getPaddingLeft();
1292 paddingRight = child.getPaddingRight();
1293 paddingTop = child.getPaddingTop();
1294 paddingBottom = child.getPaddingBottom();
1295 break;
1296 }
1297 }
1298
1299 final int visibleWidth = mDecor.getWidth() - paddingLeft - paddingRight;
1300 final int visibleHeight = mDecor.getHeight() - paddingTop - paddingBottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301
1302 canvas.save();
Jim Miller0b2a6d02010-07-13 18:01:29 -07001303 canvas.scale( (float) outBitmap.getWidth() / visibleWidth,
1304 (float) outBitmap.getHeight() / visibleHeight);
1305 canvas.translate(-paddingLeft, -paddingTop);
1306 mDecor.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 canvas.restore();
1308
1309 return true;
1310 }
1311
1312 /**
1313 * Generate a new description for this activity. This method is called
1314 * before pausing the activity and can, if desired, return some textual
1315 * description of its current state to be displayed to the user.
1316 *
1317 * <p>The default implementation returns null, which will cause you to
1318 * inherit the description from the previous activity. If all activities
1319 * return null, generally the label of the top activity will be used as the
1320 * description.
1321 *
1322 * @return A description of what the user is doing. It should be short and
1323 * sweet (only a few words).
1324 *
1325 * @see #onCreateThumbnail
1326 * @see #onSaveInstanceState
1327 * @see #onPause
1328 */
1329 public CharSequence onCreateDescription() {
1330 return null;
1331 }
1332
1333 /**
1334 * Called when you are no longer visible to the user. You will next
1335 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1336 * depending on later user activity.
1337 *
1338 * <p>Note that this method may never be called, in low memory situations
1339 * where the system does not have enough memory to keep your activity's
1340 * process running after its {@link #onPause} method is called.
1341 *
1342 * <p><em>Derived classes must call through to the super class's
1343 * implementation of this method. If they do not, an exception will be
1344 * thrown.</em></p>
1345 *
1346 * @see #onRestart
1347 * @see #onResume
1348 * @see #onSaveInstanceState
1349 * @see #onDestroy
1350 */
1351 protected void onStop() {
1352 mCalled = true;
1353 }
1354
1355 /**
1356 * Perform any final cleanup before an activity is destroyed. This can
1357 * happen either because the activity is finishing (someone called
1358 * {@link #finish} on it, or because the system is temporarily destroying
1359 * this instance of the activity to save space. You can distinguish
1360 * between these two scenarios with the {@link #isFinishing} method.
1361 *
1362 * <p><em>Note: do not count on this method being called as a place for
1363 * saving data! For example, if an activity is editing data in a content
1364 * provider, those edits should be committed in either {@link #onPause} or
1365 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1366 * free resources like threads that are associated with an activity, so
1367 * that a destroyed activity does not leave such things around while the
1368 * rest of its application is still running. There are situations where
1369 * the system will simply kill the activity's hosting process without
1370 * calling this method (or any others) in it, so it should not be used to
1371 * do things that are intended to remain around after the process goes
1372 * away.
1373 *
1374 * <p><em>Derived classes must call through to the super class's
1375 * implementation of this method. If they do not, an exception will be
1376 * thrown.</em></p>
1377 *
1378 * @see #onPause
1379 * @see #onStop
1380 * @see #finish
1381 * @see #isFinishing
1382 */
1383 protected void onDestroy() {
1384 mCalled = true;
1385
1386 // dismiss any dialogs we are managing.
1387 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 final int numDialogs = mManagedDialogs.size();
1389 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001390 final ManagedDialog md = mManagedDialogs.valueAt(i);
1391 if (md.mDialog.isShowing()) {
1392 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001395 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397
1398 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001399 synchronized (mManagedCursors) {
1400 int numCursors = mManagedCursors.size();
1401 for (int i = 0; i < numCursors; i++) {
1402 ManagedCursor c = mManagedCursors.get(i);
1403 if (c != null) {
1404 c.mCursor.close();
1405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001407 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
Amith Yamasani49860442010-03-17 20:54:10 -07001409
1410 // Close any open search dialog
1411 if (mSearchManager != null) {
1412 mSearchManager.stopSearch();
1413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
1416 /**
1417 * Called by the system when the device configuration changes while your
1418 * activity is running. Note that this will <em>only</em> be called if
1419 * you have selected configurations you would like to handle with the
1420 * {@link android.R.attr#configChanges} attribute in your manifest. If
1421 * any configuration change occurs that is not selected to be reported
1422 * by that attribute, then instead of reporting it the system will stop
1423 * and restart the activity (to have it launched with the new
1424 * configuration).
1425 *
1426 * <p>At the time that this function has been called, your Resources
1427 * object will have been updated to return resource values matching the
1428 * new configuration.
1429 *
1430 * @param newConfig The new device configuration.
1431 */
1432 public void onConfigurationChanged(Configuration newConfig) {
1433 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 if (mWindow != null) {
1436 // Pass the configuration changed event to the window
1437 mWindow.onConfigurationChanged(newConfig);
1438 }
1439 }
1440
1441 /**
1442 * If this activity is being destroyed because it can not handle a
1443 * configuration parameter being changed (and thus its
1444 * {@link #onConfigurationChanged(Configuration)} method is
1445 * <em>not</em> being called), then you can use this method to discover
1446 * the set of changes that have occurred while in the process of being
1447 * destroyed. Note that there is no guarantee that these will be
1448 * accurate (other changes could have happened at any time), so you should
1449 * only use this as an optimization hint.
1450 *
1451 * @return Returns a bit field of the configuration parameters that are
1452 * changing, as defined by the {@link android.content.res.Configuration}
1453 * class.
1454 */
1455 public int getChangingConfigurations() {
1456 return mConfigChangeFlags;
1457 }
1458
1459 /**
1460 * Retrieve the non-configuration instance data that was previously
1461 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1462 * be available from the initial {@link #onCreate} and
1463 * {@link #onStart} calls to the new instance, allowing you to extract
1464 * any useful dynamic state from the previous instance.
1465 *
1466 * <p>Note that the data you retrieve here should <em>only</em> be used
1467 * as an optimization for handling configuration changes. You should always
1468 * be able to handle getting a null pointer back, and an activity must
1469 * still be able to restore itself to its previous state (through the
1470 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1471 * function returns null.
1472 *
1473 * @return Returns the object previously returned by
1474 * {@link #onRetainNonConfigurationInstance()}.
1475 */
1476 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001477 return mLastNonConfigurationInstances != null
1478 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
1480
1481 /**
1482 * Called by the system, as part of destroying an
1483 * activity due to a configuration change, when it is known that a new
1484 * instance will immediately be created for the new configuration. You
1485 * can return any object you like here, including the activity instance
1486 * itself, which can later be retrieved by calling
1487 * {@link #getLastNonConfigurationInstance()} in the new activity
1488 * instance.
1489 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001490 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1491 * or later, consider instead using a {@link Fragment} with
1492 * {@link Fragment#setRetainInstance(boolean)
1493 * Fragment.setRetainInstance(boolean}.</em>
1494 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 * <p>This function is called purely as an optimization, and you must
1496 * not rely on it being called. When it is called, a number of guarantees
1497 * will be made to help optimize configuration switching:
1498 * <ul>
1499 * <li> The function will be called between {@link #onStop} and
1500 * {@link #onDestroy}.
1501 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001502 * created after this one's {@link #onDestroy()} is called. In particular,
1503 * <em>no</em> messages will be dispatched during this time (when the returned
1504 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 * <li> The object you return here will <em>always</em> be available from
1506 * the {@link #getLastNonConfigurationInstance()} method of the following
1507 * activity instance as described there.
1508 * </ul>
1509 *
1510 * <p>These guarantees are designed so that an activity can use this API
1511 * to propagate extensive state from the old to new activity instance, from
1512 * loaded bitmaps, to network connections, to evenly actively running
1513 * threads. Note that you should <em>not</em> propagate any data that
1514 * may change based on the configuration, including any data loaded from
1515 * resources such as strings, layouts, or drawables.
1516 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001517 * <p>The guarantee of no message handling during the switch to the next
1518 * activity simplifies use with active objects. For example if your retained
1519 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1520 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1521 * not be called from the call here until you execute the next instance's
1522 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1523 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1524 * running in a separate thread.)
1525 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 * @return Return any Object holding the desired state to propagate to the
1527 * next activity instance.
1528 */
1529 public Object onRetainNonConfigurationInstance() {
1530 return null;
1531 }
1532
1533 /**
1534 * Retrieve the non-configuration instance data that was previously
1535 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1536 * be available from the initial {@link #onCreate} and
1537 * {@link #onStart} calls to the new instance, allowing you to extract
1538 * any useful dynamic state from the previous instance.
1539 *
1540 * <p>Note that the data you retrieve here should <em>only</em> be used
1541 * as an optimization for handling configuration changes. You should always
1542 * be able to handle getting a null pointer back, and an activity must
1543 * still be able to restore itself to its previous state (through the
1544 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1545 * function returns null.
1546 *
1547 * @return Returns the object previously returned by
1548 * {@link #onRetainNonConfigurationChildInstances()}
1549 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001550 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1551 return mLastNonConfigurationInstances != null
1552 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554
1555 /**
1556 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1557 * it should return either a mapping from child activity id strings to arbitrary objects,
1558 * or null. This method is intended to be used by Activity framework subclasses that control a
1559 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1560 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1561 */
1562 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1563 return null;
1564 }
1565
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001566 NonConfigurationInstances retainNonConfigurationInstances() {
1567 Object activity = onRetainNonConfigurationInstance();
1568 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1569 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001570 boolean retainLoaders = false;
1571 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001572 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001573 // have nothing useful to retain.
1574 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001575 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001576 if (lm.mRetaining) {
1577 retainLoaders = true;
1578 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001579 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001580 mAllLoaderManagers.removeAt(i);
1581 }
1582 }
1583 }
1584 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001585 return null;
1586 }
1587
1588 NonConfigurationInstances nci = new NonConfigurationInstances();
1589 nci.activity = activity;
1590 nci.children = children;
1591 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001592 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001593 return nci;
1594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 public void onLowMemory() {
1597 mCalled = true;
1598 }
1599
1600 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001601 * Return the FragmentManager for interacting with fragments associated
1602 * with this activity.
1603 */
1604 public FragmentManager getFragmentManager() {
1605 return mFragments;
1606 }
1607
1608 /**
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001609 * Start a series of edit operations on the Fragments associated with
1610 * this activity.
Dianne Hackborndef15372010-08-15 12:43:52 -07001611 * @deprecated use {@link #getFragmentManager}.
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001612 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001613 @Deprecated
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001614 public FragmentTransaction openFragmentTransaction() {
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001615 return mFragments.openTransaction();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001616 }
1617
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001618 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001619 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001620 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001621 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1622 if (lm != null) {
1623 lm.doDestroy();
1624 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001625 mAllLoaderManagers.remove(index);
1626 }
1627 }
1628
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001629 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001630 * Called when a Fragment is being attached to this activity, immediately
1631 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1632 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1633 */
1634 public void onAttachFragment(Fragment fragment) {
1635 }
1636
1637 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 * Wrapper around
1639 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1640 * that gives the resulting {@link Cursor} to call
1641 * {@link #startManagingCursor} so that the activity will manage its
1642 * lifecycle for you.
1643 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001644 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1645 * or later, consider instead using {@link LoaderManager} instead, available
1646 * via {@link #getLoaderManager()}.</em>
1647 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 * @param uri The URI of the content provider to query.
1649 * @param projection List of columns to return.
1650 * @param selection SQL WHERE clause.
1651 * @param sortOrder SQL ORDER BY clause.
1652 *
1653 * @return The Cursor that was returned by query().
1654 *
1655 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1656 * @see #startManagingCursor
1657 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001658 *
1659 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 */
Jason parks6ed50de2010-08-25 10:18:50 -05001661 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001662 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1663 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1665 if (c != null) {
1666 startManagingCursor(c);
1667 }
1668 return c;
1669 }
1670
1671 /**
1672 * Wrapper around
1673 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1674 * that gives the resulting {@link Cursor} to call
1675 * {@link #startManagingCursor} so that the activity will manage its
1676 * lifecycle for you.
1677 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001678 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1679 * or later, consider instead using {@link LoaderManager} instead, available
1680 * via {@link #getLoaderManager()}.</em>
1681 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 * @param uri The URI of the content provider to query.
1683 * @param projection List of columns to return.
1684 * @param selection SQL WHERE clause.
1685 * @param selectionArgs The arguments to selection, if any ?s are pesent
1686 * @param sortOrder SQL ORDER BY clause.
1687 *
1688 * @return The Cursor that was returned by query().
1689 *
1690 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1691 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001692 *
1693 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 */
Jason parks6ed50de2010-08-25 10:18:50 -05001695 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001696 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1697 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1699 if (c != null) {
1700 startManagingCursor(c);
1701 }
1702 return c;
1703 }
1704
1705 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 * This method allows the activity to take care of managing the given
1707 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1708 * That is, when the activity is stopped it will automatically call
1709 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1710 * it will call {@link Cursor#requery} for you. When the activity is
1711 * destroyed, all managed Cursors will be closed automatically.
1712 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001713 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1714 * or later, consider instead using {@link LoaderManager} instead, available
1715 * via {@link #getLoaderManager()}.</em>
1716 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 * @param c The Cursor to be managed.
1718 *
1719 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1720 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001721 *
1722 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 */
Jason parks6ed50de2010-08-25 10:18:50 -05001724 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 public void startManagingCursor(Cursor c) {
1726 synchronized (mManagedCursors) {
1727 mManagedCursors.add(new ManagedCursor(c));
1728 }
1729 }
1730
1731 /**
1732 * Given a Cursor that was previously given to
1733 * {@link #startManagingCursor}, stop the activity's management of that
1734 * cursor.
1735 *
1736 * @param c The Cursor that was being managed.
1737 *
1738 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001739 *
1740 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 */
Jason parks6ed50de2010-08-25 10:18:50 -05001742 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 public void stopManagingCursor(Cursor c) {
1744 synchronized (mManagedCursors) {
1745 final int N = mManagedCursors.size();
1746 for (int i=0; i<N; i++) {
1747 ManagedCursor mc = mManagedCursors.get(i);
1748 if (mc.mCursor == c) {
1749 mManagedCursors.remove(i);
1750 break;
1751 }
1752 }
1753 }
1754 }
1755
1756 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001757 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1758 * this is a no-op.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001760 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763
1764 /**
1765 * Finds a view that was identified by the id attribute from the XML that
1766 * was processed in {@link #onCreate}.
1767 *
1768 * @return The view if found or null otherwise.
1769 */
1770 public View findViewById(int id) {
1771 return getWindow().findViewById(id);
1772 }
Adam Powell33b97432010-04-20 10:01:14 -07001773
1774 /**
1775 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001776 *
Adam Powell33b97432010-04-20 10:01:14 -07001777 * @return The Activity's ActionBar, or null if it does not have one.
1778 */
1779 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001780 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001781 return mActionBar;
1782 }
1783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 /**
Adam Powell33b97432010-04-20 10:01:14 -07001785 * Creates a new ActionBar, locates the inflated ActionBarView,
1786 * initializes the ActionBar with the view, and sets mActionBar.
1787 */
1788 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001789 Window window = getWindow();
Adam Powell9b4c8042010-08-10 15:36:44 -07001790 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001791 return;
1792 }
1793
Adam Powell661c9082010-07-02 10:09:44 -07001794 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001795 }
1796
1797 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001798 * Finds a fragment that was identified by the given id either when inflated
1799 * from XML or as the container ID when added in a transaction. This only
1800 * returns fragments that are currently added to the activity's content.
1801 * @return The fragment if found or null otherwise.
Dianne Hackborndef15372010-08-15 12:43:52 -07001802 * @deprecated use {@link #getFragmentManager}.
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001803 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001804 @Deprecated
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001805 public Fragment findFragmentById(int id) {
1806 return mFragments.findFragmentById(id);
1807 }
1808
1809 /**
1810 * Finds a fragment that was identified by the given tag either when inflated
1811 * from XML or as supplied when added in a transaction. This only
1812 * returns fragments that are currently added to the activity's content.
1813 * @return The fragment if found or null otherwise.
Dianne Hackborndef15372010-08-15 12:43:52 -07001814 * @deprecated use {@link #getFragmentManager}.
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001815 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001816 @Deprecated
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001817 public Fragment findFragmentByTag(String tag) {
1818 return mFragments.findFragmentByTag(tag);
1819 }
1820
1821 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 * Set the activity content from a layout resource. The resource will be
1823 * inflated, adding all top-level views to the activity.
1824 *
1825 * @param layoutResID Resource ID to be inflated.
1826 */
1827 public void setContentView(int layoutResID) {
1828 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001829 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831
1832 /**
1833 * Set the activity content to an explicit view. This view is placed
1834 * directly into the activity's view hierarchy. It can itself be a complex
1835 * view hierarhcy.
1836 *
1837 * @param view The desired content to display.
1838 */
1839 public void setContentView(View view) {
1840 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001841 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
1844 /**
1845 * Set the activity content to an explicit view. This view is placed
1846 * directly into the activity's view hierarchy. It can itself be a complex
1847 * view hierarhcy.
1848 *
1849 * @param view The desired content to display.
1850 * @param params Layout parameters for the view.
1851 */
1852 public void setContentView(View view, ViewGroup.LayoutParams params) {
1853 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001854 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
1857 /**
1858 * Add an additional content view to the activity. Added after any existing
1859 * ones in the activity -- existing views are NOT removed.
1860 *
1861 * @param view The desired content to display.
1862 * @param params Layout parameters for the view.
1863 */
1864 public void addContentView(View view, ViewGroup.LayoutParams params) {
1865 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001866 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868
1869 /**
1870 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1871 * keys.
1872 *
1873 * @see #setDefaultKeyMode
1874 */
1875 static public final int DEFAULT_KEYS_DISABLE = 0;
1876 /**
1877 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1878 * key handling.
1879 *
1880 * @see #setDefaultKeyMode
1881 */
1882 static public final int DEFAULT_KEYS_DIALER = 1;
1883 /**
1884 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1885 * default key handling.
1886 *
1887 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1888 *
1889 * @see #setDefaultKeyMode
1890 */
1891 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1892 /**
1893 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1894 * will start an application-defined search. (If the application or activity does not
1895 * actually define a search, the the keys will be ignored.)
1896 *
1897 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1898 *
1899 * @see #setDefaultKeyMode
1900 */
1901 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1902
1903 /**
1904 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1905 * will start a global search (typically web search, but some platforms may define alternate
1906 * methods for global search)
1907 *
1908 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1909 *
1910 * @see #setDefaultKeyMode
1911 */
1912 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1913
1914 /**
1915 * Select the default key handling for this activity. This controls what
1916 * will happen to key events that are not otherwise handled. The default
1917 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1918 * floor. Other modes allow you to launch the dialer
1919 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1920 * menu without requiring the menu key be held down
1921 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1922 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1923 *
1924 * <p>Note that the mode selected here does not impact the default
1925 * handling of system keys, such as the "back" and "menu" keys, and your
1926 * activity and its views always get a first chance to receive and handle
1927 * all application keys.
1928 *
1929 * @param mode The desired default key mode constant.
1930 *
1931 * @see #DEFAULT_KEYS_DISABLE
1932 * @see #DEFAULT_KEYS_DIALER
1933 * @see #DEFAULT_KEYS_SHORTCUT
1934 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1935 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1936 * @see #onKeyDown
1937 */
1938 public final void setDefaultKeyMode(int mode) {
1939 mDefaultKeyMode = mode;
1940
1941 // Some modes use a SpannableStringBuilder to track & dispatch input events
1942 // This list must remain in sync with the switch in onKeyDown()
1943 switch (mode) {
1944 case DEFAULT_KEYS_DISABLE:
1945 case DEFAULT_KEYS_SHORTCUT:
1946 mDefaultKeySsb = null; // not used in these modes
1947 break;
1948 case DEFAULT_KEYS_DIALER:
1949 case DEFAULT_KEYS_SEARCH_LOCAL:
1950 case DEFAULT_KEYS_SEARCH_GLOBAL:
1951 mDefaultKeySsb = new SpannableStringBuilder();
1952 Selection.setSelection(mDefaultKeySsb,0);
1953 break;
1954 default:
1955 throw new IllegalArgumentException();
1956 }
1957 }
1958
1959 /**
1960 * Called when a key was pressed down and not handled by any of the views
1961 * inside of the activity. So, for example, key presses while the cursor
1962 * is inside a TextView will not trigger the event (unless it is a navigation
1963 * to another object) because TextView handles its own key presses.
1964 *
1965 * <p>If the focused view didn't want this event, this method is called.
1966 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001967 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1968 * by calling {@link #onBackPressed()}, though the behavior varies based
1969 * on the application compatibility mode: for
1970 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1971 * it will set up the dispatch to call {@link #onKeyUp} where the action
1972 * will be performed; for earlier applications, it will perform the
1973 * action immediately in on-down, as those versions of the platform
1974 * behaved.
1975 *
1976 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001977 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 *
1979 * @return Return <code>true</code> to prevent this event from being propagated
1980 * further, or <code>false</code> to indicate that you have not handled
1981 * this event and it should continue to be propagated.
1982 * @see #onKeyUp
1983 * @see android.view.KeyEvent
1984 */
1985 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001986 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001987 if (getApplicationInfo().targetSdkVersion
1988 >= Build.VERSION_CODES.ECLAIR) {
1989 event.startTracking();
1990 } else {
1991 onBackPressed();
1992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 return true;
1994 }
1995
1996 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1997 return false;
1998 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001999 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
2000 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2001 return true;
2002 }
2003 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 } else {
2005 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2006 boolean clearSpannable = false;
2007 boolean handled;
2008 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2009 clearSpannable = true;
2010 handled = false;
2011 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002012 handled = TextKeyListener.getInstance().onKeyDown(
2013 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 if (handled && mDefaultKeySsb.length() > 0) {
2015 // something useable has been typed - dispatch it now.
2016
2017 final String str = mDefaultKeySsb.toString();
2018 clearSpannable = true;
2019
2020 switch (mDefaultKeyMode) {
2021 case DEFAULT_KEYS_DIALER:
2022 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2023 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2024 startActivity(intent);
2025 break;
2026 case DEFAULT_KEYS_SEARCH_LOCAL:
2027 startSearch(str, false, null, false);
2028 break;
2029 case DEFAULT_KEYS_SEARCH_GLOBAL:
2030 startSearch(str, false, null, true);
2031 break;
2032 }
2033 }
2034 }
2035 if (clearSpannable) {
2036 mDefaultKeySsb.clear();
2037 mDefaultKeySsb.clearSpans();
2038 Selection.setSelection(mDefaultKeySsb,0);
2039 }
2040 return handled;
2041 }
2042 }
2043
2044 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002045 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2046 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2047 * the event).
2048 */
2049 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2050 return false;
2051 }
2052
2053 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 * Called when a key was released and not handled by any of the views
2055 * inside of the activity. So, for example, key presses while the cursor
2056 * is inside a TextView will not trigger the event (unless it is a navigation
2057 * to another object) because TextView handles its own key presses.
2058 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002059 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2060 * and go back.
2061 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 * @return Return <code>true</code> to prevent this event from being propagated
2063 * further, or <code>false</code> to indicate that you have not handled
2064 * this event and it should continue to be propagated.
2065 * @see #onKeyDown
2066 * @see KeyEvent
2067 */
2068 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002069 if (getApplicationInfo().targetSdkVersion
2070 >= Build.VERSION_CODES.ECLAIR) {
2071 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2072 && !event.isCanceled()) {
2073 onBackPressed();
2074 return true;
2075 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 return false;
2078 }
2079
2080 /**
2081 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2082 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2083 * the event).
2084 */
2085 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2086 return false;
2087 }
2088
2089 /**
Dianne Hackborndd913a52010-07-22 12:17:04 -07002090 * Flag for {@link #popBackStack(String, int)}
2091 * and {@link #popBackStack(int, int)}: If set, and the name or ID of
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -07002092 * a back stack entry has been supplied, then all matching entries will
2093 * be consumed until one that doesn't match is found or the bottom of
2094 * the stack is reached. Otherwise, all entries up to but not including that entry
2095 * will be removed.
Dianne Hackborndd913a52010-07-22 12:17:04 -07002096 */
Jean-Baptiste Queru005cb6d2010-07-27 10:54:51 -07002097 public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
Dianne Hackborndd913a52010-07-22 12:17:04 -07002098
2099 /**
2100 * Pop the top state off the back stack. Returns true if there was one
2101 * to pop, else false.
Dianne Hackborndef15372010-08-15 12:43:52 -07002102 * @deprecated use {@link #getFragmentManager}.
Dianne Hackborndd913a52010-07-22 12:17:04 -07002103 */
Dianne Hackborndef15372010-08-15 12:43:52 -07002104 @Deprecated
Dianne Hackborndd913a52010-07-22 12:17:04 -07002105 public boolean popBackStack() {
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07002106 return mFragments.popBackStack();
Dianne Hackborndd913a52010-07-22 12:17:04 -07002107 }
2108
2109 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002110 * Pop the last fragment transition from the local activity's fragment
2111 * back stack. If there is nothing to pop, false is returned.
Dianne Hackbornf121be72010-05-06 14:10:32 -07002112 * @param name If non-null, this is the name of a previous back state
Dianne Hackborndd913a52010-07-22 12:17:04 -07002113 * to look for; if found, all states up to that state will be popped. The
2114 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2115 * the named state itself is popped. If null, only the top state is popped.
2116 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
Dianne Hackborndef15372010-08-15 12:43:52 -07002117 * @deprecated use {@link #getFragmentManager}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002118 */
Dianne Hackborndef15372010-08-15 12:43:52 -07002119 @Deprecated
Dianne Hackborndd913a52010-07-22 12:17:04 -07002120 public boolean popBackStack(String name, int flags) {
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07002121 return mFragments.popBackStack(name, flags);
Dianne Hackborndd913a52010-07-22 12:17:04 -07002122 }
2123
2124 /**
2125 * Pop all back stack states up to the one with the given identifier.
2126 * @param id Identifier of the stated to be popped. If no identifier exists,
2127 * false is returned.
2128 * The identifier is the number returned by
2129 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}. The
2130 * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether
2131 * the named state itself is popped.
2132 * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.
Dianne Hackborndef15372010-08-15 12:43:52 -07002133 * @deprecated use {@link #getFragmentManager}.
Dianne Hackborndd913a52010-07-22 12:17:04 -07002134 */
Dianne Hackborndef15372010-08-15 12:43:52 -07002135 @Deprecated
Dianne Hackborndd913a52010-07-22 12:17:04 -07002136 public boolean popBackStack(int id, int flags) {
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07002137 return mFragments.popBackStack(id, flags);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002138 }
2139
2140 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002141 * Called when the activity has detected the user's press of the back
2142 * key. The default implementation simply finishes the current activity,
2143 * but you can override this to do whatever you want.
2144 */
2145 public void onBackPressed() {
Dianne Hackborndef15372010-08-15 12:43:52 -07002146 if (!mFragments.popBackStack()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002147 finish();
2148 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002149 }
2150
2151 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 * Called when a touch screen event was not handled by any of the views
2153 * under it. This is most useful to process touch events that happen
2154 * outside of your window bounds, where there is no view to receive it.
2155 *
2156 * @param event The touch screen event being processed.
2157 *
2158 * @return Return true if you have consumed the event, false if you haven't.
2159 * The default implementation always returns false.
2160 */
2161 public boolean onTouchEvent(MotionEvent event) {
2162 return false;
2163 }
2164
2165 /**
2166 * Called when the trackball was moved and not handled by any of the
2167 * views inside of the activity. So, for example, if the trackball moves
2168 * while focus is on a button, you will receive a call here because
2169 * buttons do not normally do anything with trackball events. The call
2170 * here happens <em>before</em> trackball movements are converted to
2171 * DPAD key events, which then get sent back to the view hierarchy, and
2172 * will be processed at the point for things like focus navigation.
2173 *
2174 * @param event The trackball event being processed.
2175 *
2176 * @return Return true if you have consumed the event, false if you haven't.
2177 * The default implementation always returns false.
2178 */
2179 public boolean onTrackballEvent(MotionEvent event) {
2180 return false;
2181 }
2182
2183 /**
2184 * Called whenever a key, touch, or trackball event is dispatched to the
2185 * activity. Implement this method if you wish to know that the user has
2186 * interacted with the device in some way while your activity is running.
2187 * This callback and {@link #onUserLeaveHint} are intended to help
2188 * activities manage status bar notifications intelligently; specifically,
2189 * for helping activities determine the proper time to cancel a notfication.
2190 *
2191 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2192 * be accompanied by calls to {@link #onUserInteraction}. This
2193 * ensures that your activity will be told of relevant user activity such
2194 * as pulling down the notification pane and touching an item there.
2195 *
2196 * <p>Note that this callback will be invoked for the touch down action
2197 * that begins a touch gesture, but may not be invoked for the touch-moved
2198 * and touch-up actions that follow.
2199 *
2200 * @see #onUserLeaveHint()
2201 */
2202 public void onUserInteraction() {
2203 }
2204
2205 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2206 // Update window manager if: we have a view, that view is
2207 // attached to its parent (which will be a RootView), and
2208 // this activity is not embedded.
2209 if (mParent == null) {
2210 View decor = mDecor;
2211 if (decor != null && decor.getParent() != null) {
2212 getWindowManager().updateViewLayout(decor, params);
2213 }
2214 }
2215 }
2216
2217 public void onContentChanged() {
2218 }
2219
2220 /**
2221 * Called when the current {@link Window} of the activity gains or loses
2222 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002223 * to the user. The default implementation clears the key tracking
2224 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002226 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 * is managed independently of activity lifecycles. As such, while focus
2228 * changes will generally have some relation to lifecycle changes (an
2229 * activity that is stopped will not generally get window focus), you
2230 * should not rely on any particular order between the callbacks here and
2231 * those in the other lifecycle methods such as {@link #onResume}.
2232 *
2233 * <p>As a general rule, however, a resumed activity will have window
2234 * focus... unless it has displayed other dialogs or popups that take
2235 * input focus, in which case the activity itself will not have focus
2236 * when the other windows have it. Likewise, the system may display
2237 * system-level windows (such as the status bar notification panel or
2238 * a system alert) which will temporarily take window input focus without
2239 * pausing the foreground activity.
2240 *
2241 * @param hasFocus Whether the window of this activity has focus.
2242 *
2243 * @see #hasWindowFocus()
2244 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002245 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 */
2247 public void onWindowFocusChanged(boolean hasFocus) {
2248 }
2249
2250 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002251 * Called when the main window associated with the activity has been
2252 * attached to the window manager.
2253 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2254 * for more information.
2255 * @see View#onAttachedToWindow
2256 */
2257 public void onAttachedToWindow() {
2258 }
2259
2260 /**
2261 * Called when the main window associated with the activity has been
2262 * detached from the window manager.
2263 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2264 * for more information.
2265 * @see View#onDetachedFromWindow
2266 */
2267 public void onDetachedFromWindow() {
2268 }
2269
2270 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 * Returns true if this activity's <em>main</em> window currently has window focus.
2272 * Note that this is not the same as the view itself having focus.
2273 *
2274 * @return True if this activity's main window currently has window focus.
2275 *
2276 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2277 */
2278 public boolean hasWindowFocus() {
2279 Window w = getWindow();
2280 if (w != null) {
2281 View d = w.getDecorView();
2282 if (d != null) {
2283 return d.hasWindowFocus();
2284 }
2285 }
2286 return false;
2287 }
2288
2289 /**
2290 * Called to process key events. You can override this to intercept all
2291 * key events before they are dispatched to the window. Be sure to call
2292 * this implementation for key events that should be handled normally.
2293 *
2294 * @param event The key event.
2295 *
2296 * @return boolean Return true if this event was consumed.
2297 */
2298 public boolean dispatchKeyEvent(KeyEvent event) {
2299 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002300 Window win = getWindow();
2301 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 return true;
2303 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002304 View decor = mDecor;
2305 if (decor == null) decor = win.getDecorView();
2306 return event.dispatch(this, decor != null
2307 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309
2310 /**
2311 * Called to process touch screen events. You can override this to
2312 * intercept all touch screen events before they are dispatched to the
2313 * window. Be sure to call this implementation for touch screen events
2314 * that should be handled normally.
2315 *
2316 * @param ev The touch screen event.
2317 *
2318 * @return boolean Return true if this event was consumed.
2319 */
2320 public boolean dispatchTouchEvent(MotionEvent ev) {
2321 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2322 onUserInteraction();
2323 }
2324 if (getWindow().superDispatchTouchEvent(ev)) {
2325 return true;
2326 }
2327 return onTouchEvent(ev);
2328 }
2329
2330 /**
2331 * Called to process trackball events. You can override this to
2332 * intercept all trackball events before they are dispatched to the
2333 * window. Be sure to call this implementation for trackball events
2334 * that should be handled normally.
2335 *
2336 * @param ev The trackball event.
2337 *
2338 * @return boolean Return true if this event was consumed.
2339 */
2340 public boolean dispatchTrackballEvent(MotionEvent ev) {
2341 onUserInteraction();
2342 if (getWindow().superDispatchTrackballEvent(ev)) {
2343 return true;
2344 }
2345 return onTrackballEvent(ev);
2346 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002347
2348 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2349 event.setClassName(getClass().getName());
2350 event.setPackageName(getPackageName());
2351
2352 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002353 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2354 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002355 event.setFullScreen(isFullScreen);
2356
2357 CharSequence title = getTitle();
2358 if (!TextUtils.isEmpty(title)) {
2359 event.getText().add(title);
2360 }
2361
2362 return true;
2363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 /**
2366 * Default implementation of
2367 * {@link android.view.Window.Callback#onCreatePanelView}
2368 * for activities. This
2369 * simply returns null so that all panel sub-windows will have the default
2370 * menu behavior.
2371 */
2372 public View onCreatePanelView(int featureId) {
2373 return null;
2374 }
2375
2376 /**
2377 * Default implementation of
2378 * {@link android.view.Window.Callback#onCreatePanelMenu}
2379 * for activities. This calls through to the new
2380 * {@link #onCreateOptionsMenu} method for the
2381 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2382 * so that subclasses of Activity don't need to deal with feature codes.
2383 */
2384 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2385 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002386 boolean show = onCreateOptionsMenu(menu);
2387 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2388 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
2390 return false;
2391 }
2392
2393 /**
2394 * Default implementation of
2395 * {@link android.view.Window.Callback#onPreparePanel}
2396 * for activities. This
2397 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2398 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2399 * panel, so that subclasses of
2400 * Activity don't need to deal with feature codes.
2401 */
2402 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2403 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2404 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002405 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return goforit && menu.hasVisibleItems();
2407 }
2408 return true;
2409 }
2410
2411 /**
2412 * {@inheritDoc}
2413 *
2414 * @return The default implementation returns true.
2415 */
2416 public boolean onMenuOpened(int featureId, Menu menu) {
2417 return true;
2418 }
2419
2420 /**
2421 * Default implementation of
2422 * {@link android.view.Window.Callback#onMenuItemSelected}
2423 * for activities. This calls through to the new
2424 * {@link #onOptionsItemSelected} method for the
2425 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2426 * panel, so that subclasses of
2427 * Activity don't need to deal with feature codes.
2428 */
2429 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2430 switch (featureId) {
2431 case Window.FEATURE_OPTIONS_PANEL:
2432 // Put event logging here so it gets called even if subclass
2433 // doesn't call through to superclass's implmeentation of each
2434 // of these methods below
2435 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002436 if (onOptionsItemSelected(item)) {
2437 return true;
2438 }
2439 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440
2441 case Window.FEATURE_CONTEXT_MENU:
2442 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002443 if (onContextItemSelected(item)) {
2444 return true;
2445 }
2446 return mFragments.dispatchContextItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447
2448 default:
2449 return false;
2450 }
2451 }
2452
2453 /**
2454 * Default implementation of
2455 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2456 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2457 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2458 * so that subclasses of Activity don't need to deal with feature codes.
2459 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2460 * {@link #onContextMenuClosed(Menu)} will be called.
2461 */
2462 public void onPanelClosed(int featureId, Menu menu) {
2463 switch (featureId) {
2464 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002465 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 onOptionsMenuClosed(menu);
2467 break;
2468
2469 case Window.FEATURE_CONTEXT_MENU:
2470 onContextMenuClosed(menu);
2471 break;
2472 }
2473 }
2474
2475 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002476 * Declare that the options menu has changed, so should be recreated.
2477 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2478 * time it needs to be displayed.
2479 */
2480 public void invalidateOptionsMenu() {
2481 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2482 }
2483
2484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 * Initialize the contents of the Activity's standard options menu. You
2486 * should place your menu items in to <var>menu</var>.
2487 *
2488 * <p>This is only called once, the first time the options menu is
2489 * displayed. To update the menu every time it is displayed, see
2490 * {@link #onPrepareOptionsMenu}.
2491 *
2492 * <p>The default implementation populates the menu with standard system
2493 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2494 * they will be correctly ordered with application-defined menu items.
2495 * Deriving classes should always call through to the base implementation.
2496 *
2497 * <p>You can safely hold on to <var>menu</var> (and any items created
2498 * from it), making modifications to it as desired, until the next
2499 * time onCreateOptionsMenu() is called.
2500 *
2501 * <p>When you add items to the menu, you can implement the Activity's
2502 * {@link #onOptionsItemSelected} method to handle them there.
2503 *
2504 * @param menu The options menu in which you place your items.
2505 *
2506 * @return You must return true for the menu to be displayed;
2507 * if you return false it will not be shown.
2508 *
2509 * @see #onPrepareOptionsMenu
2510 * @see #onOptionsItemSelected
2511 */
2512 public boolean onCreateOptionsMenu(Menu menu) {
2513 if (mParent != null) {
2514 return mParent.onCreateOptionsMenu(menu);
2515 }
2516 return true;
2517 }
2518
2519 /**
2520 * Prepare the Screen's standard options menu to be displayed. This is
2521 * called right before the menu is shown, every time it is shown. You can
2522 * use this method to efficiently enable/disable items or otherwise
2523 * dynamically modify the contents.
2524 *
2525 * <p>The default implementation updates the system menu items based on the
2526 * activity's state. Deriving classes should always call through to the
2527 * base class implementation.
2528 *
2529 * @param menu The options menu as last shown or first initialized by
2530 * onCreateOptionsMenu().
2531 *
2532 * @return You must return true for the menu to be displayed;
2533 * if you return false it will not be shown.
2534 *
2535 * @see #onCreateOptionsMenu
2536 */
2537 public boolean onPrepareOptionsMenu(Menu menu) {
2538 if (mParent != null) {
2539 return mParent.onPrepareOptionsMenu(menu);
2540 }
2541 return true;
2542 }
2543
2544 /**
2545 * This hook is called whenever an item in your options menu is selected.
2546 * The default implementation simply returns false to have the normal
2547 * processing happen (calling the item's Runnable or sending a message to
2548 * its Handler as appropriate). You can use this method for any items
2549 * for which you would like to do processing without those other
2550 * facilities.
2551 *
2552 * <p>Derived classes should call through to the base class for it to
2553 * perform the default menu handling.
2554 *
2555 * @param item The menu item that was selected.
2556 *
2557 * @return boolean Return false to allow normal menu processing to
2558 * proceed, true to consume it here.
2559 *
2560 * @see #onCreateOptionsMenu
2561 */
2562 public boolean onOptionsItemSelected(MenuItem item) {
2563 if (mParent != null) {
2564 return mParent.onOptionsItemSelected(item);
2565 }
2566 return false;
2567 }
2568
2569 /**
2570 * This hook is called whenever the options menu is being closed (either by the user canceling
2571 * the menu with the back/menu button, or when an item is selected).
2572 *
2573 * @param menu The options menu as last shown or first initialized by
2574 * onCreateOptionsMenu().
2575 */
2576 public void onOptionsMenuClosed(Menu menu) {
2577 if (mParent != null) {
2578 mParent.onOptionsMenuClosed(menu);
2579 }
2580 }
2581
2582 /**
2583 * Programmatically opens the options menu. If the options menu is already
2584 * open, this method does nothing.
2585 */
2586 public void openOptionsMenu() {
2587 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2588 }
2589
2590 /**
2591 * Progammatically closes the options menu. If the options menu is already
2592 * closed, this method does nothing.
2593 */
2594 public void closeOptionsMenu() {
2595 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2596 }
2597
2598 /**
2599 * Called when a context menu for the {@code view} is about to be shown.
2600 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2601 * time the context menu is about to be shown and should be populated for
2602 * the view (or item inside the view for {@link AdapterView} subclasses,
2603 * this can be found in the {@code menuInfo})).
2604 * <p>
2605 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2606 * item has been selected.
2607 * <p>
2608 * It is not safe to hold onto the context menu after this method returns.
2609 * {@inheritDoc}
2610 */
2611 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2612 }
2613
2614 /**
2615 * Registers a context menu to be shown for the given view (multiple views
2616 * can show the context menu). This method will set the
2617 * {@link OnCreateContextMenuListener} on the view to this activity, so
2618 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2619 * called when it is time to show the context menu.
2620 *
2621 * @see #unregisterForContextMenu(View)
2622 * @param view The view that should show a context menu.
2623 */
2624 public void registerForContextMenu(View view) {
2625 view.setOnCreateContextMenuListener(this);
2626 }
2627
2628 /**
2629 * Prevents a context menu to be shown for the given view. This method will remove the
2630 * {@link OnCreateContextMenuListener} on the view.
2631 *
2632 * @see #registerForContextMenu(View)
2633 * @param view The view that should stop showing a context menu.
2634 */
2635 public void unregisterForContextMenu(View view) {
2636 view.setOnCreateContextMenuListener(null);
2637 }
2638
2639 /**
2640 * Programmatically opens the context menu for a particular {@code view}.
2641 * The {@code view} should have been added via
2642 * {@link #registerForContextMenu(View)}.
2643 *
2644 * @param view The view to show the context menu for.
2645 */
2646 public void openContextMenu(View view) {
2647 view.showContextMenu();
2648 }
2649
2650 /**
2651 * Programmatically closes the most recently opened context menu, if showing.
2652 */
2653 public void closeContextMenu() {
2654 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2655 }
2656
2657 /**
2658 * This hook is called whenever an item in a context menu is selected. The
2659 * default implementation simply returns false to have the normal processing
2660 * happen (calling the item's Runnable or sending a message to its Handler
2661 * as appropriate). You can use this method for any items for which you
2662 * would like to do processing without those other facilities.
2663 * <p>
2664 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2665 * View that added this menu item.
2666 * <p>
2667 * Derived classes should call through to the base class for it to perform
2668 * the default menu handling.
2669 *
2670 * @param item The context menu item that was selected.
2671 * @return boolean Return false to allow normal context menu processing to
2672 * proceed, true to consume it here.
2673 */
2674 public boolean onContextItemSelected(MenuItem item) {
2675 if (mParent != null) {
2676 return mParent.onContextItemSelected(item);
2677 }
2678 return false;
2679 }
2680
2681 /**
2682 * This hook is called whenever the context menu is being closed (either by
2683 * the user canceling the menu with the back/menu button, or when an item is
2684 * selected).
2685 *
2686 * @param menu The context menu that is being closed.
2687 */
2688 public void onContextMenuClosed(Menu menu) {
2689 if (mParent != null) {
2690 mParent.onContextMenuClosed(menu);
2691 }
2692 }
2693
2694 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002695 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002697 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 protected Dialog onCreateDialog(int id) {
2699 return null;
2700 }
2701
2702 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002703 * Callback for creating dialogs that are managed (saved and restored) for you
2704 * by the activity. The default implementation calls through to
2705 * {@link #onCreateDialog(int)} for compatibility.
2706 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002707 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2708 * or later, consider instead using a {@link DialogFragment} instead.</em>
2709 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002710 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2711 * this method the first time, and hang onto it thereafter. Any dialog
2712 * that is created by this method will automatically be saved and restored
2713 * for you, including whether it is showing.
2714 *
2715 * <p>If you would like the activity to manage saving and restoring dialogs
2716 * for you, you should override this method and handle any ids that are
2717 * passed to {@link #showDialog}.
2718 *
2719 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2720 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2721 *
2722 * @param id The id of the dialog.
2723 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2724 * @return The dialog. If you return null, the dialog will not be created.
2725 *
2726 * @see #onPrepareDialog(int, Dialog, Bundle)
2727 * @see #showDialog(int, Bundle)
2728 * @see #dismissDialog(int)
2729 * @see #removeDialog(int)
2730 */
2731 protected Dialog onCreateDialog(int id, Bundle args) {
2732 return onCreateDialog(id);
2733 }
2734
2735 /**
2736 * @deprecated Old no-arguments version of
2737 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2738 */
2739 @Deprecated
2740 protected void onPrepareDialog(int id, Dialog dialog) {
2741 dialog.setOwnerActivity(this);
2742 }
2743
2744 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002746 * shown. The default implementation calls through to
2747 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2748 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 * <p>
2750 * Override this if you need to update a managed dialog based on the state
2751 * of the application each time it is shown. For example, a time picker
2752 * dialog might want to be updated with the current time. You should call
2753 * through to the superclass's implementation. The default implementation
2754 * will set this Activity as the owner activity on the Dialog.
2755 *
2756 * @param id The id of the managed dialog.
2757 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002758 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2759 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 * @see #showDialog(int)
2761 * @see #dismissDialog(int)
2762 * @see #removeDialog(int)
2763 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002764 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2765 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 }
2767
2768 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002769 * Simple version of {@link #showDialog(int, Bundle)} that does not
2770 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2771 * with null arguments.
2772 */
2773 public final void showDialog(int id) {
2774 showDialog(id, null);
2775 }
2776
2777 /**
2778 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 * will be made with the same id the first time this is called for a given
2780 * id. From thereafter, the dialog will be automatically saved and restored.
2781 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002782 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2783 * or later, consider instead using a {@link DialogFragment} instead.</em>
2784 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002785 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 * be made to provide an opportunity to do any timely preparation.
2787 *
2788 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002789 * @param args Arguments to pass through to the dialog. These will be saved
2790 * and restored for you. Note that if the dialog is already created,
2791 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2792 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002793 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002794 * @return Returns true if the Dialog was created; false is returned if
2795 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2796 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002797 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002798 * @see #onCreateDialog(int, Bundle)
2799 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 * @see #dismissDialog(int)
2801 * @see #removeDialog(int)
2802 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002803 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002805 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002807 ManagedDialog md = mManagedDialogs.get(id);
2808 if (md == null) {
2809 md = new ManagedDialog();
2810 md.mDialog = createDialog(id, null, args);
2811 if (md.mDialog == null) {
2812 return false;
2813 }
2814 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 }
2816
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002817 md.mArgs = args;
2818 onPrepareDialog(id, md.mDialog, args);
2819 md.mDialog.show();
2820 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822
2823 /**
2824 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2825 *
2826 * @param id The id of the managed dialog.
2827 *
2828 * @throws IllegalArgumentException if the id was not previously shown via
2829 * {@link #showDialog(int)}.
2830 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002831 * @see #onCreateDialog(int, Bundle)
2832 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 * @see #showDialog(int)
2834 * @see #removeDialog(int)
2835 */
2836 public final void dismissDialog(int id) {
2837 if (mManagedDialogs == null) {
2838 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002840
2841 final ManagedDialog md = mManagedDialogs.get(id);
2842 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 throw missingDialog(id);
2844 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002845 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 }
2847
2848 /**
2849 * Creates an exception to throw if a user passed in a dialog id that is
2850 * unexpected.
2851 */
2852 private IllegalArgumentException missingDialog(int id) {
2853 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2854 + "shown via Activity#showDialog");
2855 }
2856
2857 /**
2858 * Removes any internal references to a dialog managed by this Activity.
2859 * If the dialog is showing, it will dismiss it as part of the clean up.
2860 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002861 * <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 -08002862 * want to avoid the overhead of saving and restoring it in the future.
2863 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002864 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2865 * will not throw an exception if you try to remove an ID that does not
2866 * currently have an associated dialog.</p>
2867 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 * @param id The id of the managed dialog.
2869 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002870 * @see #onCreateDialog(int, Bundle)
2871 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 * @see #showDialog(int)
2873 * @see #dismissDialog(int)
2874 */
2875 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002876 if (mManagedDialogs != null) {
2877 final ManagedDialog md = mManagedDialogs.get(id);
2878 if (md != null) {
2879 md.mDialog.dismiss();
2880 mManagedDialogs.remove(id);
2881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 }
2884
2885 /**
2886 * This hook is called when the user signals the desire to start a search.
2887 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002888 * <p>You can use this function as a simple way to launch the search UI, in response to a
2889 * menu item, search button, or other widgets within your activity. Unless overidden,
2890 * calling this function is the same as calling
2891 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2892 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 *
2894 * <p>You can override this function to force global search, e.g. in response to a dedicated
2895 * search key, or to block search entirely (by simply returning false).
2896 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002897 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2898 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 *
2900 * @see android.app.SearchManager
2901 */
2902 public boolean onSearchRequested() {
2903 startSearch(null, false, null, false);
2904 return true;
2905 }
2906
2907 /**
2908 * This hook is called to launch the search UI.
2909 *
2910 * <p>It is typically called from onSearchRequested(), either directly from
2911 * Activity.onSearchRequested() or from an overridden version in any given
2912 * Activity. If your goal is simply to activate search, it is preferred to call
2913 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2914 * is to inject specific data such as context data, it is preferred to <i>override</i>
2915 * onSearchRequested(), so that any callers to it will benefit from the override.
2916 *
2917 * @param initialQuery Any non-null non-empty string will be inserted as
2918 * pre-entered text in the search query box.
2919 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2920 * any further typing will replace it. This is useful for cases where an entire pre-formed
2921 * query is being inserted. If false, the selection point will be placed at the end of the
2922 * inserted query. This is useful when the inserted query is text that the user entered,
2923 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2924 * if initialQuery is a non-empty string.</i>
2925 * @param appSearchData An application can insert application-specific
2926 * context here, in order to improve quality or specificity of its own
2927 * searches. This data will be returned with SEARCH intent(s). Null if
2928 * no extra data is required.
2929 * @param globalSearch If false, this will only launch the search that has been specifically
2930 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002931 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2933 *
2934 * @see android.app.SearchManager
2935 * @see #onSearchRequested
2936 */
2937 public void startSearch(String initialQuery, boolean selectInitialQuery,
2938 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002939 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002940 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 appSearchData, globalSearch);
2942 }
2943
2944 /**
krosaend2d60142009-08-17 08:56:48 -07002945 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2946 * the search dialog. Made available for testing purposes.
2947 *
2948 * @param query The query to trigger. If empty, the request will be ignored.
2949 * @param appSearchData An application can insert application-specific
2950 * context here, in order to improve quality or specificity of its own
2951 * searches. This data will be returned with SEARCH intent(s). Null if
2952 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002953 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002954 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002955 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002956 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002957 }
2958
2959 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 * Request that key events come to this activity. Use this if your
2961 * activity has no views with focus, but the activity still wants
2962 * a chance to process key events.
2963 *
2964 * @see android.view.Window#takeKeyEvents
2965 */
2966 public void takeKeyEvents(boolean get) {
2967 getWindow().takeKeyEvents(get);
2968 }
2969
2970 /**
2971 * Enable extended window features. This is a convenience for calling
2972 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2973 *
2974 * @param featureId The desired feature as defined in
2975 * {@link android.view.Window}.
2976 * @return Returns true if the requested feature is supported and now
2977 * enabled.
2978 *
2979 * @see android.view.Window#requestFeature
2980 */
2981 public final boolean requestWindowFeature(int featureId) {
2982 return getWindow().requestFeature(featureId);
2983 }
2984
2985 /**
2986 * Convenience for calling
2987 * {@link android.view.Window#setFeatureDrawableResource}.
2988 */
2989 public final void setFeatureDrawableResource(int featureId, int resId) {
2990 getWindow().setFeatureDrawableResource(featureId, resId);
2991 }
2992
2993 /**
2994 * Convenience for calling
2995 * {@link android.view.Window#setFeatureDrawableUri}.
2996 */
2997 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2998 getWindow().setFeatureDrawableUri(featureId, uri);
2999 }
3000
3001 /**
3002 * Convenience for calling
3003 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3004 */
3005 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3006 getWindow().setFeatureDrawable(featureId, drawable);
3007 }
3008
3009 /**
3010 * Convenience for calling
3011 * {@link android.view.Window#setFeatureDrawableAlpha}.
3012 */
3013 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3014 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3015 }
3016
3017 /**
3018 * Convenience for calling
3019 * {@link android.view.Window#getLayoutInflater}.
3020 */
3021 public LayoutInflater getLayoutInflater() {
3022 return getWindow().getLayoutInflater();
3023 }
3024
3025 /**
3026 * Returns a {@link MenuInflater} with this context.
3027 */
3028 public MenuInflater getMenuInflater() {
3029 return new MenuInflater(this);
3030 }
3031
3032 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003033 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3034 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 if (mParent == null) {
3036 super.onApplyThemeResource(theme, resid, first);
3037 } else {
3038 try {
3039 theme.setTo(mParent.getTheme());
3040 } catch (Exception e) {
3041 // Empty
3042 }
3043 theme.applyStyle(resid, false);
3044 }
3045 }
3046
3047 /**
3048 * Launch an activity for which you would like a result when it finished.
3049 * When this activity exits, your
3050 * onActivityResult() method will be called with the given requestCode.
3051 * Using a negative requestCode is the same as calling
3052 * {@link #startActivity} (the activity is not launched as a sub-activity).
3053 *
3054 * <p>Note that this method should only be used with Intent protocols
3055 * that are defined to return a result. In other protocols (such as
3056 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3057 * not get the result when you expect. For example, if the activity you
3058 * are launching uses the singleTask launch mode, it will not run in your
3059 * task and thus you will immediately receive a cancel result.
3060 *
3061 * <p>As a special case, if you call startActivityForResult() with a requestCode
3062 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3063 * activity, then your window will not be displayed until a result is
3064 * returned back from the started activity. This is to avoid visible
3065 * flickering when redirecting to another activity.
3066 *
3067 * <p>This method throws {@link android.content.ActivityNotFoundException}
3068 * if there was no Activity found to run the given Intent.
3069 *
3070 * @param intent The intent to start.
3071 * @param requestCode If >= 0, this code will be returned in
3072 * onActivityResult() when the activity exits.
3073 *
3074 * @throws android.content.ActivityNotFoundException
3075 *
3076 * @see #startActivity
3077 */
3078 public void startActivityForResult(Intent intent, int requestCode) {
3079 if (mParent == null) {
3080 Instrumentation.ActivityResult ar =
3081 mInstrumentation.execStartActivity(
3082 this, mMainThread.getApplicationThread(), mToken, this,
3083 intent, requestCode);
3084 if (ar != null) {
3085 mMainThread.sendActivityResult(
3086 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3087 ar.getResultData());
3088 }
3089 if (requestCode >= 0) {
3090 // If this start is requesting a result, we can avoid making
3091 // the activity visible until the result is received. Setting
3092 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3093 // activity hidden during this time, to avoid flickering.
3094 // This can only be done when a result is requested because
3095 // that guarantees we will get information back when the
3096 // activity is finished, no matter what happens to it.
3097 mStartedActivity = true;
3098 }
3099 } else {
3100 mParent.startActivityFromChild(this, intent, requestCode);
3101 }
3102 }
3103
3104 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003105 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003106 * to use a IntentSender to describe the activity to be started. If
3107 * the IntentSender is for an activity, that activity will be started
3108 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3109 * here; otherwise, its associated action will be executed (such as
3110 * sending a broadcast) as if you had called
3111 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003112 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003113 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003114 * @param requestCode If >= 0, this code will be returned in
3115 * onActivityResult() when the activity exits.
3116 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003117 * intent parameter to {@link IntentSender#sendIntent}.
3118 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003119 * would like to change.
3120 * @param flagsValues Desired values for any bits set in
3121 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003122 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003123 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003124 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3125 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3126 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003127 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003128 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003129 flagsMask, flagsValues, this);
3130 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003131 mParent.startIntentSenderFromChild(this, intent, requestCode,
3132 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003133 }
3134 }
3135
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003136 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003137 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003138 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003139 try {
3140 String resolvedType = null;
3141 if (fillInIntent != null) {
3142 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3143 }
3144 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003145 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003146 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3147 requestCode, flagsMask, flagsValues);
3148 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003149 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003150 }
3151 Instrumentation.checkStartActivityResult(result, null);
3152 } catch (RemoteException e) {
3153 }
3154 if (requestCode >= 0) {
3155 // If this start is requesting a result, we can avoid making
3156 // the activity visible until the result is received. Setting
3157 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3158 // activity hidden during this time, to avoid flickering.
3159 // This can only be done when a result is requested because
3160 // that guarantees we will get information back when the
3161 // activity is finished, no matter what happens to it.
3162 mStartedActivity = true;
3163 }
3164 }
3165
3166 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 * Launch a new activity. You will not receive any information about when
3168 * the activity exits. This implementation overrides the base version,
3169 * providing information about
3170 * the activity performing the launch. Because of this additional
3171 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3172 * required; if not specified, the new activity will be added to the
3173 * task of the caller.
3174 *
3175 * <p>This method throws {@link android.content.ActivityNotFoundException}
3176 * if there was no Activity found to run the given Intent.
3177 *
3178 * @param intent The intent to start.
3179 *
3180 * @throws android.content.ActivityNotFoundException
3181 *
3182 * @see #startActivityForResult
3183 */
3184 @Override
3185 public void startActivity(Intent intent) {
3186 startActivityForResult(intent, -1);
3187 }
3188
3189 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003190 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003191 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003192 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003193 * for more information.
3194 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003195 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003196 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003197 * intent parameter to {@link IntentSender#sendIntent}.
3198 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003199 * would like to change.
3200 * @param flagsValues Desired values for any bits set in
3201 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003202 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003203 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003204 public void startIntentSender(IntentSender intent,
3205 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3206 throws IntentSender.SendIntentException {
3207 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3208 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003209 }
3210
3211 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 * A special variation to launch an activity only if a new activity
3213 * instance is needed to handle the given Intent. In other words, this is
3214 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3215 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3216 * singleTask or singleTop
3217 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3218 * and the activity
3219 * that handles <var>intent</var> is the same as your currently running
3220 * activity, then a new instance is not needed. In this case, instead of
3221 * the normal behavior of calling {@link #onNewIntent} this function will
3222 * return and you can handle the Intent yourself.
3223 *
3224 * <p>This function can only be called from a top-level activity; if it is
3225 * called from a child activity, a runtime exception will be thrown.
3226 *
3227 * @param intent The intent to start.
3228 * @param requestCode If >= 0, this code will be returned in
3229 * onActivityResult() when the activity exits, as described in
3230 * {@link #startActivityForResult}.
3231 *
3232 * @return If a new activity was launched then true is returned; otherwise
3233 * false is returned and you must handle the Intent yourself.
3234 *
3235 * @see #startActivity
3236 * @see #startActivityForResult
3237 */
3238 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3239 if (mParent == null) {
3240 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3241 try {
3242 result = ActivityManagerNative.getDefault()
3243 .startActivity(mMainThread.getApplicationThread(),
3244 intent, intent.resolveTypeIfNeeded(
3245 getContentResolver()),
3246 null, 0,
3247 mToken, mEmbeddedID, requestCode, true, false);
3248 } catch (RemoteException e) {
3249 // Empty
3250 }
3251
3252 Instrumentation.checkStartActivityResult(result, intent);
3253
3254 if (requestCode >= 0) {
3255 // If this start is requesting a result, we can avoid making
3256 // the activity visible until the result is received. Setting
3257 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3258 // activity hidden during this time, to avoid flickering.
3259 // This can only be done when a result is requested because
3260 // that guarantees we will get information back when the
3261 // activity is finished, no matter what happens to it.
3262 mStartedActivity = true;
3263 }
3264 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3265 }
3266
3267 throw new UnsupportedOperationException(
3268 "startActivityIfNeeded can only be called from a top-level activity");
3269 }
3270
3271 /**
3272 * Special version of starting an activity, for use when you are replacing
3273 * other activity components. You can use this to hand the Intent off
3274 * to the next Activity that can handle it. You typically call this in
3275 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3276 *
3277 * @param intent The intent to dispatch to the next activity. For
3278 * correct behavior, this must be the same as the Intent that started
3279 * your own activity; the only changes you can make are to the extras
3280 * inside of it.
3281 *
3282 * @return Returns a boolean indicating whether there was another Activity
3283 * to start: true if there was a next activity to start, false if there
3284 * wasn't. In general, if true is returned you will then want to call
3285 * finish() on yourself.
3286 */
3287 public boolean startNextMatchingActivity(Intent intent) {
3288 if (mParent == null) {
3289 try {
3290 return ActivityManagerNative.getDefault()
3291 .startNextMatchingActivity(mToken, intent);
3292 } catch (RemoteException e) {
3293 // Empty
3294 }
3295 return false;
3296 }
3297
3298 throw new UnsupportedOperationException(
3299 "startNextMatchingActivity can only be called from a top-level activity");
3300 }
3301
3302 /**
3303 * This is called when a child activity of this one calls its
3304 * {@link #startActivity} or {@link #startActivityForResult} method.
3305 *
3306 * <p>This method throws {@link android.content.ActivityNotFoundException}
3307 * if there was no Activity found to run the given Intent.
3308 *
3309 * @param child The activity making the call.
3310 * @param intent The intent to start.
3311 * @param requestCode Reply request code. < 0 if reply is not requested.
3312 *
3313 * @throws android.content.ActivityNotFoundException
3314 *
3315 * @see #startActivity
3316 * @see #startActivityForResult
3317 */
3318 public void startActivityFromChild(Activity child, Intent intent,
3319 int requestCode) {
3320 Instrumentation.ActivityResult ar =
3321 mInstrumentation.execStartActivity(
3322 this, mMainThread.getApplicationThread(), mToken, child,
3323 intent, requestCode);
3324 if (ar != null) {
3325 mMainThread.sendActivityResult(
3326 mToken, child.mEmbeddedID, requestCode,
3327 ar.getResultCode(), ar.getResultData());
3328 }
3329 }
3330
3331 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003332 * This is called when a Fragment in this activity calls its
3333 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3334 * method.
3335 *
3336 * <p>This method throws {@link android.content.ActivityNotFoundException}
3337 * if there was no Activity found to run the given Intent.
3338 *
3339 * @param fragment The fragment making the call.
3340 * @param intent The intent to start.
3341 * @param requestCode Reply request code. < 0 if reply is not requested.
3342 *
3343 * @throws android.content.ActivityNotFoundException
3344 *
3345 * @see Fragment#startActivity
3346 * @see Fragment#startActivityForResult
3347 */
3348 public void startActivityFromFragment(Fragment fragment, Intent intent,
3349 int requestCode) {
3350 Instrumentation.ActivityResult ar =
3351 mInstrumentation.execStartActivity(
3352 this, mMainThread.getApplicationThread(), mToken, fragment,
3353 intent, requestCode);
3354 if (ar != null) {
3355 mMainThread.sendActivityResult(
3356 mToken, fragment.mWho, requestCode,
3357 ar.getResultCode(), ar.getResultData());
3358 }
3359 }
3360
3361 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003362 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003363 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003364 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003365 * for more information.
3366 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003367 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3368 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3369 int extraFlags)
3370 throws IntentSender.SendIntentException {
3371 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003372 flagsMask, flagsValues, child);
3373 }
3374
3375 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003376 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3377 * or {@link #finish} to specify an explicit transition animation to
3378 * perform next.
3379 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003380 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003381 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003382 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003383 */
3384 public void overridePendingTransition(int enterAnim, int exitAnim) {
3385 try {
3386 ActivityManagerNative.getDefault().overridePendingTransition(
3387 mToken, getPackageName(), enterAnim, exitAnim);
3388 } catch (RemoteException e) {
3389 }
3390 }
3391
3392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 * Call this to set the result that your activity will return to its
3394 * caller.
3395 *
3396 * @param resultCode The result code to propagate back to the originating
3397 * activity, often RESULT_CANCELED or RESULT_OK
3398 *
3399 * @see #RESULT_CANCELED
3400 * @see #RESULT_OK
3401 * @see #RESULT_FIRST_USER
3402 * @see #setResult(int, Intent)
3403 */
3404 public final void setResult(int resultCode) {
3405 synchronized (this) {
3406 mResultCode = resultCode;
3407 mResultData = null;
3408 }
3409 }
3410
3411 /**
3412 * Call this to set the result that your activity will return to its
3413 * caller.
3414 *
3415 * @param resultCode The result code to propagate back to the originating
3416 * activity, often RESULT_CANCELED or RESULT_OK
3417 * @param data The data to propagate back to the originating activity.
3418 *
3419 * @see #RESULT_CANCELED
3420 * @see #RESULT_OK
3421 * @see #RESULT_FIRST_USER
3422 * @see #setResult(int)
3423 */
3424 public final void setResult(int resultCode, Intent data) {
3425 synchronized (this) {
3426 mResultCode = resultCode;
3427 mResultData = data;
3428 }
3429 }
3430
3431 /**
3432 * Return the name of the package that invoked this activity. This is who
3433 * the data in {@link #setResult setResult()} will be sent to. You can
3434 * use this information to validate that the recipient is allowed to
3435 * receive the data.
3436 *
3437 * <p>Note: if the calling activity is not expecting a result (that is it
3438 * did not use the {@link #startActivityForResult}
3439 * form that includes a request code), then the calling package will be
3440 * null.
3441 *
3442 * @return The package of the activity that will receive your
3443 * reply, or null if none.
3444 */
3445 public String getCallingPackage() {
3446 try {
3447 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3448 } catch (RemoteException e) {
3449 return null;
3450 }
3451 }
3452
3453 /**
3454 * Return the name of the activity that invoked this activity. This is
3455 * who the data in {@link #setResult setResult()} will be sent to. You
3456 * can use this information to validate that the recipient is allowed to
3457 * receive the data.
3458 *
3459 * <p>Note: if the calling activity is not expecting a result (that is it
3460 * did not use the {@link #startActivityForResult}
3461 * form that includes a request code), then the calling package will be
3462 * null.
3463 *
3464 * @return String The full name of the activity that will receive your
3465 * reply, or null if none.
3466 */
3467 public ComponentName getCallingActivity() {
3468 try {
3469 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3470 } catch (RemoteException e) {
3471 return null;
3472 }
3473 }
3474
3475 /**
3476 * Control whether this activity's main window is visible. This is intended
3477 * only for the special case of an activity that is not going to show a
3478 * UI itself, but can't just finish prior to onResume() because it needs
3479 * to wait for a service binding or such. Setting this to false allows
3480 * you to prevent your UI from being shown during that time.
3481 *
3482 * <p>The default value for this is taken from the
3483 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3484 */
3485 public void setVisible(boolean visible) {
3486 if (mVisibleFromClient != visible) {
3487 mVisibleFromClient = visible;
3488 if (mVisibleFromServer) {
3489 if (visible) makeVisible();
3490 else mDecor.setVisibility(View.INVISIBLE);
3491 }
3492 }
3493 }
3494
3495 void makeVisible() {
3496 if (!mWindowAdded) {
3497 ViewManager wm = getWindowManager();
3498 wm.addView(mDecor, getWindow().getAttributes());
3499 mWindowAdded = true;
3500 }
3501 mDecor.setVisibility(View.VISIBLE);
3502 }
3503
3504 /**
3505 * Check to see whether this activity is in the process of finishing,
3506 * either because you called {@link #finish} on it or someone else
3507 * has requested that it finished. This is often used in
3508 * {@link #onPause} to determine whether the activity is simply pausing or
3509 * completely finishing.
3510 *
3511 * @return If the activity is finishing, returns true; else returns false.
3512 *
3513 * @see #finish
3514 */
3515 public boolean isFinishing() {
3516 return mFinished;
3517 }
3518
3519 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003520 * Check to see whether this activity is in the process of being destroyed in order to be
3521 * recreated with a new configuration. This is often used in
3522 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3523 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3524 *
3525 * @return If the activity is being torn down in order to be recreated with a new configuration,
3526 * returns true; else returns false.
3527 */
3528 public boolean isChangingConfigurations() {
3529 return mChangingConfigurations;
3530 }
3531
3532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 * Call this when your activity is done and should be closed. The
3534 * ActivityResult is propagated back to whoever launched you via
3535 * onActivityResult().
3536 */
3537 public void finish() {
3538 if (mParent == null) {
3539 int resultCode;
3540 Intent resultData;
3541 synchronized (this) {
3542 resultCode = mResultCode;
3543 resultData = mResultData;
3544 }
3545 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3546 try {
3547 if (ActivityManagerNative.getDefault()
3548 .finishActivity(mToken, resultCode, resultData)) {
3549 mFinished = true;
3550 }
3551 } catch (RemoteException e) {
3552 // Empty
3553 }
3554 } else {
3555 mParent.finishFromChild(this);
3556 }
3557 }
3558
3559 /**
3560 * This is called when a child activity of this one calls its
3561 * {@link #finish} method. The default implementation simply calls
3562 * finish() on this activity (the parent), finishing the entire group.
3563 *
3564 * @param child The activity making the call.
3565 *
3566 * @see #finish
3567 */
3568 public void finishFromChild(Activity child) {
3569 finish();
3570 }
3571
3572 /**
3573 * Force finish another activity that you had previously started with
3574 * {@link #startActivityForResult}.
3575 *
3576 * @param requestCode The request code of the activity that you had
3577 * given to startActivityForResult(). If there are multiple
3578 * activities started with this request code, they
3579 * will all be finished.
3580 */
3581 public void finishActivity(int requestCode) {
3582 if (mParent == null) {
3583 try {
3584 ActivityManagerNative.getDefault()
3585 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3586 } catch (RemoteException e) {
3587 // Empty
3588 }
3589 } else {
3590 mParent.finishActivityFromChild(this, requestCode);
3591 }
3592 }
3593
3594 /**
3595 * This is called when a child activity of this one calls its
3596 * finishActivity().
3597 *
3598 * @param child The activity making the call.
3599 * @param requestCode Request code that had been used to start the
3600 * activity.
3601 */
3602 public void finishActivityFromChild(Activity child, int requestCode) {
3603 try {
3604 ActivityManagerNative.getDefault()
3605 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3606 } catch (RemoteException e) {
3607 // Empty
3608 }
3609 }
3610
3611 /**
3612 * Called when an activity you launched exits, giving you the requestCode
3613 * you started it with, the resultCode it returned, and any additional
3614 * data from it. The <var>resultCode</var> will be
3615 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3616 * didn't return any result, or crashed during its operation.
3617 *
3618 * <p>You will receive this call immediately before onResume() when your
3619 * activity is re-starting.
3620 *
3621 * @param requestCode The integer request code originally supplied to
3622 * startActivityForResult(), allowing you to identify who this
3623 * result came from.
3624 * @param resultCode The integer result code returned by the child activity
3625 * through its setResult().
3626 * @param data An Intent, which can return result data to the caller
3627 * (various data can be attached to Intent "extras").
3628 *
3629 * @see #startActivityForResult
3630 * @see #createPendingResult
3631 * @see #setResult(int)
3632 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003633 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635
3636 /**
3637 * Create a new PendingIntent object which you can hand to others
3638 * for them to use to send result data back to your
3639 * {@link #onActivityResult} callback. The created object will be either
3640 * one-shot (becoming invalid after a result is sent back) or multiple
3641 * (allowing any number of results to be sent through it).
3642 *
3643 * @param requestCode Private request code for the sender that will be
3644 * associated with the result data when it is returned. The sender can not
3645 * modify this value, allowing you to identify incoming results.
3646 * @param data Default data to supply in the result, which may be modified
3647 * by the sender.
3648 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3649 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3650 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3651 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3652 * or any of the flags as supported by
3653 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3654 * of the intent that can be supplied when the actual send happens.
3655 *
3656 * @return Returns an existing or new PendingIntent matching the given
3657 * parameters. May return null only if
3658 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3659 * supplied.
3660 *
3661 * @see PendingIntent
3662 */
3663 public PendingIntent createPendingResult(int requestCode, Intent data,
3664 int flags) {
3665 String packageName = getPackageName();
3666 try {
3667 IIntentSender target =
3668 ActivityManagerNative.getDefault().getIntentSender(
3669 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3670 mParent == null ? mToken : mParent.mToken,
3671 mEmbeddedID, requestCode, data, null, flags);
3672 return target != null ? new PendingIntent(target) : null;
3673 } catch (RemoteException e) {
3674 // Empty
3675 }
3676 return null;
3677 }
3678
3679 /**
3680 * Change the desired orientation of this activity. If the activity
3681 * is currently in the foreground or otherwise impacting the screen
3682 * orientation, the screen will immediately be changed (possibly causing
3683 * the activity to be restarted). Otherwise, this will be used the next
3684 * time the activity is visible.
3685 *
3686 * @param requestedOrientation An orientation constant as used in
3687 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3688 */
3689 public void setRequestedOrientation(int requestedOrientation) {
3690 if (mParent == null) {
3691 try {
3692 ActivityManagerNative.getDefault().setRequestedOrientation(
3693 mToken, requestedOrientation);
3694 } catch (RemoteException e) {
3695 // Empty
3696 }
3697 } else {
3698 mParent.setRequestedOrientation(requestedOrientation);
3699 }
3700 }
3701
3702 /**
3703 * Return the current requested orientation of the activity. This will
3704 * either be the orientation requested in its component's manifest, or
3705 * the last requested orientation given to
3706 * {@link #setRequestedOrientation(int)}.
3707 *
3708 * @return Returns an orientation constant as used in
3709 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3710 */
3711 public int getRequestedOrientation() {
3712 if (mParent == null) {
3713 try {
3714 return ActivityManagerNative.getDefault()
3715 .getRequestedOrientation(mToken);
3716 } catch (RemoteException e) {
3717 // Empty
3718 }
3719 } else {
3720 return mParent.getRequestedOrientation();
3721 }
3722 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3723 }
3724
3725 /**
3726 * Return the identifier of the task this activity is in. This identifier
3727 * will remain the same for the lifetime of the activity.
3728 *
3729 * @return Task identifier, an opaque integer.
3730 */
3731 public int getTaskId() {
3732 try {
3733 return ActivityManagerNative.getDefault()
3734 .getTaskForActivity(mToken, false);
3735 } catch (RemoteException e) {
3736 return -1;
3737 }
3738 }
3739
3740 /**
3741 * Return whether this activity is the root of a task. The root is the
3742 * first activity in a task.
3743 *
3744 * @return True if this is the root activity, else false.
3745 */
3746 public boolean isTaskRoot() {
3747 try {
3748 return ActivityManagerNative.getDefault()
3749 .getTaskForActivity(mToken, true) >= 0;
3750 } catch (RemoteException e) {
3751 return false;
3752 }
3753 }
3754
3755 /**
3756 * Move the task containing this activity to the back of the activity
3757 * stack. The activity's order within the task is unchanged.
3758 *
3759 * @param nonRoot If false then this only works if the activity is the root
3760 * of a task; if true it will work for any activity in
3761 * a task.
3762 *
3763 * @return If the task was moved (or it was already at the
3764 * back) true is returned, else false.
3765 */
3766 public boolean moveTaskToBack(boolean nonRoot) {
3767 try {
3768 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3769 mToken, nonRoot);
3770 } catch (RemoteException e) {
3771 // Empty
3772 }
3773 return false;
3774 }
3775
3776 /**
3777 * Returns class name for this activity with the package prefix removed.
3778 * This is the default name used to read and write settings.
3779 *
3780 * @return The local class name.
3781 */
3782 public String getLocalClassName() {
3783 final String pkg = getPackageName();
3784 final String cls = mComponent.getClassName();
3785 int packageLen = pkg.length();
3786 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3787 || cls.charAt(packageLen) != '.') {
3788 return cls;
3789 }
3790 return cls.substring(packageLen+1);
3791 }
3792
3793 /**
3794 * Returns complete component name of this activity.
3795 *
3796 * @return Returns the complete component name for this activity
3797 */
3798 public ComponentName getComponentName()
3799 {
3800 return mComponent;
3801 }
3802
3803 /**
3804 * Retrieve a {@link SharedPreferences} object for accessing preferences
3805 * that are private to this activity. This simply calls the underlying
3806 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3807 * class name as the preferences name.
3808 *
3809 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3810 * operation, {@link #MODE_WORLD_READABLE} and
3811 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3812 *
3813 * @return Returns the single SharedPreferences instance that can be used
3814 * to retrieve and modify the preference values.
3815 */
3816 public SharedPreferences getPreferences(int mode) {
3817 return getSharedPreferences(getLocalClassName(), mode);
3818 }
3819
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003820 private void ensureSearchManager() {
3821 if (mSearchManager != null) {
3822 return;
3823 }
3824
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003825 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003826 }
3827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 @Override
3829 public Object getSystemService(String name) {
3830 if (getBaseContext() == null) {
3831 throw new IllegalStateException(
3832 "System services not available to Activities before onCreate()");
3833 }
3834
3835 if (WINDOW_SERVICE.equals(name)) {
3836 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003837 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003838 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003839 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
3841 return super.getSystemService(name);
3842 }
3843
3844 /**
3845 * Change the title associated with this activity. If this is a
3846 * top-level activity, the title for its window will change. If it
3847 * is an embedded activity, the parent can do whatever it wants
3848 * with it.
3849 */
3850 public void setTitle(CharSequence title) {
3851 mTitle = title;
3852 onTitleChanged(title, mTitleColor);
3853
3854 if (mParent != null) {
3855 mParent.onChildTitleChanged(this, title);
3856 }
3857 }
3858
3859 /**
3860 * Change the title associated with this activity. If this is a
3861 * top-level activity, the title for its window will change. If it
3862 * is an embedded activity, the parent can do whatever it wants
3863 * with it.
3864 */
3865 public void setTitle(int titleId) {
3866 setTitle(getText(titleId));
3867 }
3868
3869 public void setTitleColor(int textColor) {
3870 mTitleColor = textColor;
3871 onTitleChanged(mTitle, textColor);
3872 }
3873
3874 public final CharSequence getTitle() {
3875 return mTitle;
3876 }
3877
3878 public final int getTitleColor() {
3879 return mTitleColor;
3880 }
3881
3882 protected void onTitleChanged(CharSequence title, int color) {
3883 if (mTitleReady) {
3884 final Window win = getWindow();
3885 if (win != null) {
3886 win.setTitle(title);
3887 if (color != 0) {
3888 win.setTitleColor(color);
3889 }
3890 }
3891 }
3892 }
3893
3894 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3895 }
3896
3897 /**
3898 * Sets the visibility of the progress bar in the title.
3899 * <p>
3900 * In order for the progress bar to be shown, the feature must be requested
3901 * via {@link #requestWindowFeature(int)}.
3902 *
3903 * @param visible Whether to show the progress bars in the title.
3904 */
3905 public final void setProgressBarVisibility(boolean visible) {
3906 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3907 Window.PROGRESS_VISIBILITY_OFF);
3908 }
3909
3910 /**
3911 * Sets the visibility of the indeterminate progress bar in the title.
3912 * <p>
3913 * In order for the progress bar to be shown, the feature must be requested
3914 * via {@link #requestWindowFeature(int)}.
3915 *
3916 * @param visible Whether to show the progress bars in the title.
3917 */
3918 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3919 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3920 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3921 }
3922
3923 /**
3924 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3925 * is always indeterminate).
3926 * <p>
3927 * In order for the progress bar to be shown, the feature must be requested
3928 * via {@link #requestWindowFeature(int)}.
3929 *
3930 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3931 */
3932 public final void setProgressBarIndeterminate(boolean indeterminate) {
3933 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3934 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3935 }
3936
3937 /**
3938 * Sets the progress for the progress bars in the title.
3939 * <p>
3940 * In order for the progress bar to be shown, the feature must be requested
3941 * via {@link #requestWindowFeature(int)}.
3942 *
3943 * @param progress The progress for the progress bar. Valid ranges are from
3944 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3945 * bar will be completely filled and will fade out.
3946 */
3947 public final void setProgress(int progress) {
3948 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3949 }
3950
3951 /**
3952 * Sets the secondary progress for the progress bar in the title. This
3953 * progress is drawn between the primary progress (set via
3954 * {@link #setProgress(int)} and the background. It can be ideal for media
3955 * scenarios such as showing the buffering progress while the default
3956 * progress shows the play progress.
3957 * <p>
3958 * In order for the progress bar to be shown, the feature must be requested
3959 * via {@link #requestWindowFeature(int)}.
3960 *
3961 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3962 * 0 to 10000 (both inclusive).
3963 */
3964 public final void setSecondaryProgress(int secondaryProgress) {
3965 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3966 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3967 }
3968
3969 /**
3970 * Suggests an audio stream whose volume should be changed by the hardware
3971 * volume controls.
3972 * <p>
3973 * The suggested audio stream will be tied to the window of this Activity.
3974 * If the Activity is switched, the stream set here is no longer the
3975 * suggested stream. The client does not need to save and restore the old
3976 * suggested stream value in onPause and onResume.
3977 *
3978 * @param streamType The type of the audio stream whose volume should be
3979 * changed by the hardware volume controls. It is not guaranteed that
3980 * the hardware volume controls will always change this stream's
3981 * volume (for example, if a call is in progress, its stream's volume
3982 * may be changed instead). To reset back to the default, use
3983 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3984 */
3985 public final void setVolumeControlStream(int streamType) {
3986 getWindow().setVolumeControlStream(streamType);
3987 }
3988
3989 /**
3990 * Gets the suggested audio stream whose volume should be changed by the
3991 * harwdare volume controls.
3992 *
3993 * @return The suggested audio stream type whose volume should be changed by
3994 * the hardware volume controls.
3995 * @see #setVolumeControlStream(int)
3996 */
3997 public final int getVolumeControlStream() {
3998 return getWindow().getVolumeControlStream();
3999 }
4000
4001 /**
4002 * Runs the specified action on the UI thread. If the current thread is the UI
4003 * thread, then the action is executed immediately. If the current thread is
4004 * not the UI thread, the action is posted to the event queue of the UI thread.
4005 *
4006 * @param action the action to run on the UI thread
4007 */
4008 public final void runOnUiThread(Runnable action) {
4009 if (Thread.currentThread() != mUiThread) {
4010 mHandler.post(action);
4011 } else {
4012 action.run();
4013 }
4014 }
4015
4016 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004017 * Standard implementation of
4018 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4019 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004020 * This implementation does nothing and is for
4021 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4022 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4023 *
4024 * @see android.view.LayoutInflater#createView
4025 * @see android.view.Window#getLayoutInflater
4026 */
4027 public View onCreateView(String name, Context context, AttributeSet attrs) {
4028 return null;
4029 }
4030
4031 /**
4032 * Standard implementation of
4033 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4034 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004035 * This implementation handles <fragment> tags to embed fragments inside
4036 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 *
4038 * @see android.view.LayoutInflater#createView
4039 * @see android.view.Window#getLayoutInflater
4040 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004041 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004042 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004043 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004044 }
4045
Dianne Hackborndef15372010-08-15 12:43:52 -07004046 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004047 TypedArray a =
4048 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004049 if (fname == null) {
4050 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4051 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004052 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004053 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4054 a.recycle();
4055
Dianne Hackborn625ac272010-09-17 18:29:22 -07004056 int containerId = parent != null ? parent.getId() : 0;
4057 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004058 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004059 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004060 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004061
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004062 // If we restored from a previous state, we may already have
4063 // instantiated this fragment from the state and should use
4064 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004065 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4066 if (fragment == null && tag != null) {
4067 fragment = mFragments.findFragmentByTag(tag);
4068 }
4069 if (fragment == null && containerId != View.NO_ID) {
4070 fragment = mFragments.findFragmentById(containerId);
4071 }
4072
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004073 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4074 + Integer.toHexString(id) + " fname=" + fname
4075 + " existing=" + fragment);
4076 if (fragment == null) {
4077 fragment = Fragment.instantiate(this, fname);
4078 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004079 fragment.mFragmentId = id != 0 ? id : containerId;
4080 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004081 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004082 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004083 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004084 fragment.mFragmentManager = mFragments;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004085 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4086 mFragments.addFragment(fragment, true);
4087
4088 } else if (fragment.mInLayout) {
4089 // A fragment already exists and it is not one we restored from
4090 // previous state.
4091 throw new IllegalArgumentException(attrs.getPositionDescription()
4092 + ": Duplicate id 0x" + Integer.toHexString(id)
4093 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4094 + " with another fragment for " + fname);
4095 } else {
4096 // This fragment was retained from a previous instance; get it
4097 // going now.
4098 fragment.mInLayout = true;
4099 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004100 // If this fragment is newly instantiated (either right now, or
4101 // from last saved state), then give it the attributes to
4102 // initialize itself.
4103 if (!fragment.mRetaining) {
4104 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4105 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004106 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004107 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004108
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004109 if (fragment.mView == null) {
4110 throw new IllegalStateException("Fragment " + fname
4111 + " did not create a view.");
4112 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004113 if (id != 0) {
4114 fragment.mView.setId(id);
4115 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004116 if (fragment.mView.getTag() == null) {
4117 fragment.mView.setTag(tag);
4118 }
4119 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 }
4121
Daniel Sandler69a48172010-06-23 16:29:36 -04004122 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004123 * Print the Activity's state into the given stream. This gets invoked if
4124 * you run "adb shell dumpsys activity <youractivityname>".
4125 *
4126 * @param fd The raw file descriptor that the dump is being sent to.
4127 * @param writer The PrintWriter to which you should dump your state. This will be
4128 * closed for you after you return.
4129 * @param args additional arguments to the dump request.
4130 */
4131 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
4132 mFragments.dump("", fd, writer, args);
4133 }
4134
4135 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004136 * Bit indicating that this activity is "immersive" and should not be
4137 * interrupted by notifications if possible.
4138 *
4139 * This value is initially set by the manifest property
4140 * <code>android:immersive</code> but may be changed at runtime by
4141 * {@link #setImmersive}.
4142 *
4143 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004144 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004145 */
4146 public boolean isImmersive() {
4147 try {
4148 return ActivityManagerNative.getDefault().isImmersive(mToken);
4149 } catch (RemoteException e) {
4150 return false;
4151 }
4152 }
4153
4154 /**
4155 * Adjust the current immersive mode setting.
4156 *
4157 * Note that changing this value will have no effect on the activity's
4158 * {@link android.content.pm.ActivityInfo} structure; that is, if
4159 * <code>android:immersive</code> is set to <code>true</code>
4160 * in the application's manifest entry for this activity, the {@link
4161 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4162 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4163 * FLAG_IMMERSIVE} bit set.
4164 *
4165 * @see #isImmersive
4166 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004167 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004168 */
4169 public void setImmersive(boolean i) {
4170 try {
4171 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4172 } catch (RemoteException e) {
4173 // pass
4174 }
4175 }
4176
Adam Powell6e346362010-07-23 10:18:23 -07004177 /**
4178 * Start a context mode.
4179 *
4180 * @param callback Callback that will manage lifecycle events for this context mode
4181 * @return The ContextMode that was started, or null if it was canceled
4182 *
4183 * @see ActionMode
4184 */
Adam Powell5d279772010-07-27 16:34:07 -07004185 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004186 return mWindow.getDecorView().startActionMode(callback);
4187 }
4188
4189 public ActionMode onStartActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004190 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004191 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004192 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004193 }
4194 return null;
4195 }
4196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 // ------------------ Internal API ------------------
4198
4199 final void setParent(Activity parent) {
4200 mParent = parent;
4201 }
4202
4203 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4204 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004205 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004207 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004208 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
4210
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004211 final void attach(Context context, ActivityThread aThread,
4212 Instrumentation instr, IBinder token, int ident,
4213 Application application, Intent intent, ActivityInfo info,
4214 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004215 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004216 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 attachBaseContext(context);
4218
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004219 mFragments.attachActivity(this);
4220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 mWindow = PolicyManager.makeNewWindow(this);
4222 mWindow.setCallback(this);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004223 mWindow.getLayoutInflater().setFactory2(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4225 mWindow.setSoftInputMode(info.softInputMode);
4226 }
4227 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 mMainThread = aThread;
4230 mInstrumentation = instr;
4231 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004232 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 mApplication = application;
4234 mIntent = intent;
4235 mComponent = intent.getComponent();
4236 mActivityInfo = info;
4237 mTitle = title;
4238 mParent = parent;
4239 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004240 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241
Romain Guy529b60a2010-08-03 18:05:47 -07004242 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4243 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 if (mParent != null) {
4245 mWindow.setContainer(mParent.getWindow());
4246 }
4247 mWindowManager = mWindow.getWindowManager();
4248 mCurrentConfig = config;
4249 }
4250
4251 final IBinder getActivityToken() {
4252 return mParent != null ? mParent.getActivityToken() : mToken;
4253 }
4254
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004255 final void performCreate(Bundle icicle) {
4256 onCreate(icicle);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004257 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004258 }
4259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004261 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004263 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 mInstrumentation.callActivityOnStart(this);
4265 if (!mCalled) {
4266 throw new SuperNotCalledException(
4267 "Activity " + mComponent.toShortString() +
4268 " did not call through to super.onStart()");
4269 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004270 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004271 if (mAllLoaderManagers != null) {
4272 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4273 mAllLoaderManagers.valueAt(i).finishRetain();
4274 }
4275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 }
4277
4278 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004279 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004280
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004281 synchronized (mManagedCursors) {
4282 final int N = mManagedCursors.size();
4283 for (int i=0; i<N; i++) {
4284 ManagedCursor mc = mManagedCursors.get(i);
4285 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004286 if (!mc.mCursor.requery()) {
4287 throw new IllegalStateException(
4288 "trying to requery an already closed cursor");
4289 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004290 mc.mReleased = false;
4291 mc.mUpdated = false;
4292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 }
4294 }
4295
4296 if (mStopped) {
4297 mStopped = false;
4298 mCalled = false;
4299 mInstrumentation.callActivityOnRestart(this);
4300 if (!mCalled) {
4301 throw new SuperNotCalledException(
4302 "Activity " + mComponent.toShortString() +
4303 " did not call through to super.onRestart()");
4304 }
4305 performStart();
4306 }
4307 }
4308
4309 final void performResume() {
4310 performRestart();
4311
Dianne Hackborn445646c2010-06-25 15:52:59 -07004312 mFragments.execPendingActions();
4313
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004314 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315
4316 // First call onResume() -before- setting mResumed, so we don't
4317 // send out any status bar / menu notifications the client makes.
4318 mCalled = false;
4319 mInstrumentation.callActivityOnResume(this);
4320 if (!mCalled) {
4321 throw new SuperNotCalledException(
4322 "Activity " + mComponent.toShortString() +
4323 " did not call through to super.onResume()");
4324 }
4325
4326 // Now really resume, and install the current status bar and menu.
4327 mResumed = true;
4328 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004329
4330 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004331 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 onPostResume();
4334 if (!mCalled) {
4335 throw new SuperNotCalledException(
4336 "Activity " + mComponent.toShortString() +
4337 " did not call through to super.onPostResume()");
4338 }
4339 }
4340
4341 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004342 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004343 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 onPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004345 if (!mCalled && getApplicationInfo().targetSdkVersion
4346 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4347 throw new SuperNotCalledException(
4348 "Activity " + mComponent.toShortString() +
4349 " did not call through to super.onPause()");
4350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352
4353 final void performUserLeaving() {
4354 onUserInteraction();
4355 onUserLeaveHint();
4356 }
4357
4358 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004359 if (mLoadersStarted) {
4360 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004361 if (mLoaderManager != null) {
4362 if (!mChangingConfigurations) {
4363 mLoaderManager.doStop();
4364 } else {
4365 mLoaderManager.doRetain();
4366 }
4367 }
4368 }
4369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 if (!mStopped) {
4371 if (mWindow != null) {
4372 mWindow.closeAllPanels();
4373 }
4374
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004375 mFragments.dispatchStop();
4376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 mCalled = false;
4378 mInstrumentation.callActivityOnStop(this);
4379 if (!mCalled) {
4380 throw new SuperNotCalledException(
4381 "Activity " + mComponent.toShortString() +
4382 " did not call through to super.onStop()");
4383 }
4384
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004385 synchronized (mManagedCursors) {
4386 final int N = mManagedCursors.size();
4387 for (int i=0; i<N; i++) {
4388 ManagedCursor mc = mManagedCursors.get(i);
4389 if (!mc.mReleased) {
4390 mc.mCursor.deactivate();
4391 mc.mReleased = true;
4392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394 }
4395
4396 mStopped = true;
4397 }
4398 mResumed = false;
4399 }
4400
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004401 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004402 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004403 mFragments.dispatchDestroy();
4404 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004405 if (mLoaderManager != null) {
4406 mLoaderManager.doDestroy();
4407 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004408 }
4409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 final boolean isResumed() {
4411 return mResumed;
4412 }
4413
4414 void dispatchActivityResult(String who, int requestCode,
4415 int resultCode, Intent data) {
4416 if (Config.LOGV) Log.v(
4417 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4418 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004419 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 if (who == null) {
4421 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004422 } else {
4423 Fragment frag = mFragments.findFragmentByWho(who);
4424 if (frag != null) {
4425 frag.onActivityResult(requestCode, resultCode, data);
4426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 }
4428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429}