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