blob: 8d03ac70f8020bfae7f12bddf9702c659c27c74b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Adam Powell6e346362010-07-23 10:18:23 -070019import com.android.internal.app.ActionBarImpl;
20import com.android.internal.policy.PolicyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ComponentCallbacks;
23import android.content.ComponentName;
24import android.content.ContentResolver;
25import android.content.Context;
Jason parks6ed50de2010-08-25 10:18:50 -050026import android.content.CursorLoader;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070027import android.content.IIntentSender;
Adam Powell33b97432010-04-20 10:01:14 -070028import android.content.Intent;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070029import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.SharedPreferences;
31import android.content.pm.ActivityInfo;
32import android.content.res.Configuration;
33import android.content.res.Resources;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070034import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
36import android.graphics.Bitmap;
37import android.graphics.Canvas;
38import android.graphics.drawable.Drawable;
39import android.media.AudioManager;
40import android.net.Uri;
Dianne Hackborn8d374262009-09-14 21:21:52 -070041import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Handler;
44import android.os.IBinder;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -080045import android.os.Looper;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -070046import android.os.Parcelable;
svetoslavganov75986cf2009-05-14 22:28:01 -070047import android.os.RemoteException;
Brad Fitzpatrick75803572011-01-13 14:21:03 -080048import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.text.Selection;
50import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070051import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.text.method.TextKeyListener;
53import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.EventLog;
55import android.util.Log;
56import android.util.SparseArray;
Adam Powell6e346362010-07-23 10:18:23 -070057import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070059import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextThemeWrapper;
61import android.view.KeyEvent;
62import android.view.LayoutInflater;
63import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MotionEvent;
67import android.view.View;
Dianne Hackbornce418e62011-03-01 14:31:38 -080068import android.view.WindowManagerImpl;
Adam Powell6e346362010-07-23 10:18:23 -070069import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070071import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.ViewManager;
73import android.view.Window;
74import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070075import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.widget.AdapterView;
77
Dianne Hackborn625ac272010-09-17 18:29:22 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070080import java.util.ArrayList;
81import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83/**
84 * An activity is a single, focused thing that the user can do. Almost all
85 * activities interact with the user, so the Activity class takes care of
86 * creating a window for you in which you can place your UI with
87 * {@link #setContentView}. While activities are often presented to the user
88 * as full-screen windows, they can also be used in other ways: as floating
89 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
90 * or embedded inside of another activity (using {@link ActivityGroup}).
91 *
92 * There are two methods almost all subclasses of Activity will implement:
93 *
94 * <ul>
95 * <li> {@link #onCreate} is where you initialize your activity. Most
96 * importantly, here you will usually call {@link #setContentView(int)}
97 * with a layout resource defining your UI, and using {@link #findViewById}
98 * to retrieve the widgets in that UI that you need to interact with
99 * programmatically.
100 *
101 * <li> {@link #onPause} is where you deal with the user leaving your
102 * activity. Most importantly, any changes made by the user should at this
103 * point be committed (usually to the
104 * {@link android.content.ContentProvider} holding the data).
105 * </ul>
106 *
107 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
108 * activity classes must have a corresponding
109 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
110 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
111 *
112 * <p>The Activity class is an important part of an application's overall lifecycle,
113 * and the way activities are launched and put together is a fundamental
Scott Main7aee61f2011-02-08 11:25:01 -0800114 * part of the platform's application model. For a detailed perspective on the structure of an
115 * Android application and how activities behave, please read the
116 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
117 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
118 * documents.</p>
119 *
120 * <p>You can also find a detailed discussion about how to create activities in the
121 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
122 * document.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 *
124 * <p>Topics covered here:
125 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700126 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
128 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
129 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
130 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
131 * <li><a href="#Permissions">Permissions</a>
132 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
133 * </ol>
134 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700135 * <a name="Fragments"></a>
136 * <h3>Fragments</h3>
137 *
138 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
139 * implementations can make use of the {@link Fragment} class to better
140 * modularize their code, build more sophisticated user interfaces for larger
141 * screens, and help scale their application between small and large screens.
142 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 * <a name="ActivityLifecycle"></a>
144 * <h3>Activity Lifecycle</h3>
145 *
146 * <p>Activities in the system are managed as an <em>activity stack</em>.
147 * When a new activity is started, it is placed on the top of the stack
148 * and becomes the running activity -- the previous activity always remains
149 * below it in the stack, and will not come to the foreground again until
150 * the new activity exits.</p>
151 *
152 * <p>An activity has essentially four states:</p>
153 * <ul>
154 * <li> If an activity in the foreground of the screen (at the top of
155 * the stack),
156 * it is <em>active</em> or <em>running</em>. </li>
157 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
158 * or transparent activity has focus on top of your activity), it
159 * is <em>paused</em>. A paused activity is completely alive (it
160 * maintains all state and member information and remains attached to
161 * the window manager), but can be killed by the system in extreme
162 * low memory situations.
163 * <li>If an activity is completely obscured by another activity,
164 * it is <em>stopped</em>. It still retains all state and member information,
165 * however, it is no longer visible to the user so its window is hidden
166 * and it will often be killed by the system when memory is needed
167 * elsewhere.</li>
168 * <li>If an activity is paused or stopped, the system can drop the activity
169 * from memory by either asking it to finish, or simply killing its
170 * process. When it is displayed again to the user, it must be
171 * completely restarted and restored to its previous state.</li>
172 * </ul>
173 *
174 * <p>The following diagram shows the important state paths of an Activity.
175 * The square rectangles represent callback methods you can implement to
176 * perform operations when the Activity moves between states. The colored
177 * ovals are major states the Activity can be in.</p>
178 *
179 * <p><img src="../../../images/activity_lifecycle.png"
180 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
181 *
182 * <p>There are three key loops you may be interested in monitoring within your
183 * activity:
184 *
185 * <ul>
186 * <li>The <b>entire lifetime</b> of an activity happens between the first call
187 * to {@link android.app.Activity#onCreate} through to a single final call
188 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
189 * of "global" state in onCreate(), and release all remaining resources in
190 * onDestroy(). For example, if it has a thread running in the background
191 * to download data from the network, it may create that thread in onCreate()
192 * and then stop the thread in onDestroy().
193 *
194 * <li>The <b>visible lifetime</b> of an activity happens between a call to
195 * {@link android.app.Activity#onStart} until a corresponding call to
196 * {@link android.app.Activity#onStop}. During this time the user can see the
197 * activity on-screen, though it may not be in the foreground and interacting
198 * with the user. Between these two methods you can maintain resources that
199 * are needed to show the activity to the user. For example, you can register
200 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
201 * that impact your UI, and unregister it in onStop() when the user an no
202 * longer see what you are displaying. The onStart() and onStop() methods
203 * can be called multiple times, as the activity becomes visible and hidden
204 * to the user.
205 *
206 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
207 * {@link android.app.Activity#onResume} until a corresponding call to
208 * {@link android.app.Activity#onPause}. During this time the activity is
209 * in front of all other activities and interacting with the user. An activity
210 * can frequently go between the resumed and paused states -- for example when
211 * the device goes to sleep, when an activity result is delivered, when a new
212 * intent is delivered -- so the code in these methods should be fairly
213 * lightweight.
214 * </ul>
215 *
216 * <p>The entire lifecycle of an activity is defined by the following
217 * Activity methods. All of these are hooks that you can override
218 * to do appropriate work when the activity changes state. All
219 * activities will implement {@link android.app.Activity#onCreate}
220 * to do their initial setup; many will also implement
221 * {@link android.app.Activity#onPause} to commit changes to data and
222 * otherwise prepare to stop interacting with the user. You should always
223 * call up to your superclass when implementing these methods.</p>
224 *
225 * </p>
226 * <pre class="prettyprint">
227 * public class Activity extends ApplicationContext {
228 * protected void onCreate(Bundle savedInstanceState);
229 *
230 * protected void onStart();
231 *
232 * protected void onRestart();
233 *
234 * protected void onResume();
235 *
236 * protected void onPause();
237 *
238 * protected void onStop();
239 *
240 * protected void onDestroy();
241 * }
242 * </pre>
243 *
244 * <p>In general the movement through an activity's lifecycle looks like
245 * this:</p>
246 *
247 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
248 * <colgroup align="left" span="3" />
249 * <colgroup align="left" />
250 * <colgroup align="center" />
251 * <colgroup align="center" />
252 *
253 * <thead>
254 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
255 * </thead>
256 *
257 * <tbody>
258 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
259 * <td>Called when the activity is first created.
260 * This is where you should do all of your normal static set up:
261 * create views, bind data to lists, etc. This method also
262 * provides you with a Bundle containing the activity's previously
263 * frozen state, if there was one.
264 * <p>Always followed by <code>onStart()</code>.</td>
265 * <td align="center">No</td>
266 * <td align="center"><code>onStart()</code></td>
267 * </tr>
268 *
269 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
270 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
271 * <td>Called after your activity has been stopped, prior to it being
272 * started again.
273 * <p>Always followed by <code>onStart()</code></td>
274 * <td align="center">No</td>
275 * <td align="center"><code>onStart()</code></td>
276 * </tr>
277 *
278 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
279 * <td>Called when the activity is becoming visible to the user.
280 * <p>Followed by <code>onResume()</code> if the activity comes
281 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
282 * <td align="center">No</td>
283 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
284 * </tr>
285 *
286 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
287 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
288 * <td>Called when the activity will start
289 * interacting with the user. At this point your activity is at
290 * the top of the activity stack, with user input going to it.
291 * <p>Always followed by <code>onPause()</code>.</td>
292 * <td align="center">No</td>
293 * <td align="center"><code>onPause()</code></td>
294 * </tr>
295 *
296 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
297 * <td>Called when the system is about to start resuming a previous
298 * activity. This is typically used to commit unsaved changes to
299 * persistent data, stop animations and other things that may be consuming
300 * CPU, etc. Implementations of this method must be very quick because
301 * the next activity will not be resumed until this method returns.
302 * <p>Followed by either <code>onResume()</code> if the activity
303 * returns back to the front, or <code>onStop()</code> if it becomes
304 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800305 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 * <td align="center"><code>onResume()</code> or<br>
307 * <code>onStop()</code></td>
308 * </tr>
309 *
310 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
311 * <td>Called when the activity is no longer visible to the user, because
312 * another activity has been resumed and is covering this one. This
313 * may happen either because a new activity is being started, an existing
314 * one is being brought in front of this one, or this one is being
315 * destroyed.
316 * <p>Followed by either <code>onRestart()</code> if
317 * this activity is coming back to interact with the user, or
318 * <code>onDestroy()</code> if this activity is going away.</td>
319 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
320 * <td align="center"><code>onRestart()</code> or<br>
321 * <code>onDestroy()</code></td>
322 * </tr>
323 *
324 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
325 * <td>The final call you receive before your
326 * activity is destroyed. This can happen either because the
327 * activity is finishing (someone called {@link Activity#finish} on
328 * it, or because the system is temporarily destroying this
329 * instance of the activity to save space. You can distinguish
330 * between these two scenarios with the {@link
331 * Activity#isFinishing} method.</td>
332 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
333 * <td align="center"><em>nothing</em></td>
334 * </tr>
335 * </tbody>
336 * </table>
337 *
338 * <p>Note the "Killable" column in the above table -- for those methods that
339 * are marked as being killable, after that method returns the process hosting the
340 * activity may killed by the system <em>at any time</em> without another line
341 * of its code being executed. Because of this, you should use the
342 * {@link #onPause} method to write any persistent data (such as user edits)
343 * to storage. In addition, the method
344 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
345 * in such a background state, allowing you to save away any dynamic instance
346 * state in your activity into the given Bundle, to be later received in
347 * {@link #onCreate} if the activity needs to be re-created.
348 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
349 * section for more information on how the lifecycle of a process is tied
350 * to the activities it is hosting. Note that it is important to save
351 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
Daisuke Miyakawa5c40f3f2011-02-15 13:24:36 -0800352 * because the latter is not part of the lifecycle callbacks, so will not
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 * be called in every situation as described in its documentation.</p>
354 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800355 * <p class="note">Be aware that these semantics will change slightly between
356 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
357 * vs. those targeting prior platforms. Starting with Honeycomb, an application
358 * is not in the killable state until its {@link #onStop} has returned. This
359 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
360 * safely called after {@link #onPause()} and allows and application to safely
361 * wait until {@link #onStop()} to save persistent state.</p>
362 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 * <p>For those methods that are not marked as being killable, the activity's
364 * process will not be killed by the system starting from the time the method
365 * is called and continuing after it returns. Thus an activity is in the killable
366 * state, for example, between after <code>onPause()</code> to the start of
367 * <code>onResume()</code>.</p>
368 *
369 * <a name="ConfigurationChanges"></a>
370 * <h3>Configuration Changes</h3>
371 *
372 * <p>If the configuration of the device (as defined by the
373 * {@link Configuration Resources.Configuration} class) changes,
374 * then anything displaying a user interface will need to update to match that
375 * configuration. Because Activity is the primary mechanism for interacting
376 * with the user, it includes special support for handling configuration
377 * changes.</p>
378 *
379 * <p>Unless you specify otherwise, a configuration change (such as a change
380 * in screen orientation, language, input devices, etc) will cause your
381 * current activity to be <em>destroyed</em>, going through the normal activity
382 * lifecycle process of {@link #onPause},
383 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
384 * had been in the foreground or visible to the user, once {@link #onDestroy} is
385 * called in that instance then a new instance of the activity will be
386 * created, with whatever savedInstanceState the previous instance had generated
387 * from {@link #onSaveInstanceState}.</p>
388 *
389 * <p>This is done because any application resource,
390 * including layout files, can change based on any configuration value. Thus
391 * the only safe way to handle a configuration change is to re-retrieve all
392 * resources, including layouts, drawables, and strings. Because activities
393 * must already know how to save their state and re-create themselves from
394 * that state, this is a convenient way to have an activity restart itself
395 * with a new configuration.</p>
396 *
397 * <p>In some special cases, you may want to bypass restarting of your
398 * activity based on one or more types of configuration changes. This is
399 * done with the {@link android.R.attr#configChanges android:configChanges}
400 * attribute in its manifest. For any types of configuration changes you say
401 * that you handle there, you will receive a call to your current activity's
402 * {@link #onConfigurationChanged} method instead of being restarted. If
403 * a configuration change involves any that you do not handle, however, the
404 * activity will still be restarted and {@link #onConfigurationChanged}
405 * will not be called.</p>
406 *
407 * <a name="StartingActivities"></a>
408 * <h3>Starting Activities and Getting Results</h3>
409 *
410 * <p>The {@link android.app.Activity#startActivity}
411 * method is used to start a
412 * new activity, which will be placed at the top of the activity stack. It
413 * takes a single argument, an {@link android.content.Intent Intent},
414 * which describes the activity
415 * to be executed.</p>
416 *
417 * <p>Sometimes you want to get a result back from an activity when it
418 * ends. For example, you may start an activity that lets the user pick
419 * a person in a list of contacts; when it ends, it returns the person
420 * that was selected. To do this, you call the
421 * {@link android.app.Activity#startActivityForResult(Intent, int)}
422 * version with a second integer parameter identifying the call. The result
423 * will come back through your {@link android.app.Activity#onActivityResult}
424 * method.</p>
425 *
426 * <p>When an activity exits, it can call
427 * {@link android.app.Activity#setResult(int)}
428 * to return data back to its parent. It must always supply a result code,
429 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
430 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
431 * return back an Intent containing any additional data it wants. All of this
432 * information appears back on the
433 * parent's <code>Activity.onActivityResult()</code>, along with the integer
434 * identifier it originally supplied.</p>
435 *
436 * <p>If a child activity fails for any reason (such as crashing), the parent
437 * activity will receive a result with the code RESULT_CANCELED.</p>
438 *
439 * <pre class="prettyprint">
440 * public class MyActivity extends Activity {
441 * ...
442 *
443 * static final int PICK_CONTACT_REQUEST = 0;
444 *
445 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
446 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
447 * // When the user center presses, let them pick a contact.
448 * startActivityForResult(
449 * new Intent(Intent.ACTION_PICK,
450 * new Uri("content://contacts")),
451 * PICK_CONTACT_REQUEST);
452 * return true;
453 * }
454 * return false;
455 * }
456 *
457 * protected void onActivityResult(int requestCode, int resultCode,
458 * Intent data) {
459 * if (requestCode == PICK_CONTACT_REQUEST) {
460 * if (resultCode == RESULT_OK) {
461 * // A contact was picked. Here we will just display it
462 * // to the user.
463 * startActivity(new Intent(Intent.ACTION_VIEW, data));
464 * }
465 * }
466 * }
467 * }
468 * </pre>
469 *
470 * <a name="SavingPersistentState"></a>
471 * <h3>Saving Persistent State</h3>
472 *
473 * <p>There are generally two kinds of persistent state than an activity
474 * will deal with: shared document-like data (typically stored in a SQLite
475 * database using a {@linkplain android.content.ContentProvider content provider})
476 * and internal state such as user preferences.</p>
477 *
478 * <p>For content provider data, we suggest that activities use a
479 * "edit in place" user model. That is, any edits a user makes are effectively
480 * made immediately without requiring an additional confirmation step.
481 * Supporting this model is generally a simple matter of following two rules:</p>
482 *
483 * <ul>
484 * <li> <p>When creating a new document, the backing database entry or file for
485 * it is created immediately. For example, if the user chooses to write
486 * a new e-mail, a new entry for that e-mail is created as soon as they
487 * start entering data, so that if they go to any other activity after
488 * that point this e-mail will now appear in the list of drafts.</p>
489 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
490 * commit to the backing content provider or file any changes the user
491 * has made. This ensures that those changes will be seen by any other
492 * activity that is about to run. You will probably want to commit
493 * your data even more aggressively at key times during your
494 * activity's lifecycle: for example before starting a new
495 * activity, before finishing your own activity, when the user
496 * switches between input fields, etc.</p>
497 * </ul>
498 *
499 * <p>This model is designed to prevent data loss when a user is navigating
500 * between activities, and allows the system to safely kill an activity (because
501 * system resources are needed somewhere else) at any time after it has been
502 * paused. Note this implies
503 * that the user pressing BACK from your activity does <em>not</em>
504 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800505 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
507 *
508 * <p>See the {@linkplain android.content.ContentProvider content package} for
509 * more information about content providers. These are a key aspect of how
510 * different activities invoke and propagate data between themselves.</p>
511 *
512 * <p>The Activity class also provides an API for managing internal persistent state
513 * associated with an activity. This can be used, for example, to remember
514 * the user's preferred initial display in a calendar (day view or week view)
515 * or the user's default home page in a web browser.</p>
516 *
517 * <p>Activity persistent state is managed
518 * with the method {@link #getPreferences},
519 * allowing you to retrieve and
520 * modify a set of name/value pairs associated with the activity. To use
521 * preferences that are shared across multiple application components
522 * (activities, receivers, services, providers), you can use the underlying
523 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
524 * to retrieve a preferences
525 * object stored under a specific name.
526 * (Note that it is not possible to share settings data across application
527 * packages -- for that you will need a content provider.)</p>
528 *
529 * <p>Here is an excerpt from a calendar activity that stores the user's
530 * preferred view mode in its persistent settings:</p>
531 *
532 * <pre class="prettyprint">
533 * public class CalendarActivity extends Activity {
534 * ...
535 *
536 * static final int DAY_VIEW_MODE = 0;
537 * static final int WEEK_VIEW_MODE = 1;
538 *
539 * private SharedPreferences mPrefs;
540 * private int mCurViewMode;
541 *
542 * protected void onCreate(Bundle savedInstanceState) {
543 * super.onCreate(savedInstanceState);
544 *
545 * SharedPreferences mPrefs = getSharedPreferences();
546 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
547 * }
548 *
549 * protected void onPause() {
550 * super.onPause();
551 *
552 * SharedPreferences.Editor ed = mPrefs.edit();
553 * ed.putInt("view_mode", mCurViewMode);
554 * ed.commit();
555 * }
556 * }
557 * </pre>
558 *
559 * <a name="Permissions"></a>
560 * <h3>Permissions</h3>
561 *
562 * <p>The ability to start a particular Activity can be enforced when it is
563 * declared in its
564 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
565 * tag. By doing so, other applications will need to declare a corresponding
566 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
567 * element in their own manifest to be able to start that activity.
568 *
569 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
570 * document for more information on permissions and security in general.
571 *
572 * <a name="ProcessLifecycle"></a>
573 * <h3>Process Lifecycle</h3>
574 *
575 * <p>The Android system attempts to keep application process around for as
576 * long as possible, but eventually will need to remove old processes when
577 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
578 * Lifecycle</a>, the decision about which process to remove is intimately
579 * tied to the state of the user's interaction with it. In general, there
580 * are four states a process can be in based on the activities running in it,
581 * listed here in order of importance. The system will kill less important
582 * processes (the last ones) before it resorts to killing more important
583 * processes (the first ones).
584 *
585 * <ol>
586 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
587 * that the user is currently interacting with) is considered the most important.
588 * Its process will only be killed as a last resort, if it uses more memory
589 * than is available on the device. Generally at this point the device has
590 * reached a memory paging state, so this is required in order to keep the user
591 * interface responsive.
592 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
593 * but not in the foreground, such as one sitting behind a foreground dialog)
594 * is considered extremely important and will not be killed unless that is
595 * required to keep the foreground activity running.
596 * <li> <p>A <b>background activity</b> (an activity that is not visible to
597 * the user and has been paused) is no longer critical, so the system may
598 * safely kill its process to reclaim memory for other foreground or
599 * visible processes. If its process needs to be killed, when the user navigates
600 * back to the activity (making it visible on the screen again), its
601 * {@link #onCreate} method will be called with the savedInstanceState it had previously
602 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
603 * state as the user last left it.
604 * <li> <p>An <b>empty process</b> is one hosting no activities or other
605 * application components (such as {@link Service} or
606 * {@link android.content.BroadcastReceiver} classes). These are killed very
607 * quickly by the system as memory becomes low. For this reason, any
608 * background operation you do outside of an activity must be executed in the
609 * context of an activity BroadcastReceiver or Service to ensure that the system
610 * knows it needs to keep your process around.
611 * </ol>
612 *
613 * <p>Sometimes an Activity may need to do a long-running operation that exists
614 * independently of the activity lifecycle itself. An example may be a camera
615 * application that allows you to upload a picture to a web site. The upload
616 * may take a long time, and the application should allow the user to leave
617 * the application will it is executing. To accomplish this, your Activity
618 * should start a {@link Service} in which the upload takes place. This allows
619 * the system to properly prioritize your process (considering it to be more
620 * important than other non-visible applications) for the duration of the
621 * upload, independent of whether the original activity is paused, stopped,
622 * or finished.
623 */
624public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700625 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 Window.Callback, KeyEvent.Callback,
627 OnCreateContextMenuListener, ComponentCallbacks {
628 private static final String TAG = "Activity";
629
630 /** Standard activity result: operation canceled. */
631 public static final int RESULT_CANCELED = 0;
632 /** Standard activity result: operation succeeded. */
633 public static final int RESULT_OK = -1;
634 /** Start of user-defined activity results. */
635 public static final int RESULT_FIRST_USER = 1;
636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700638 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
640 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
641 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800642 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800644 private static class ManagedDialog {
645 Dialog mDialog;
646 Bundle mArgs;
647 }
648 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
650 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
651 private Instrumentation mInstrumentation;
652 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700653 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 /*package*/ String mEmbeddedID;
655 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700656 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 private ComponentName mComponent;
658 /*package*/ ActivityInfo mActivityInfo;
659 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 Activity mParent;
661 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700662 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700663 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600664 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 private boolean mStopped;
666 boolean mFinished;
667 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700668 /** true if the activity is going through a transient pause */
669 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500670 /** true if the activity is being destroyed in order to recreate it with a new configuration */
671 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 /*package*/ int mConfigChangeFlags;
673 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100674 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700676 static final class NonConfigurationInstances {
677 Object activity;
678 HashMap<String, Object> children;
679 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700680 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700681 }
682 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 private Window mWindow;
685
686 private WindowManager mWindowManager;
687 /*package*/ View mDecor = null;
688 /*package*/ boolean mWindowAdded = false;
689 /*package*/ boolean mVisibleFromServer = false;
690 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700691 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692
693 private CharSequence mTitle;
694 private int mTitleColor = 0;
695
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700696 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700697
Dianne Hackborn4911b782010-07-15 12:54:39 -0700698 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
699 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 private static final class ManagedCursor {
702 ManagedCursor(Cursor cursor) {
703 mCursor = cursor;
704 mReleased = false;
705 mUpdated = false;
706 }
707
708 private final Cursor mCursor;
709 private boolean mReleased;
710 private boolean mUpdated;
711 }
712 private final ArrayList<ManagedCursor> mManagedCursors =
713 new ArrayList<ManagedCursor>();
714
715 // protected by synchronized (this)
716 int mResultCode = RESULT_CANCELED;
717 Intent mResultData = null;
718
719 private boolean mTitleReady = false;
720
721 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
722 private SpannableStringBuilder mDefaultKeySsb = null;
723
724 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
725
Jeff Brown7e442832011-06-10 18:00:16 -0700726 private final Object mInstanceTracker = StrictMode.trackActivity(this);
727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700729 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 /** Return the intent that started this activity. */
732 public Intent getIntent() {
733 return mIntent;
734 }
735
736 /**
737 * Change the intent returned by {@link #getIntent}. This holds a
738 * reference to the given intent; it does not copy it. Often used in
739 * conjunction with {@link #onNewIntent}.
740 *
741 * @param newIntent The new Intent object to return from getIntent
742 *
743 * @see #getIntent
744 * @see #onNewIntent
745 */
746 public void setIntent(Intent newIntent) {
747 mIntent = newIntent;
748 }
749
750 /** Return the application that owns this activity. */
751 public final Application getApplication() {
752 return mApplication;
753 }
754
755 /** Is this activity embedded inside of another activity? */
756 public final boolean isChild() {
757 return mParent != null;
758 }
759
760 /** Return the parent activity if this view is an embedded child. */
761 public final Activity getParent() {
762 return mParent;
763 }
764
765 /** Retrieve the window manager for showing custom windows. */
766 public WindowManager getWindowManager() {
767 return mWindowManager;
768 }
769
770 /**
771 * Retrieve the current {@link android.view.Window} for the activity.
772 * This can be used to directly access parts of the Window API that
773 * are not available through Activity/Screen.
774 *
775 * @return Window The current window, or null if the activity is not
776 * visual.
777 */
778 public Window getWindow() {
779 return mWindow;
780 }
781
782 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700783 * Return the LoaderManager for this fragment, creating it if needed.
784 */
785 public LoaderManager getLoaderManager() {
786 if (mLoaderManager != null) {
787 return mLoaderManager;
788 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700789 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700790 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700791 return mLoaderManager;
792 }
793
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700794 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700795 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700796 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700797 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700798 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700799 if (lm == null) {
800 if (create) {
801 lm = new LoaderManagerImpl(this, started);
802 mAllLoaderManagers.put(index, lm);
803 }
804 } else {
805 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700806 }
807 return lm;
808 }
809
810 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 * Calls {@link android.view.Window#getCurrentFocus} on the
812 * Window of this Activity to return the currently focused view.
813 *
814 * @return View The current View with focus or null.
815 *
816 * @see #getWindow
817 * @see android.view.Window#getCurrentFocus
818 */
819 public View getCurrentFocus() {
820 return mWindow != null ? mWindow.getCurrentFocus() : null;
821 }
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 /**
824 * Called when the activity is starting. This is where most initialization
825 * should go: calling {@link #setContentView(int)} to inflate the
826 * activity's UI, using {@link #findViewById} to programmatically interact
827 * with widgets in the UI, calling
828 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
829 * cursors for data being displayed, etc.
830 *
831 * <p>You can call {@link #finish} from within this function, in
832 * which case onDestroy() will be immediately called without any of the rest
833 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
834 * {@link #onPause}, etc) executing.
835 *
836 * <p><em>Derived classes must call through to the super class's
837 * implementation of this method. If they do not, an exception will be
838 * thrown.</em></p>
839 *
840 * @param savedInstanceState If the activity is being re-initialized after
841 * previously being shut down then this Bundle contains the data it most
842 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
843 *
844 * @see #onStart
845 * @see #onSaveInstanceState
846 * @see #onRestoreInstanceState
847 * @see #onPostCreate
848 */
849 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700850 if (mLastNonConfigurationInstances != null) {
851 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
852 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700853 if (savedInstanceState != null) {
854 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
855 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
856 ? mLastNonConfigurationInstances.fragments : null);
857 }
858 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mCalled = true;
860 }
861
862 /**
863 * The hook for {@link ActivityThread} to restore the state of this activity.
864 *
865 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
866 * {@link #restoreManagedDialogs(android.os.Bundle)}.
867 *
868 * @param savedInstanceState contains the saved state
869 */
870 final void performRestoreInstanceState(Bundle savedInstanceState) {
871 onRestoreInstanceState(savedInstanceState);
872 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
875 /**
876 * This method is called after {@link #onStart} when the activity is
877 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800878 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 * to restore their state, but it is sometimes convenient to do it here
880 * after all of the initialization has been done or to allow subclasses to
881 * decide whether to use your default implementation. The default
882 * implementation of this method performs a restore of any view state that
883 * had previously been frozen by {@link #onSaveInstanceState}.
884 *
885 * <p>This method is called between {@link #onStart} and
886 * {@link #onPostCreate}.
887 *
888 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
889 *
890 * @see #onCreate
891 * @see #onPostCreate
892 * @see #onResume
893 * @see #onSaveInstanceState
894 */
895 protected void onRestoreInstanceState(Bundle savedInstanceState) {
896 if (mWindow != null) {
897 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
898 if (windowState != null) {
899 mWindow.restoreHierarchyState(windowState);
900 }
901 }
902 }
903
904 /**
905 * Restore the state of any saved managed dialogs.
906 *
907 * @param savedInstanceState The bundle to restore from.
908 */
909 private void restoreManagedDialogs(Bundle savedInstanceState) {
910 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
911 if (b == null) {
912 return;
913 }
914
915 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
916 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800917 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 for (int i = 0; i < numDialogs; i++) {
919 final Integer dialogId = ids[i];
920 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
921 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700922 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
923 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800924 final ManagedDialog md = new ManagedDialog();
925 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
926 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
927 if (md.mDialog != null) {
928 mManagedDialogs.put(dialogId, md);
929 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
930 md.mDialog.onRestoreInstanceState(dialogState);
931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
933 }
934 }
935
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800936 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
937 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700938 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800939 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700940 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700941 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700942 return dialog;
943 }
944
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800945 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 return SAVED_DIALOG_KEY_PREFIX + key;
947 }
948
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800949 private static String savedDialogArgsKeyFor(int key) {
950 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952
953 /**
954 * Called when activity start-up is complete (after {@link #onStart}
955 * and {@link #onRestoreInstanceState} have been called). Applications will
956 * generally not implement this method; it is intended for system
957 * classes to do final initialization after application code has run.
958 *
959 * <p><em>Derived classes must call through to the super class's
960 * implementation of this method. If they do not, an exception will be
961 * thrown.</em></p>
962 *
963 * @param savedInstanceState If the activity is being re-initialized after
964 * previously being shut down then this Bundle contains the data it most
965 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
966 * @see #onCreate
967 */
968 protected void onPostCreate(Bundle savedInstanceState) {
969 if (!isChild()) {
970 mTitleReady = true;
971 onTitleChanged(getTitle(), getTitleColor());
972 }
973 mCalled = true;
974 }
975
976 /**
977 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
978 * the activity had been stopped, but is now again being displayed to the
979 * user. It will be followed by {@link #onResume}.
980 *
981 * <p><em>Derived classes must call through to the super class's
982 * implementation of this method. If they do not, an exception will be
983 * thrown.</em></p>
984 *
985 * @see #onCreate
986 * @see #onStop
987 * @see #onResume
988 */
989 protected void onStart() {
990 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700991
992 if (!mLoadersStarted) {
993 mLoadersStarted = true;
994 if (mLoaderManager != null) {
995 mLoaderManager.doStart();
996 } else if (!mCheckedForLoaderManager) {
997 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
998 }
999 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002
1003 /**
1004 * Called after {@link #onStop} when the current activity is being
1005 * re-displayed to the user (the user has navigated back to it). It will
1006 * be followed by {@link #onStart} and then {@link #onResume}.
1007 *
1008 * <p>For activities that are using raw {@link Cursor} objects (instead of
1009 * creating them through
1010 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1011 * this is usually the place
1012 * where the cursor should be requeried (because you had deactivated it in
1013 * {@link #onStop}.
1014 *
1015 * <p><em>Derived classes must call through to the super class's
1016 * implementation of this method. If they do not, an exception will be
1017 * thrown.</em></p>
1018 *
1019 * @see #onStop
1020 * @see #onStart
1021 * @see #onResume
1022 */
1023 protected void onRestart() {
1024 mCalled = true;
1025 }
1026
1027 /**
1028 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1029 * {@link #onPause}, for your activity to start interacting with the user.
1030 * This is a good place to begin animations, open exclusive-access devices
1031 * (such as the camera), etc.
1032 *
1033 * <p>Keep in mind that onResume is not the best indicator that your activity
1034 * is visible to the user; a system window such as the keyguard may be in
1035 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1036 * activity is visible to the user (for example, to resume a game).
1037 *
1038 * <p><em>Derived classes must call through to the super class's
1039 * implementation of this method. If they do not, an exception will be
1040 * thrown.</em></p>
1041 *
1042 * @see #onRestoreInstanceState
1043 * @see #onRestart
1044 * @see #onPostResume
1045 * @see #onPause
1046 */
1047 protected void onResume() {
1048 mCalled = true;
1049 }
1050
1051 /**
1052 * Called when activity resume is complete (after {@link #onResume} has
1053 * been called). Applications will generally not implement this method;
1054 * it is intended for system classes to do final setup after application
1055 * resume code has run.
1056 *
1057 * <p><em>Derived classes must call through to the super class's
1058 * implementation of this method. If they do not, an exception will be
1059 * thrown.</em></p>
1060 *
1061 * @see #onResume
1062 */
1063 protected void onPostResume() {
1064 final Window win = getWindow();
1065 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001066 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 mCalled = true;
1068 }
1069
1070 /**
1071 * This is called for activities that set launchMode to "singleTop" in
1072 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1073 * flag when calling {@link #startActivity}. In either case, when the
1074 * activity is re-launched while at the top of the activity stack instead
1075 * of a new instance of the activity being started, onNewIntent() will be
1076 * called on the existing instance with the Intent that was used to
1077 * re-launch it.
1078 *
1079 * <p>An activity will always be paused before receiving a new intent, so
1080 * you can count on {@link #onResume} being called after this method.
1081 *
1082 * <p>Note that {@link #getIntent} still returns the original Intent. You
1083 * can use {@link #setIntent} to update it to this new Intent.
1084 *
1085 * @param intent The new intent that was started for the activity.
1086 *
1087 * @see #getIntent
1088 * @see #setIntent
1089 * @see #onResume
1090 */
1091 protected void onNewIntent(Intent intent) {
1092 }
1093
1094 /**
1095 * The hook for {@link ActivityThread} to save the state of this activity.
1096 *
1097 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1098 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1099 *
1100 * @param outState The bundle to save the state to.
1101 */
1102 final void performSaveInstanceState(Bundle outState) {
1103 onSaveInstanceState(outState);
1104 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106
1107 /**
1108 * Called to retrieve per-instance state from an activity before being killed
1109 * so that the state can be restored in {@link #onCreate} or
1110 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1111 * will be passed to both).
1112 *
1113 * <p>This method is called before an activity may be killed so that when it
1114 * comes back some time in the future it can restore its state. For example,
1115 * if activity B is launched in front of activity A, and at some point activity
1116 * A is killed to reclaim resources, activity A will have a chance to save the
1117 * current state of its user interface via this method so that when the user
1118 * returns to activity A, the state of the user interface can be restored
1119 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1120 *
1121 * <p>Do not confuse this method with activity lifecycle callbacks such as
1122 * {@link #onPause}, which is always called when an activity is being placed
1123 * in the background or on its way to destruction, or {@link #onStop} which
1124 * is called before destruction. One example of when {@link #onPause} and
1125 * {@link #onStop} is called and not this method is when a user navigates back
1126 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1127 * on B because that particular instance will never be restored, so the
1128 * system avoids calling it. An example when {@link #onPause} is called and
1129 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1130 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1131 * killed during the lifetime of B since the state of the user interface of
1132 * A will stay intact.
1133 *
1134 * <p>The default implementation takes care of most of the UI per-instance
1135 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1136 * view in the hierarchy that has an id, and by saving the id of the currently
1137 * focused view (all of which is restored by the default implementation of
1138 * {@link #onRestoreInstanceState}). If you override this method to save additional
1139 * information not captured by each individual view, you will likely want to
1140 * call through to the default implementation, otherwise be prepared to save
1141 * all of the state of each view yourself.
1142 *
1143 * <p>If called, this method will occur before {@link #onStop}. There are
1144 * no guarantees about whether it will occur before or after {@link #onPause}.
1145 *
1146 * @param outState Bundle in which to place your saved state.
1147 *
1148 * @see #onCreate
1149 * @see #onRestoreInstanceState
1150 * @see #onPause
1151 */
1152 protected void onSaveInstanceState(Bundle outState) {
1153 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001154 Parcelable p = mFragments.saveAllState();
1155 if (p != null) {
1156 outState.putParcelable(FRAGMENTS_TAG, p);
1157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
1159
1160 /**
1161 * Save the state of any managed dialogs.
1162 *
1163 * @param outState place to store the saved state.
1164 */
1165 private void saveManagedDialogs(Bundle outState) {
1166 if (mManagedDialogs == null) {
1167 return;
1168 }
1169
1170 final int numDialogs = mManagedDialogs.size();
1171 if (numDialogs == 0) {
1172 return;
1173 }
1174
1175 Bundle dialogState = new Bundle();
1176
1177 int[] ids = new int[mManagedDialogs.size()];
1178
1179 // save each dialog's bundle, gather the ids
1180 for (int i = 0; i < numDialogs; i++) {
1181 final int key = mManagedDialogs.keyAt(i);
1182 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001183 final ManagedDialog md = mManagedDialogs.valueAt(i);
1184 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1185 if (md.mArgs != null) {
1186 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189
1190 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1191 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1192 }
1193
1194
1195 /**
1196 * Called as part of the activity lifecycle when an activity is going into
1197 * the background, but has not (yet) been killed. The counterpart to
1198 * {@link #onResume}.
1199 *
1200 * <p>When activity B is launched in front of activity A, this callback will
1201 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1202 * so be sure to not do anything lengthy here.
1203 *
1204 * <p>This callback is mostly used for saving any persistent state the
1205 * activity is editing, to present a "edit in place" model to the user and
1206 * making sure nothing is lost if there are not enough resources to start
1207 * the new activity without first killing this one. This is also a good
1208 * place to do things like stop animations and other things that consume a
1209 * noticeable mount of CPU in order to make the switch to the next activity
1210 * as fast as possible, or to close resources that are exclusive access
1211 * such as the camera.
1212 *
1213 * <p>In situations where the system needs more memory it may kill paused
1214 * processes to reclaim resources. Because of this, you should be sure
1215 * that all of your state is saved by the time you return from
1216 * this function. In general {@link #onSaveInstanceState} is used to save
1217 * per-instance state in the activity and this method is used to store
1218 * global persistent data (in content providers, files, etc.)
1219 *
1220 * <p>After receiving this call you will usually receive a following call
1221 * to {@link #onStop} (after the next activity has been resumed and
1222 * displayed), however in some cases there will be a direct call back to
1223 * {@link #onResume} without going through the stopped state.
1224 *
1225 * <p><em>Derived classes must call through to the super class's
1226 * implementation of this method. If they do not, an exception will be
1227 * thrown.</em></p>
1228 *
1229 * @see #onResume
1230 * @see #onSaveInstanceState
1231 * @see #onStop
1232 */
1233 protected void onPause() {
1234 mCalled = true;
1235 }
1236
1237 /**
1238 * Called as part of the activity lifecycle when an activity is about to go
1239 * into the background as the result of user choice. For example, when the
1240 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1241 * when an incoming phone call causes the in-call Activity to be automatically
1242 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1243 * the activity being interrupted. In cases when it is invoked, this method
1244 * is called right before the activity's {@link #onPause} callback.
1245 *
1246 * <p>This callback and {@link #onUserInteraction} are intended to help
1247 * activities manage status bar notifications intelligently; specifically,
1248 * for helping activities determine the proper time to cancel a notfication.
1249 *
1250 * @see #onUserInteraction()
1251 */
1252 protected void onUserLeaveHint() {
1253 }
1254
1255 /**
1256 * Generate a new thumbnail for this activity. This method is called before
1257 * pausing the activity, and should draw into <var>outBitmap</var> the
1258 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1259 * can use the given <var>canvas</var>, which is configured to draw into the
1260 * bitmap, for rendering if desired.
1261 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001262 * <p>The default implementation returns fails and does not draw a thumbnail;
1263 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 *
1265 * @param outBitmap The bitmap to contain the thumbnail.
1266 * @param canvas Can be used to render into the bitmap.
1267 *
1268 * @return Return true if you have drawn into the bitmap; otherwise after
1269 * you return it will be filled with a default thumbnail.
1270 *
1271 * @see #onCreateDescription
1272 * @see #onSaveInstanceState
1273 * @see #onPause
1274 */
1275 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001276 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278
1279 /**
1280 * Generate a new description for this activity. This method is called
1281 * before pausing the activity and can, if desired, return some textual
1282 * description of its current state to be displayed to the user.
1283 *
1284 * <p>The default implementation returns null, which will cause you to
1285 * inherit the description from the previous activity. If all activities
1286 * return null, generally the label of the top activity will be used as the
1287 * description.
1288 *
1289 * @return A description of what the user is doing. It should be short and
1290 * sweet (only a few words).
1291 *
1292 * @see #onCreateThumbnail
1293 * @see #onSaveInstanceState
1294 * @see #onPause
1295 */
1296 public CharSequence onCreateDescription() {
1297 return null;
1298 }
1299
1300 /**
1301 * Called when you are no longer visible to the user. You will next
1302 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1303 * depending on later user activity.
1304 *
1305 * <p>Note that this method may never be called, in low memory situations
1306 * where the system does not have enough memory to keep your activity's
1307 * process running after its {@link #onPause} method is called.
1308 *
1309 * <p><em>Derived classes must call through to the super class's
1310 * implementation of this method. If they do not, an exception will be
1311 * thrown.</em></p>
1312 *
1313 * @see #onRestart
1314 * @see #onResume
1315 * @see #onSaveInstanceState
1316 * @see #onDestroy
1317 */
1318 protected void onStop() {
Adam Powell50efbed2011-02-08 16:20:15 -08001319 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 mCalled = true;
1321 }
1322
1323 /**
1324 * Perform any final cleanup before an activity is destroyed. This can
1325 * happen either because the activity is finishing (someone called
1326 * {@link #finish} on it, or because the system is temporarily destroying
1327 * this instance of the activity to save space. You can distinguish
1328 * between these two scenarios with the {@link #isFinishing} method.
1329 *
1330 * <p><em>Note: do not count on this method being called as a place for
1331 * saving data! For example, if an activity is editing data in a content
1332 * provider, those edits should be committed in either {@link #onPause} or
1333 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1334 * free resources like threads that are associated with an activity, so
1335 * that a destroyed activity does not leave such things around while the
1336 * rest of its application is still running. There are situations where
1337 * the system will simply kill the activity's hosting process without
1338 * calling this method (or any others) in it, so it should not be used to
1339 * do things that are intended to remain around after the process goes
1340 * away.
1341 *
1342 * <p><em>Derived classes must call through to the super class's
1343 * implementation of this method. If they do not, an exception will be
1344 * thrown.</em></p>
1345 *
1346 * @see #onPause
1347 * @see #onStop
1348 * @see #finish
1349 * @see #isFinishing
1350 */
1351 protected void onDestroy() {
1352 mCalled = true;
1353
1354 // dismiss any dialogs we are managing.
1355 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 final int numDialogs = mManagedDialogs.size();
1357 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001358 final ManagedDialog md = mManagedDialogs.valueAt(i);
1359 if (md.mDialog.isShowing()) {
1360 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001363 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365
1366 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001367 synchronized (mManagedCursors) {
1368 int numCursors = mManagedCursors.size();
1369 for (int i = 0; i < numCursors; i++) {
1370 ManagedCursor c = mManagedCursors.get(i);
1371 if (c != null) {
1372 c.mCursor.close();
1373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001375 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Amith Yamasani49860442010-03-17 20:54:10 -07001377
1378 // Close any open search dialog
1379 if (mSearchManager != null) {
1380 mSearchManager.stopSearch();
1381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
1383
1384 /**
1385 * Called by the system when the device configuration changes while your
1386 * activity is running. Note that this will <em>only</em> be called if
1387 * you have selected configurations you would like to handle with the
1388 * {@link android.R.attr#configChanges} attribute in your manifest. If
1389 * any configuration change occurs that is not selected to be reported
1390 * by that attribute, then instead of reporting it the system will stop
1391 * and restart the activity (to have it launched with the new
1392 * configuration).
1393 *
1394 * <p>At the time that this function has been called, your Resources
1395 * object will have been updated to return resource values matching the
1396 * new configuration.
1397 *
1398 * @param newConfig The new device configuration.
1399 */
1400 public void onConfigurationChanged(Configuration newConfig) {
1401 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001402
Adam Powellf8ac6b72011-05-23 18:14:09 -07001403 if (mActionBar != null) {
1404 mActionBar.onConfigurationChanged(newConfig);
1405 }
1406
Dianne Hackborn9d071802010-12-08 14:49:15 -08001407 mFragments.dispatchConfigurationChanged(newConfig);
1408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 if (mWindow != null) {
1410 // Pass the configuration changed event to the window
1411 mWindow.onConfigurationChanged(newConfig);
1412 }
1413 }
1414
1415 /**
1416 * If this activity is being destroyed because it can not handle a
1417 * configuration parameter being changed (and thus its
1418 * {@link #onConfigurationChanged(Configuration)} method is
1419 * <em>not</em> being called), then you can use this method to discover
1420 * the set of changes that have occurred while in the process of being
1421 * destroyed. Note that there is no guarantee that these will be
1422 * accurate (other changes could have happened at any time), so you should
1423 * only use this as an optimization hint.
1424 *
1425 * @return Returns a bit field of the configuration parameters that are
1426 * changing, as defined by the {@link android.content.res.Configuration}
1427 * class.
1428 */
1429 public int getChangingConfigurations() {
1430 return mConfigChangeFlags;
1431 }
1432
1433 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07001434 * @deprecated Use the new {@link Fragment} API
1435 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1436 * available on older platforms through the Android compatibility package.
1437 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 * Retrieve the non-configuration instance data that was previously
1439 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1440 * be available from the initial {@link #onCreate} and
1441 * {@link #onStart} calls to the new instance, allowing you to extract
1442 * any useful dynamic state from the previous instance.
1443 *
1444 * <p>Note that the data you retrieve here should <em>only</em> be used
1445 * as an optimization for handling configuration changes. You should always
1446 * be able to handle getting a null pointer back, and an activity must
1447 * still be able to restore itself to its previous state (through the
1448 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1449 * function returns null.
1450 *
1451 * @return Returns the object previously returned by
1452 * {@link #onRetainNonConfigurationInstance()}.
1453 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07001454 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001456 return mLastNonConfigurationInstances != null
1457 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459
1460 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07001461 * @deprecated Use the new {@link Fragment} API
1462 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
1463 * available on older platforms through the Android compatibility package.
1464 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 * Called by the system, as part of destroying an
1466 * activity due to a configuration change, when it is known that a new
1467 * instance will immediately be created for the new configuration. You
1468 * can return any object you like here, including the activity instance
1469 * itself, which can later be retrieved by calling
1470 * {@link #getLastNonConfigurationInstance()} in the new activity
1471 * instance.
1472 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001473 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1474 * or later, consider instead using a {@link Fragment} with
1475 * {@link Fragment#setRetainInstance(boolean)
1476 * Fragment.setRetainInstance(boolean}.</em>
1477 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 * <p>This function is called purely as an optimization, and you must
1479 * not rely on it being called. When it is called, a number of guarantees
1480 * will be made to help optimize configuration switching:
1481 * <ul>
1482 * <li> The function will be called between {@link #onStop} and
1483 * {@link #onDestroy}.
1484 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001485 * created after this one's {@link #onDestroy()} is called. In particular,
1486 * <em>no</em> messages will be dispatched during this time (when the returned
1487 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 * <li> The object you return here will <em>always</em> be available from
1489 * the {@link #getLastNonConfigurationInstance()} method of the following
1490 * activity instance as described there.
1491 * </ul>
1492 *
1493 * <p>These guarantees are designed so that an activity can use this API
1494 * to propagate extensive state from the old to new activity instance, from
1495 * loaded bitmaps, to network connections, to evenly actively running
1496 * threads. Note that you should <em>not</em> propagate any data that
1497 * may change based on the configuration, including any data loaded from
1498 * resources such as strings, layouts, or drawables.
1499 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001500 * <p>The guarantee of no message handling during the switch to the next
1501 * activity simplifies use with active objects. For example if your retained
1502 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1503 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1504 * not be called from the call here until you execute the next instance's
1505 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1506 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1507 * running in a separate thread.)
1508 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 * @return Return any Object holding the desired state to propagate to the
1510 * next activity instance.
1511 */
1512 public Object onRetainNonConfigurationInstance() {
1513 return null;
1514 }
1515
1516 /**
1517 * Retrieve the non-configuration instance data that was previously
1518 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1519 * be available from the initial {@link #onCreate} and
1520 * {@link #onStart} calls to the new instance, allowing you to extract
1521 * any useful dynamic state from the previous instance.
1522 *
1523 * <p>Note that the data you retrieve here should <em>only</em> be used
1524 * as an optimization for handling configuration changes. You should always
1525 * be able to handle getting a null pointer back, and an activity must
1526 * still be able to restore itself to its previous state (through the
1527 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1528 * function returns null.
1529 *
1530 * @return Returns the object previously returned by
1531 * {@link #onRetainNonConfigurationChildInstances()}
1532 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001533 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1534 return mLastNonConfigurationInstances != null
1535 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537
1538 /**
1539 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1540 * it should return either a mapping from child activity id strings to arbitrary objects,
1541 * or null. This method is intended to be used by Activity framework subclasses that control a
1542 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1543 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1544 */
1545 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1546 return null;
1547 }
1548
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001549 NonConfigurationInstances retainNonConfigurationInstances() {
1550 Object activity = onRetainNonConfigurationInstance();
1551 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1552 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001553 boolean retainLoaders = false;
1554 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001555 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001556 // have nothing useful to retain.
1557 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001558 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001559 if (lm.mRetaining) {
1560 retainLoaders = true;
1561 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001562 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001563 mAllLoaderManagers.removeAt(i);
1564 }
1565 }
1566 }
1567 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001568 return null;
1569 }
1570
1571 NonConfigurationInstances nci = new NonConfigurationInstances();
1572 nci.activity = activity;
1573 nci.children = children;
1574 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001575 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001576 return nci;
1577 }
1578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public void onLowMemory() {
1580 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001581 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
1584 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001585 * Return the FragmentManager for interacting with fragments associated
1586 * with this activity.
1587 */
1588 public FragmentManager getFragmentManager() {
1589 return mFragments;
1590 }
1591
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001592 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001593 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001594 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001595 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornd04ad542011-07-25 16:16:15 -07001596 if (lm != null && !lm.mRetaining) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001597 lm.doDestroy();
Dianne Hackbornd04ad542011-07-25 16:16:15 -07001598 mAllLoaderManagers.remove(index);
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001599 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001600 }
1601 }
1602
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001603 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001604 * Called when a Fragment is being attached to this activity, immediately
1605 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1606 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1607 */
1608 public void onAttachFragment(Fragment fragment) {
1609 }
1610
1611 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 * Wrapper around
1613 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1614 * that gives the resulting {@link Cursor} to call
1615 * {@link #startManagingCursor} so that the activity will manage its
1616 * lifecycle for you.
1617 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001618 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1619 * or later, consider instead using {@link LoaderManager} instead, available
1620 * via {@link #getLoaderManager()}.</em>
1621 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 * @param uri The URI of the content provider to query.
1623 * @param projection List of columns to return.
1624 * @param selection SQL WHERE clause.
1625 * @param sortOrder SQL ORDER BY clause.
1626 *
1627 * @return The Cursor that was returned by query().
1628 *
1629 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1630 * @see #startManagingCursor
1631 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001632 *
1633 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 */
Jason parks6ed50de2010-08-25 10:18:50 -05001635 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001636 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1637 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1639 if (c != null) {
1640 startManagingCursor(c);
1641 }
1642 return c;
1643 }
1644
1645 /**
1646 * Wrapper around
1647 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1648 * that gives the resulting {@link Cursor} to call
1649 * {@link #startManagingCursor} so that the activity will manage its
1650 * lifecycle for you.
1651 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001652 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1653 * or later, consider instead using {@link LoaderManager} instead, available
1654 * via {@link #getLoaderManager()}.</em>
1655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 * @param uri The URI of the content provider to query.
1657 * @param projection List of columns to return.
1658 * @param selection SQL WHERE clause.
1659 * @param selectionArgs The arguments to selection, if any ?s are pesent
1660 * @param sortOrder SQL ORDER BY clause.
1661 *
1662 * @return The Cursor that was returned by query().
1663 *
1664 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1665 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001666 *
1667 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 */
Jason parks6ed50de2010-08-25 10:18:50 -05001669 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001670 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1671 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1673 if (c != null) {
1674 startManagingCursor(c);
1675 }
1676 return c;
1677 }
1678
1679 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07001680 * @deprecated Use the new {@link android.content.CursorLoader} class with
1681 * {@link LoaderManager} instead; this is also
1682 * available on older platforms through the Android compatibility package.
1683 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 * This method allows the activity to take care of managing the given
1685 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1686 * That is, when the activity is stopped it will automatically call
1687 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1688 * it will call {@link Cursor#requery} for you. When the activity is
1689 * destroyed, all managed Cursors will be closed automatically.
1690 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001691 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1692 * or later, consider instead using {@link LoaderManager} instead, available
1693 * via {@link #getLoaderManager()}.</em>
1694 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 * @param c The Cursor to be managed.
1696 *
1697 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1698 * @see #stopManagingCursor
1699 */
Jason parks6ed50de2010-08-25 10:18:50 -05001700 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 public void startManagingCursor(Cursor c) {
1702 synchronized (mManagedCursors) {
1703 mManagedCursors.add(new ManagedCursor(c));
1704 }
1705 }
1706
1707 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07001708 * @deprecated Use the new {@link android.content.CursorLoader} class with
1709 * {@link LoaderManager} instead; this is also
1710 * available on older platforms through the Android compatibility package.
1711 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 * Given a Cursor that was previously given to
1713 * {@link #startManagingCursor}, stop the activity's management of that
1714 * cursor.
1715 *
1716 * @param c The Cursor that was being managed.
1717 *
1718 * @see #startManagingCursor
1719 */
Jason parks6ed50de2010-08-25 10:18:50 -05001720 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 public void stopManagingCursor(Cursor c) {
1722 synchronized (mManagedCursors) {
1723 final int N = mManagedCursors.size();
1724 for (int i=0; i<N; i++) {
1725 ManagedCursor mc = mManagedCursors.get(i);
1726 if (mc.mCursor == c) {
1727 mManagedCursors.remove(i);
1728 break;
1729 }
1730 }
1731 }
1732 }
1733
1734 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001735 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1736 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001737 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001739 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
1742
1743 /**
1744 * Finds a view that was identified by the id attribute from the XML that
1745 * was processed in {@link #onCreate}.
1746 *
1747 * @return The view if found or null otherwise.
1748 */
1749 public View findViewById(int id) {
1750 return getWindow().findViewById(id);
1751 }
Adam Powell33b97432010-04-20 10:01:14 -07001752
1753 /**
1754 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001755 *
Adam Powell33b97432010-04-20 10:01:14 -07001756 * @return The Activity's ActionBar, or null if it does not have one.
1757 */
1758 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001759 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001760 return mActionBar;
1761 }
1762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 /**
Adam Powell33b97432010-04-20 10:01:14 -07001764 * Creates a new ActionBar, locates the inflated ActionBarView,
1765 * initializes the ActionBar with the view, and sets mActionBar.
1766 */
1767 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001768 Window window = getWindow();
Adam Powella593d982011-05-13 14:09:54 -07001769
1770 // Initializing the window decor can change window feature flags.
1771 // Make sure that we have the correct set before performing the test below.
1772 window.getDecorView();
1773
Adam Powell9b4c8042010-08-10 15:36:44 -07001774 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001775 return;
1776 }
1777
Adam Powell661c9082010-07-02 10:09:44 -07001778 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001779 }
1780
1781 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 * Set the activity content from a layout resource. The resource will be
1783 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08001784 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a62011-01-20 10:59:28 -08001786 *
1787 * @see #setContentView(android.view.View)
1788 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 */
1790 public void setContentView(int layoutResID) {
1791 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001792 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794
1795 /**
1796 * Set the activity content to an explicit view. This view is placed
1797 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001798 * view hierarchy. When calling this method, the layout parameters of the
1799 * specified view are ignored. Both the width and the height of the view are
1800 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1801 * your own layout parameters, invoke
1802 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1803 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 *
1805 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08001806 *
1807 * @see #setContentView(int)
1808 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 */
1810 public void setContentView(View view) {
1811 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001812 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
1814
1815 /**
1816 * Set the activity content to an explicit view. This view is placed
1817 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001818 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 *
1820 * @param view The desired content to display.
1821 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08001822 *
1823 * @see #setContentView(android.view.View)
1824 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 */
1826 public void setContentView(View view, ViewGroup.LayoutParams params) {
1827 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001828 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830
1831 /**
1832 * Add an additional content view to the activity. Added after any existing
1833 * ones in the activity -- existing views are NOT removed.
1834 *
1835 * @param view The desired content to display.
1836 * @param params Layout parameters for the view.
1837 */
1838 public void addContentView(View view, ViewGroup.LayoutParams params) {
1839 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001840 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842
1843 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001844 * Sets whether this activity is finished when touched outside its window's
1845 * bounds.
1846 */
1847 public void setFinishOnTouchOutside(boolean finish) {
1848 mWindow.setCloseOnTouchOutside(finish);
1849 }
1850
1851 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1853 * keys.
1854 *
1855 * @see #setDefaultKeyMode
1856 */
1857 static public final int DEFAULT_KEYS_DISABLE = 0;
1858 /**
1859 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1860 * key handling.
1861 *
1862 * @see #setDefaultKeyMode
1863 */
1864 static public final int DEFAULT_KEYS_DIALER = 1;
1865 /**
1866 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1867 * default key handling.
1868 *
1869 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1870 *
1871 * @see #setDefaultKeyMode
1872 */
1873 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1874 /**
1875 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1876 * will start an application-defined search. (If the application or activity does not
1877 * actually define a search, the the keys will be ignored.)
1878 *
1879 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1880 *
1881 * @see #setDefaultKeyMode
1882 */
1883 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1884
1885 /**
1886 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1887 * will start a global search (typically web search, but some platforms may define alternate
1888 * methods for global search)
1889 *
1890 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1891 *
1892 * @see #setDefaultKeyMode
1893 */
1894 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1895
1896 /**
1897 * Select the default key handling for this activity. This controls what
1898 * will happen to key events that are not otherwise handled. The default
1899 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1900 * floor. Other modes allow you to launch the dialer
1901 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1902 * menu without requiring the menu key be held down
1903 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1904 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1905 *
1906 * <p>Note that the mode selected here does not impact the default
1907 * handling of system keys, such as the "back" and "menu" keys, and your
1908 * activity and its views always get a first chance to receive and handle
1909 * all application keys.
1910 *
1911 * @param mode The desired default key mode constant.
1912 *
1913 * @see #DEFAULT_KEYS_DISABLE
1914 * @see #DEFAULT_KEYS_DIALER
1915 * @see #DEFAULT_KEYS_SHORTCUT
1916 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1917 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1918 * @see #onKeyDown
1919 */
1920 public final void setDefaultKeyMode(int mode) {
1921 mDefaultKeyMode = mode;
1922
1923 // Some modes use a SpannableStringBuilder to track & dispatch input events
1924 // This list must remain in sync with the switch in onKeyDown()
1925 switch (mode) {
1926 case DEFAULT_KEYS_DISABLE:
1927 case DEFAULT_KEYS_SHORTCUT:
1928 mDefaultKeySsb = null; // not used in these modes
1929 break;
1930 case DEFAULT_KEYS_DIALER:
1931 case DEFAULT_KEYS_SEARCH_LOCAL:
1932 case DEFAULT_KEYS_SEARCH_GLOBAL:
1933 mDefaultKeySsb = new SpannableStringBuilder();
1934 Selection.setSelection(mDefaultKeySsb,0);
1935 break;
1936 default:
1937 throw new IllegalArgumentException();
1938 }
1939 }
1940
1941 /**
1942 * Called when a key was pressed down and not handled by any of the views
1943 * inside of the activity. So, for example, key presses while the cursor
1944 * is inside a TextView will not trigger the event (unless it is a navigation
1945 * to another object) because TextView handles its own key presses.
1946 *
1947 * <p>If the focused view didn't want this event, this method is called.
1948 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001949 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1950 * by calling {@link #onBackPressed()}, though the behavior varies based
1951 * on the application compatibility mode: for
1952 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1953 * it will set up the dispatch to call {@link #onKeyUp} where the action
1954 * will be performed; for earlier applications, it will perform the
1955 * action immediately in on-down, as those versions of the platform
1956 * behaved.
1957 *
1958 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001959 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 *
1961 * @return Return <code>true</code> to prevent this event from being propagated
1962 * further, or <code>false</code> to indicate that you have not handled
1963 * this event and it should continue to be propagated.
1964 * @see #onKeyUp
1965 * @see android.view.KeyEvent
1966 */
1967 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001968 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001969 if (getApplicationInfo().targetSdkVersion
1970 >= Build.VERSION_CODES.ECLAIR) {
1971 event.startTracking();
1972 } else {
1973 onBackPressed();
1974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 return true;
1976 }
1977
1978 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1979 return false;
1980 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001981 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1982 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1983 return true;
1984 }
1985 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 } else {
1987 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1988 boolean clearSpannable = false;
1989 boolean handled;
1990 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1991 clearSpannable = true;
1992 handled = false;
1993 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001994 handled = TextKeyListener.getInstance().onKeyDown(
1995 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 if (handled && mDefaultKeySsb.length() > 0) {
1997 // something useable has been typed - dispatch it now.
1998
1999 final String str = mDefaultKeySsb.toString();
2000 clearSpannable = true;
2001
2002 switch (mDefaultKeyMode) {
2003 case DEFAULT_KEYS_DIALER:
2004 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2005 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2006 startActivity(intent);
2007 break;
2008 case DEFAULT_KEYS_SEARCH_LOCAL:
2009 startSearch(str, false, null, false);
2010 break;
2011 case DEFAULT_KEYS_SEARCH_GLOBAL:
2012 startSearch(str, false, null, true);
2013 break;
2014 }
2015 }
2016 }
2017 if (clearSpannable) {
2018 mDefaultKeySsb.clear();
2019 mDefaultKeySsb.clearSpans();
2020 Selection.setSelection(mDefaultKeySsb,0);
2021 }
2022 return handled;
2023 }
2024 }
2025
2026 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002027 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2028 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2029 * the event).
2030 */
2031 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2032 return false;
2033 }
2034
2035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 * Called when a key was released and not handled by any of the views
2037 * inside of the activity. So, for example, key presses while the cursor
2038 * is inside a TextView will not trigger the event (unless it is a navigation
2039 * to another object) because TextView handles its own key presses.
2040 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002041 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2042 * and go back.
2043 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 * @return Return <code>true</code> to prevent this event from being propagated
2045 * further, or <code>false</code> to indicate that you have not handled
2046 * this event and it should continue to be propagated.
2047 * @see #onKeyDown
2048 * @see KeyEvent
2049 */
2050 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002051 if (getApplicationInfo().targetSdkVersion
2052 >= Build.VERSION_CODES.ECLAIR) {
2053 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2054 && !event.isCanceled()) {
2055 onBackPressed();
2056 return true;
2057 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 return false;
2060 }
2061
2062 /**
2063 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2064 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2065 * the event).
2066 */
2067 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2068 return false;
2069 }
2070
2071 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002072 * Called when the activity has detected the user's press of the back
2073 * key. The default implementation simply finishes the current activity,
2074 * but you can override this to do whatever you want.
2075 */
2076 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002077 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002078 finish();
2079 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002080 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002081
2082 /**
2083 * Called when a key shortcut event is not handled by any of the views in the Activity.
2084 * Override this method to implement global key shortcuts for the Activity.
2085 * Key shortcuts can also be implemented by setting the
2086 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2087 *
2088 * @param keyCode The value in event.getKeyCode().
2089 * @param event Description of the key event.
2090 * @return True if the key shortcut was handled.
2091 */
2092 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2093 return false;
2094 }
2095
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002096 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 * Called when a touch screen event was not handled by any of the views
2098 * under it. This is most useful to process touch events that happen
2099 * outside of your window bounds, where there is no view to receive it.
2100 *
2101 * @param event The touch screen event being processed.
2102 *
2103 * @return Return true if you have consumed the event, false if you haven't.
2104 * The default implementation always returns false.
2105 */
2106 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002107 if (mWindow.shouldCloseOnTouch(this, event)) {
2108 finish();
2109 return true;
2110 }
2111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 return false;
2113 }
2114
2115 /**
2116 * Called when the trackball was moved and not handled by any of the
2117 * views inside of the activity. So, for example, if the trackball moves
2118 * while focus is on a button, you will receive a call here because
2119 * buttons do not normally do anything with trackball events. The call
2120 * here happens <em>before</em> trackball movements are converted to
2121 * DPAD key events, which then get sent back to the view hierarchy, and
2122 * will be processed at the point for things like focus navigation.
2123 *
2124 * @param event The trackball event being processed.
2125 *
2126 * @return Return true if you have consumed the event, false if you haven't.
2127 * The default implementation always returns false.
2128 */
2129 public boolean onTrackballEvent(MotionEvent event) {
2130 return false;
2131 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002132
2133 /**
2134 * Called when a generic motion event was not handled by any of the
2135 * views inside of the activity.
2136 * <p>
Jeff Brown33bbfd22011-02-24 20:55:35 -08002137 * Generic motion events describe joystick movements, mouse hovers, track pad
2138 * touches, scroll wheel movements and other input events. The
Jeff Browncb1404e2011-01-15 18:14:15 -08002139 * {@link MotionEvent#getSource() source} of the motion event specifies
2140 * the class of input that was received. Implementations of this method
2141 * must examine the bits in the source before processing the event.
2142 * The following code example shows how this is done.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002143 * </p><p>
2144 * Generic motion events with source class
2145 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2146 * are delivered to the view under the pointer. All other generic motion events are
2147 * delivered to the focused view.
2148 * </p><p>
2149 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2150 * handle this event.
Jeff Browncb1404e2011-01-15 18:14:15 -08002151 * </p>
Jeff Browncb1404e2011-01-15 18:14:15 -08002152 *
2153 * @param event The generic motion event being processed.
2154 *
2155 * @return Return true if you have consumed the event, false if you haven't.
2156 * The default implementation always returns false.
2157 */
2158 public boolean onGenericMotionEvent(MotionEvent event) {
2159 return false;
2160 }
2161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 /**
2163 * Called whenever a key, touch, or trackball event is dispatched to the
2164 * activity. Implement this method if you wish to know that the user has
2165 * interacted with the device in some way while your activity is running.
2166 * This callback and {@link #onUserLeaveHint} are intended to help
2167 * activities manage status bar notifications intelligently; specifically,
2168 * for helping activities determine the proper time to cancel a notfication.
2169 *
2170 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2171 * be accompanied by calls to {@link #onUserInteraction}. This
2172 * ensures that your activity will be told of relevant user activity such
2173 * as pulling down the notification pane and touching an item there.
2174 *
2175 * <p>Note that this callback will be invoked for the touch down action
2176 * that begins a touch gesture, but may not be invoked for the touch-moved
2177 * and touch-up actions that follow.
2178 *
2179 * @see #onUserLeaveHint()
2180 */
2181 public void onUserInteraction() {
2182 }
2183
2184 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2185 // Update window manager if: we have a view, that view is
2186 // attached to its parent (which will be a RootView), and
2187 // this activity is not embedded.
2188 if (mParent == null) {
2189 View decor = mDecor;
2190 if (decor != null && decor.getParent() != null) {
2191 getWindowManager().updateViewLayout(decor, params);
2192 }
2193 }
2194 }
2195
2196 public void onContentChanged() {
2197 }
2198
2199 /**
2200 * Called when the current {@link Window} of the activity gains or loses
2201 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002202 * to the user. The default implementation clears the key tracking
2203 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002205 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 * is managed independently of activity lifecycles. As such, while focus
2207 * changes will generally have some relation to lifecycle changes (an
2208 * activity that is stopped will not generally get window focus), you
2209 * should not rely on any particular order between the callbacks here and
2210 * those in the other lifecycle methods such as {@link #onResume}.
2211 *
2212 * <p>As a general rule, however, a resumed activity will have window
2213 * focus... unless it has displayed other dialogs or popups that take
2214 * input focus, in which case the activity itself will not have focus
2215 * when the other windows have it. Likewise, the system may display
2216 * system-level windows (such as the status bar notification panel or
2217 * a system alert) which will temporarily take window input focus without
2218 * pausing the foreground activity.
2219 *
2220 * @param hasFocus Whether the window of this activity has focus.
2221 *
2222 * @see #hasWindowFocus()
2223 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002224 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 */
2226 public void onWindowFocusChanged(boolean hasFocus) {
2227 }
2228
2229 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002230 * Called when the main window associated with the activity has been
2231 * attached to the window manager.
2232 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2233 * for more information.
2234 * @see View#onAttachedToWindow
2235 */
2236 public void onAttachedToWindow() {
2237 }
2238
2239 /**
2240 * Called when the main window associated with the activity has been
2241 * detached from the window manager.
2242 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2243 * for more information.
2244 * @see View#onDetachedFromWindow
2245 */
2246 public void onDetachedFromWindow() {
2247 }
2248
2249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 * Returns true if this activity's <em>main</em> window currently has window focus.
2251 * Note that this is not the same as the view itself having focus.
2252 *
2253 * @return True if this activity's main window currently has window focus.
2254 *
2255 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2256 */
2257 public boolean hasWindowFocus() {
2258 Window w = getWindow();
2259 if (w != null) {
2260 View d = w.getDecorView();
2261 if (d != null) {
2262 return d.hasWindowFocus();
2263 }
2264 }
2265 return false;
2266 }
2267
2268 /**
2269 * Called to process key events. You can override this to intercept all
2270 * key events before they are dispatched to the window. Be sure to call
2271 * this implementation for key events that should be handled normally.
2272 *
2273 * @param event The key event.
2274 *
2275 * @return boolean Return true if this event was consumed.
2276 */
2277 public boolean dispatchKeyEvent(KeyEvent event) {
2278 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002279 Window win = getWindow();
2280 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 return true;
2282 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002283 View decor = mDecor;
2284 if (decor == null) decor = win.getDecorView();
2285 return event.dispatch(this, decor != null
2286 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
2288
2289 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002290 * Called to process a key shortcut event.
2291 * You can override this to intercept all key shortcut events before they are
2292 * dispatched to the window. Be sure to call this implementation for key shortcut
2293 * events that should be handled normally.
2294 *
2295 * @param event The key shortcut event.
2296 * @return True if this event was consumed.
2297 */
2298 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2299 onUserInteraction();
2300 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2301 return true;
2302 }
2303 return onKeyShortcut(event.getKeyCode(), event);
2304 }
2305
2306 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 * Called to process touch screen events. You can override this to
2308 * intercept all touch screen events before they are dispatched to the
2309 * window. Be sure to call this implementation for touch screen events
2310 * that should be handled normally.
2311 *
2312 * @param ev The touch screen event.
2313 *
2314 * @return boolean Return true if this event was consumed.
2315 */
2316 public boolean dispatchTouchEvent(MotionEvent ev) {
2317 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2318 onUserInteraction();
2319 }
2320 if (getWindow().superDispatchTouchEvent(ev)) {
2321 return true;
2322 }
2323 return onTouchEvent(ev);
2324 }
2325
2326 /**
2327 * Called to process trackball events. You can override this to
2328 * intercept all trackball events before they are dispatched to the
2329 * window. Be sure to call this implementation for trackball events
2330 * that should be handled normally.
2331 *
2332 * @param ev The trackball event.
2333 *
2334 * @return boolean Return true if this event was consumed.
2335 */
2336 public boolean dispatchTrackballEvent(MotionEvent ev) {
2337 onUserInteraction();
2338 if (getWindow().superDispatchTrackballEvent(ev)) {
2339 return true;
2340 }
2341 return onTrackballEvent(ev);
2342 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002343
Jeff Browncb1404e2011-01-15 18:14:15 -08002344 /**
2345 * Called to process generic motion events. You can override this to
2346 * intercept all generic motion events before they are dispatched to the
2347 * window. Be sure to call this implementation for generic motion events
2348 * that should be handled normally.
2349 *
2350 * @param ev The generic motion event.
2351 *
2352 * @return boolean Return true if this event was consumed.
2353 */
2354 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2355 onUserInteraction();
2356 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2357 return true;
2358 }
2359 return onGenericMotionEvent(ev);
2360 }
2361
svetoslavganov75986cf2009-05-14 22:28:01 -07002362 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2363 event.setClassName(getClass().getName());
2364 event.setPackageName(getPackageName());
2365
2366 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002367 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2368 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002369 event.setFullScreen(isFullScreen);
2370
2371 CharSequence title = getTitle();
2372 if (!TextUtils.isEmpty(title)) {
2373 event.getText().add(title);
2374 }
2375
2376 return true;
2377 }
2378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 /**
2380 * Default implementation of
2381 * {@link android.view.Window.Callback#onCreatePanelView}
2382 * for activities. This
2383 * simply returns null so that all panel sub-windows will have the default
2384 * menu behavior.
2385 */
2386 public View onCreatePanelView(int featureId) {
2387 return null;
2388 }
2389
2390 /**
2391 * Default implementation of
2392 * {@link android.view.Window.Callback#onCreatePanelMenu}
2393 * for activities. This calls through to the new
2394 * {@link #onCreateOptionsMenu} method for the
2395 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2396 * so that subclasses of Activity don't need to deal with feature codes.
2397 */
2398 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2399 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002400 boolean show = onCreateOptionsMenu(menu);
2401 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2402 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404 return false;
2405 }
2406
2407 /**
2408 * Default implementation of
2409 * {@link android.view.Window.Callback#onPreparePanel}
2410 * for activities. This
2411 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2412 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2413 * panel, so that subclasses of
2414 * Activity don't need to deal with feature codes.
2415 */
2416 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2417 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2418 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002419 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 return goforit && menu.hasVisibleItems();
2421 }
2422 return true;
2423 }
2424
2425 /**
2426 * {@inheritDoc}
2427 *
2428 * @return The default implementation returns true.
2429 */
2430 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002431 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell763cbb12011-03-01 10:45:34 -08002432 initActionBar();
Adam Powell049dd3d2010-12-02 13:43:59 -08002433 if (mActionBar != null) {
2434 mActionBar.dispatchMenuVisibilityChanged(true);
2435 } else {
2436 Log.e(TAG, "Tried to open action bar menu with no action bar");
2437 }
Adam Powell8515ee82010-11-30 14:09:55 -08002438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 return true;
2440 }
2441
2442 /**
2443 * Default implementation of
2444 * {@link android.view.Window.Callback#onMenuItemSelected}
2445 * for activities. This calls through to the new
2446 * {@link #onOptionsItemSelected} method for the
2447 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2448 * panel, so that subclasses of
2449 * Activity don't need to deal with feature codes.
2450 */
2451 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2452 switch (featureId) {
2453 case Window.FEATURE_OPTIONS_PANEL:
2454 // Put event logging here so it gets called even if subclass
2455 // doesn't call through to superclass's implmeentation of each
2456 // of these methods below
2457 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002458 if (onOptionsItemSelected(item)) {
2459 return true;
2460 }
2461 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462
2463 case Window.FEATURE_CONTEXT_MENU:
2464 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002465 if (onContextItemSelected(item)) {
2466 return true;
2467 }
2468 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 default:
2471 return false;
2472 }
2473 }
2474
2475 /**
2476 * Default implementation of
2477 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2478 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2479 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2480 * so that subclasses of Activity don't need to deal with feature codes.
2481 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2482 * {@link #onContextMenuClosed(Menu)} will be called.
2483 */
2484 public void onPanelClosed(int featureId, Menu menu) {
2485 switch (featureId) {
2486 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002487 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 onOptionsMenuClosed(menu);
2489 break;
2490
2491 case Window.FEATURE_CONTEXT_MENU:
2492 onContextMenuClosed(menu);
2493 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002494
2495 case Window.FEATURE_ACTION_BAR:
Adam Powell9b4bee02011-04-27 19:24:47 -07002496 initActionBar();
Adam Powell8515ee82010-11-30 14:09:55 -08002497 mActionBar.dispatchMenuVisibilityChanged(false);
2498 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500 }
2501
2502 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002503 * Declare that the options menu has changed, so should be recreated.
2504 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2505 * time it needs to be displayed.
2506 */
2507 public void invalidateOptionsMenu() {
2508 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2509 }
2510
2511 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 * Initialize the contents of the Activity's standard options menu. You
2513 * should place your menu items in to <var>menu</var>.
2514 *
2515 * <p>This is only called once, the first time the options menu is
2516 * displayed. To update the menu every time it is displayed, see
2517 * {@link #onPrepareOptionsMenu}.
2518 *
2519 * <p>The default implementation populates the menu with standard system
2520 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2521 * they will be correctly ordered with application-defined menu items.
2522 * Deriving classes should always call through to the base implementation.
2523 *
2524 * <p>You can safely hold on to <var>menu</var> (and any items created
2525 * from it), making modifications to it as desired, until the next
2526 * time onCreateOptionsMenu() is called.
2527 *
2528 * <p>When you add items to the menu, you can implement the Activity's
2529 * {@link #onOptionsItemSelected} method to handle them there.
2530 *
2531 * @param menu The options menu in which you place your items.
2532 *
2533 * @return You must return true for the menu to be displayed;
2534 * if you return false it will not be shown.
2535 *
2536 * @see #onPrepareOptionsMenu
2537 * @see #onOptionsItemSelected
2538 */
2539 public boolean onCreateOptionsMenu(Menu menu) {
2540 if (mParent != null) {
2541 return mParent.onCreateOptionsMenu(menu);
2542 }
2543 return true;
2544 }
2545
2546 /**
2547 * Prepare the Screen's standard options menu to be displayed. This is
2548 * called right before the menu is shown, every time it is shown. You can
2549 * use this method to efficiently enable/disable items or otherwise
2550 * dynamically modify the contents.
2551 *
2552 * <p>The default implementation updates the system menu items based on the
2553 * activity's state. Deriving classes should always call through to the
2554 * base class implementation.
2555 *
2556 * @param menu The options menu as last shown or first initialized by
2557 * onCreateOptionsMenu().
2558 *
2559 * @return You must return true for the menu to be displayed;
2560 * if you return false it will not be shown.
2561 *
2562 * @see #onCreateOptionsMenu
2563 */
2564 public boolean onPrepareOptionsMenu(Menu menu) {
2565 if (mParent != null) {
2566 return mParent.onPrepareOptionsMenu(menu);
2567 }
2568 return true;
2569 }
2570
2571 /**
2572 * This hook is called whenever an item in your options menu is selected.
2573 * The default implementation simply returns false to have the normal
2574 * processing happen (calling the item's Runnable or sending a message to
2575 * its Handler as appropriate). You can use this method for any items
2576 * for which you would like to do processing without those other
2577 * facilities.
2578 *
2579 * <p>Derived classes should call through to the base class for it to
2580 * perform the default menu handling.
2581 *
2582 * @param item The menu item that was selected.
2583 *
2584 * @return boolean Return false to allow normal menu processing to
2585 * proceed, true to consume it here.
2586 *
2587 * @see #onCreateOptionsMenu
2588 */
2589 public boolean onOptionsItemSelected(MenuItem item) {
2590 if (mParent != null) {
2591 return mParent.onOptionsItemSelected(item);
2592 }
2593 return false;
2594 }
2595
2596 /**
2597 * This hook is called whenever the options menu is being closed (either by the user canceling
2598 * the menu with the back/menu button, or when an item is selected).
2599 *
2600 * @param menu The options menu as last shown or first initialized by
2601 * onCreateOptionsMenu().
2602 */
2603 public void onOptionsMenuClosed(Menu menu) {
2604 if (mParent != null) {
2605 mParent.onOptionsMenuClosed(menu);
2606 }
2607 }
2608
2609 /**
2610 * Programmatically opens the options menu. If the options menu is already
2611 * open, this method does nothing.
2612 */
2613 public void openOptionsMenu() {
2614 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2615 }
2616
2617 /**
2618 * Progammatically closes the options menu. If the options menu is already
2619 * closed, this method does nothing.
2620 */
2621 public void closeOptionsMenu() {
2622 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2623 }
2624
2625 /**
2626 * Called when a context menu for the {@code view} is about to be shown.
2627 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2628 * time the context menu is about to be shown and should be populated for
2629 * the view (or item inside the view for {@link AdapterView} subclasses,
2630 * this can be found in the {@code menuInfo})).
2631 * <p>
2632 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2633 * item has been selected.
2634 * <p>
2635 * It is not safe to hold onto the context menu after this method returns.
2636 * {@inheritDoc}
2637 */
2638 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2639 }
2640
2641 /**
2642 * Registers a context menu to be shown for the given view (multiple views
2643 * can show the context menu). This method will set the
2644 * {@link OnCreateContextMenuListener} on the view to this activity, so
2645 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2646 * called when it is time to show the context menu.
2647 *
2648 * @see #unregisterForContextMenu(View)
2649 * @param view The view that should show a context menu.
2650 */
2651 public void registerForContextMenu(View view) {
2652 view.setOnCreateContextMenuListener(this);
2653 }
2654
2655 /**
2656 * Prevents a context menu to be shown for the given view. This method will remove the
2657 * {@link OnCreateContextMenuListener} on the view.
2658 *
2659 * @see #registerForContextMenu(View)
2660 * @param view The view that should stop showing a context menu.
2661 */
2662 public void unregisterForContextMenu(View view) {
2663 view.setOnCreateContextMenuListener(null);
2664 }
2665
2666 /**
2667 * Programmatically opens the context menu for a particular {@code view}.
2668 * The {@code view} should have been added via
2669 * {@link #registerForContextMenu(View)}.
2670 *
2671 * @param view The view to show the context menu for.
2672 */
2673 public void openContextMenu(View view) {
2674 view.showContextMenu();
2675 }
2676
2677 /**
2678 * Programmatically closes the most recently opened context menu, if showing.
2679 */
2680 public void closeContextMenu() {
2681 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2682 }
2683
2684 /**
2685 * This hook is called whenever an item in a context menu is selected. The
2686 * default implementation simply returns false to have the normal processing
2687 * happen (calling the item's Runnable or sending a message to its Handler
2688 * as appropriate). You can use this method for any items for which you
2689 * would like to do processing without those other facilities.
2690 * <p>
2691 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2692 * View that added this menu item.
2693 * <p>
2694 * Derived classes should call through to the base class for it to perform
2695 * the default menu handling.
2696 *
2697 * @param item The context menu item that was selected.
2698 * @return boolean Return false to allow normal context menu processing to
2699 * proceed, true to consume it here.
2700 */
2701 public boolean onContextItemSelected(MenuItem item) {
2702 if (mParent != null) {
2703 return mParent.onContextItemSelected(item);
2704 }
2705 return false;
2706 }
2707
2708 /**
2709 * This hook is called whenever the context menu is being closed (either by
2710 * the user canceling the menu with the back/menu button, or when an item is
2711 * selected).
2712 *
2713 * @param menu The context menu that is being closed.
2714 */
2715 public void onContextMenuClosed(Menu menu) {
2716 if (mParent != null) {
2717 mParent.onContextMenuClosed(menu);
2718 }
2719 }
2720
2721 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002722 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002724 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 protected Dialog onCreateDialog(int id) {
2726 return null;
2727 }
2728
2729 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002730 * @deprecated Use the new {@link DialogFragment} class with
2731 * {@link FragmentManager} instead; this is also
2732 * available on older platforms through the Android compatibility package.
2733 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002734 * Callback for creating dialogs that are managed (saved and restored) for you
2735 * by the activity. The default implementation calls through to
2736 * {@link #onCreateDialog(int)} for compatibility.
2737 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002738 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2739 * or later, consider instead using a {@link DialogFragment} instead.</em>
2740 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002741 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2742 * this method the first time, and hang onto it thereafter. Any dialog
2743 * that is created by this method will automatically be saved and restored
2744 * for you, including whether it is showing.
2745 *
2746 * <p>If you would like the activity to manage saving and restoring dialogs
2747 * for you, you should override this method and handle any ids that are
2748 * passed to {@link #showDialog}.
2749 *
2750 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2751 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2752 *
2753 * @param id The id of the dialog.
2754 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2755 * @return The dialog. If you return null, the dialog will not be created.
2756 *
2757 * @see #onPrepareDialog(int, Dialog, Bundle)
2758 * @see #showDialog(int, Bundle)
2759 * @see #dismissDialog(int)
2760 * @see #removeDialog(int)
2761 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002762 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002763 protected Dialog onCreateDialog(int id, Bundle args) {
2764 return onCreateDialog(id);
2765 }
2766
2767 /**
2768 * @deprecated Old no-arguments version of
2769 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2770 */
2771 @Deprecated
2772 protected void onPrepareDialog(int id, Dialog dialog) {
2773 dialog.setOwnerActivity(this);
2774 }
2775
2776 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002777 * @deprecated Use the new {@link DialogFragment} class with
2778 * {@link FragmentManager} instead; this is also
2779 * available on older platforms through the Android compatibility package.
2780 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002782 * shown. The default implementation calls through to
2783 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2784 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 * <p>
2786 * Override this if you need to update a managed dialog based on the state
2787 * of the application each time it is shown. For example, a time picker
2788 * dialog might want to be updated with the current time. You should call
2789 * through to the superclass's implementation. The default implementation
2790 * will set this Activity as the owner activity on the Dialog.
2791 *
2792 * @param id The id of the managed dialog.
2793 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002794 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2795 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 * @see #showDialog(int)
2797 * @see #dismissDialog(int)
2798 * @see #removeDialog(int)
2799 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002800 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002801 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2802 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 }
2804
2805 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002806 * @deprecated Use the new {@link DialogFragment} class with
2807 * {@link FragmentManager} instead; this is also
2808 * available on older platforms through the Android compatibility package.
2809 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002810 * Simple version of {@link #showDialog(int, Bundle)} that does not
2811 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2812 * with null arguments.
2813 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002814 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002815 public final void showDialog(int id) {
2816 showDialog(id, null);
2817 }
2818
2819 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002820 * @deprecated Use the new {@link DialogFragment} class with
2821 * {@link FragmentManager} instead; this is also
2822 * available on older platforms through the Android compatibility package.
2823 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002824 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 * will be made with the same id the first time this is called for a given
2826 * id. From thereafter, the dialog will be automatically saved and restored.
2827 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002828 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2829 * or later, consider instead using a {@link DialogFragment} instead.</em>
2830 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002831 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 * be made to provide an opportunity to do any timely preparation.
2833 *
2834 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002835 * @param args Arguments to pass through to the dialog. These will be saved
2836 * and restored for you. Note that if the dialog is already created,
2837 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2838 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002839 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002840 * @return Returns true if the Dialog was created; false is returned if
2841 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2842 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002843 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002844 * @see #onCreateDialog(int, Bundle)
2845 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 * @see #dismissDialog(int)
2847 * @see #removeDialog(int)
2848 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002849 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002850 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002852 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002854 ManagedDialog md = mManagedDialogs.get(id);
2855 if (md == null) {
2856 md = new ManagedDialog();
2857 md.mDialog = createDialog(id, null, args);
2858 if (md.mDialog == null) {
2859 return false;
2860 }
2861 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
2863
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002864 md.mArgs = args;
2865 onPrepareDialog(id, md.mDialog, args);
2866 md.mDialog.show();
2867 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 }
2869
2870 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002871 * @deprecated Use the new {@link DialogFragment} class with
2872 * {@link FragmentManager} instead; this is also
2873 * available on older platforms through the Android compatibility package.
2874 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2876 *
2877 * @param id The id of the managed dialog.
2878 *
2879 * @throws IllegalArgumentException if the id was not previously shown via
2880 * {@link #showDialog(int)}.
2881 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002882 * @see #onCreateDialog(int, Bundle)
2883 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 * @see #showDialog(int)
2885 * @see #removeDialog(int)
2886 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002887 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 public final void dismissDialog(int id) {
2889 if (mManagedDialogs == null) {
2890 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002892
2893 final ManagedDialog md = mManagedDialogs.get(id);
2894 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 throw missingDialog(id);
2896 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002897 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 }
2899
2900 /**
2901 * Creates an exception to throw if a user passed in a dialog id that is
2902 * unexpected.
2903 */
2904 private IllegalArgumentException missingDialog(int id) {
2905 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2906 + "shown via Activity#showDialog");
2907 }
2908
2909 /**
Dianne Hackborn9567a662011-04-19 18:44:03 -07002910 * @deprecated Use the new {@link DialogFragment} class with
2911 * {@link FragmentManager} instead; this is also
2912 * available on older platforms through the Android compatibility package.
2913 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 * Removes any internal references to a dialog managed by this Activity.
2915 * If the dialog is showing, it will dismiss it as part of the clean up.
2916 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002917 * <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 -08002918 * want to avoid the overhead of saving and restoring it in the future.
2919 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002920 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2921 * will not throw an exception if you try to remove an ID that does not
2922 * currently have an associated dialog.</p>
2923 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 * @param id The id of the managed dialog.
2925 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002926 * @see #onCreateDialog(int, Bundle)
2927 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 * @see #showDialog(int)
2929 * @see #dismissDialog(int)
2930 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07002931 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002933 if (mManagedDialogs != null) {
2934 final ManagedDialog md = mManagedDialogs.get(id);
2935 if (md != null) {
2936 md.mDialog.dismiss();
2937 mManagedDialogs.remove(id);
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941
2942 /**
2943 * This hook is called when the user signals the desire to start a search.
2944 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002945 * <p>You can use this function as a simple way to launch the search UI, in response to a
2946 * menu item, search button, or other widgets within your activity. Unless overidden,
2947 * calling this function is the same as calling
2948 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2949 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 *
2951 * <p>You can override this function to force global search, e.g. in response to a dedicated
2952 * search key, or to block search entirely (by simply returning false).
2953 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002954 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2955 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 *
2957 * @see android.app.SearchManager
2958 */
2959 public boolean onSearchRequested() {
2960 startSearch(null, false, null, false);
2961 return true;
2962 }
2963
2964 /**
2965 * This hook is called to launch the search UI.
2966 *
2967 * <p>It is typically called from onSearchRequested(), either directly from
2968 * Activity.onSearchRequested() or from an overridden version in any given
2969 * Activity. If your goal is simply to activate search, it is preferred to call
2970 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2971 * is to inject specific data such as context data, it is preferred to <i>override</i>
2972 * onSearchRequested(), so that any callers to it will benefit from the override.
2973 *
2974 * @param initialQuery Any non-null non-empty string will be inserted as
2975 * pre-entered text in the search query box.
2976 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2977 * any further typing will replace it. This is useful for cases where an entire pre-formed
2978 * query is being inserted. If false, the selection point will be placed at the end of the
2979 * inserted query. This is useful when the inserted query is text that the user entered,
2980 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2981 * if initialQuery is a non-empty string.</i>
2982 * @param appSearchData An application can insert application-specific
2983 * context here, in order to improve quality or specificity of its own
2984 * searches. This data will be returned with SEARCH intent(s). Null if
2985 * no extra data is required.
2986 * @param globalSearch If false, this will only launch the search that has been specifically
2987 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002988 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2990 *
2991 * @see android.app.SearchManager
2992 * @see #onSearchRequested
2993 */
2994 public void startSearch(String initialQuery, boolean selectInitialQuery,
2995 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002996 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002997 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 appSearchData, globalSearch);
2999 }
3000
3001 /**
krosaend2d60142009-08-17 08:56:48 -07003002 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3003 * the search dialog. Made available for testing purposes.
3004 *
3005 * @param query The query to trigger. If empty, the request will be ignored.
3006 * @param appSearchData An application can insert application-specific
3007 * context here, in order to improve quality or specificity of its own
3008 * searches. This data will be returned with SEARCH intent(s). Null if
3009 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07003010 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003011 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07003012 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01003013 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07003014 }
3015
3016 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 * Request that key events come to this activity. Use this if your
3018 * activity has no views with focus, but the activity still wants
3019 * a chance to process key events.
3020 *
3021 * @see android.view.Window#takeKeyEvents
3022 */
3023 public void takeKeyEvents(boolean get) {
3024 getWindow().takeKeyEvents(get);
3025 }
3026
3027 /**
3028 * Enable extended window features. This is a convenience for calling
3029 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3030 *
3031 * @param featureId The desired feature as defined in
3032 * {@link android.view.Window}.
3033 * @return Returns true if the requested feature is supported and now
3034 * enabled.
3035 *
3036 * @see android.view.Window#requestFeature
3037 */
3038 public final boolean requestWindowFeature(int featureId) {
3039 return getWindow().requestFeature(featureId);
3040 }
3041
3042 /**
3043 * Convenience for calling
3044 * {@link android.view.Window#setFeatureDrawableResource}.
3045 */
3046 public final void setFeatureDrawableResource(int featureId, int resId) {
3047 getWindow().setFeatureDrawableResource(featureId, resId);
3048 }
3049
3050 /**
3051 * Convenience for calling
3052 * {@link android.view.Window#setFeatureDrawableUri}.
3053 */
3054 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3055 getWindow().setFeatureDrawableUri(featureId, uri);
3056 }
3057
3058 /**
3059 * Convenience for calling
3060 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3061 */
3062 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3063 getWindow().setFeatureDrawable(featureId, drawable);
3064 }
3065
3066 /**
3067 * Convenience for calling
3068 * {@link android.view.Window#setFeatureDrawableAlpha}.
3069 */
3070 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3071 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3072 }
3073
3074 /**
3075 * Convenience for calling
3076 * {@link android.view.Window#getLayoutInflater}.
3077 */
3078 public LayoutInflater getLayoutInflater() {
3079 return getWindow().getLayoutInflater();
3080 }
3081
3082 /**
3083 * Returns a {@link MenuInflater} with this context.
3084 */
3085 public MenuInflater getMenuInflater() {
3086 return new MenuInflater(this);
3087 }
3088
3089 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003090 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3091 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 if (mParent == null) {
3093 super.onApplyThemeResource(theme, resid, first);
3094 } else {
3095 try {
3096 theme.setTo(mParent.getTheme());
3097 } catch (Exception e) {
3098 // Empty
3099 }
3100 theme.applyStyle(resid, false);
3101 }
3102 }
3103
3104 /**
3105 * Launch an activity for which you would like a result when it finished.
3106 * When this activity exits, your
3107 * onActivityResult() method will be called with the given requestCode.
3108 * Using a negative requestCode is the same as calling
3109 * {@link #startActivity} (the activity is not launched as a sub-activity).
3110 *
3111 * <p>Note that this method should only be used with Intent protocols
3112 * that are defined to return a result. In other protocols (such as
3113 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3114 * not get the result when you expect. For example, if the activity you
3115 * are launching uses the singleTask launch mode, it will not run in your
3116 * task and thus you will immediately receive a cancel result.
3117 *
3118 * <p>As a special case, if you call startActivityForResult() with a requestCode
3119 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3120 * activity, then your window will not be displayed until a result is
3121 * returned back from the started activity. This is to avoid visible
3122 * flickering when redirecting to another activity.
3123 *
3124 * <p>This method throws {@link android.content.ActivityNotFoundException}
3125 * if there was no Activity found to run the given Intent.
3126 *
3127 * @param intent The intent to start.
3128 * @param requestCode If >= 0, this code will be returned in
3129 * onActivityResult() when the activity exits.
3130 *
3131 * @throws android.content.ActivityNotFoundException
3132 *
3133 * @see #startActivity
3134 */
3135 public void startActivityForResult(Intent intent, int requestCode) {
3136 if (mParent == null) {
3137 Instrumentation.ActivityResult ar =
3138 mInstrumentation.execStartActivity(
3139 this, mMainThread.getApplicationThread(), mToken, this,
3140 intent, requestCode);
3141 if (ar != null) {
3142 mMainThread.sendActivityResult(
3143 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3144 ar.getResultData());
3145 }
3146 if (requestCode >= 0) {
3147 // If this start is requesting a result, we can avoid making
3148 // the activity visible until the result is received. Setting
3149 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3150 // activity hidden during this time, to avoid flickering.
3151 // This can only be done when a result is requested because
3152 // that guarantees we will get information back when the
3153 // activity is finished, no matter what happens to it.
3154 mStartedActivity = true;
3155 }
3156 } else {
3157 mParent.startActivityFromChild(this, intent, requestCode);
3158 }
3159 }
3160
3161 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003162 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003163 * to use a IntentSender to describe the activity to be started. If
3164 * the IntentSender is for an activity, that activity will be started
3165 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3166 * here; otherwise, its associated action will be executed (such as
3167 * sending a broadcast) as if you had called
3168 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003169 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003170 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003171 * @param requestCode If >= 0, this code will be returned in
3172 * onActivityResult() when the activity exits.
3173 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003174 * intent parameter to {@link IntentSender#sendIntent}.
3175 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003176 * would like to change.
3177 * @param flagsValues Desired values for any bits set in
3178 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003179 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003180 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003181 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3182 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3183 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003184 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003185 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003186 flagsMask, flagsValues, this);
3187 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003188 mParent.startIntentSenderFromChild(this, intent, requestCode,
3189 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003190 }
3191 }
3192
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003193 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003194 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003195 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003196 try {
3197 String resolvedType = null;
3198 if (fillInIntent != null) {
3199 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3200 }
3201 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003202 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003203 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3204 requestCode, flagsMask, flagsValues);
3205 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003206 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003207 }
3208 Instrumentation.checkStartActivityResult(result, null);
3209 } catch (RemoteException e) {
3210 }
3211 if (requestCode >= 0) {
3212 // If this start is requesting a result, we can avoid making
3213 // the activity visible until the result is received. Setting
3214 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3215 // activity hidden during this time, to avoid flickering.
3216 // This can only be done when a result is requested because
3217 // that guarantees we will get information back when the
3218 // activity is finished, no matter what happens to it.
3219 mStartedActivity = true;
3220 }
3221 }
3222
3223 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 * Launch a new activity. You will not receive any information about when
3225 * the activity exits. This implementation overrides the base version,
3226 * providing information about
3227 * the activity performing the launch. Because of this additional
3228 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3229 * required; if not specified, the new activity will be added to the
3230 * task of the caller.
3231 *
3232 * <p>This method throws {@link android.content.ActivityNotFoundException}
3233 * if there was no Activity found to run the given Intent.
3234 *
3235 * @param intent The intent to start.
3236 *
3237 * @throws android.content.ActivityNotFoundException
3238 *
3239 * @see #startActivityForResult
3240 */
3241 @Override
3242 public void startActivity(Intent intent) {
3243 startActivityForResult(intent, -1);
3244 }
3245
3246 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003247 * Launch a new activity. You will not receive any information about when
3248 * the activity exits. This implementation overrides the base version,
3249 * providing information about
3250 * the activity performing the launch. Because of this additional
3251 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3252 * required; if not specified, the new activity will be added to the
3253 * task of the caller.
3254 *
3255 * <p>This method throws {@link android.content.ActivityNotFoundException}
3256 * if there was no Activity found to run the given Intent.
3257 *
3258 * @param intents The intents to start.
3259 *
3260 * @throws android.content.ActivityNotFoundException
3261 *
3262 * @see #startActivityForResult
3263 */
3264 @Override
3265 public void startActivities(Intent[] intents) {
3266 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3267 mToken, this, intents);
3268 }
3269
3270 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003271 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003272 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003273 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003274 * for more information.
3275 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003276 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003277 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003278 * intent parameter to {@link IntentSender#sendIntent}.
3279 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003280 * would like to change.
3281 * @param flagsValues Desired values for any bits set in
3282 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003283 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003284 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003285 public void startIntentSender(IntentSender intent,
3286 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3287 throws IntentSender.SendIntentException {
3288 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3289 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003290 }
3291
3292 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 * A special variation to launch an activity only if a new activity
3294 * instance is needed to handle the given Intent. In other words, this is
3295 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3296 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3297 * singleTask or singleTop
3298 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3299 * and the activity
3300 * that handles <var>intent</var> is the same as your currently running
3301 * activity, then a new instance is not needed. In this case, instead of
3302 * the normal behavior of calling {@link #onNewIntent} this function will
3303 * return and you can handle the Intent yourself.
3304 *
3305 * <p>This function can only be called from a top-level activity; if it is
3306 * called from a child activity, a runtime exception will be thrown.
3307 *
3308 * @param intent The intent to start.
3309 * @param requestCode If >= 0, this code will be returned in
3310 * onActivityResult() when the activity exits, as described in
3311 * {@link #startActivityForResult}.
3312 *
3313 * @return If a new activity was launched then true is returned; otherwise
3314 * false is returned and you must handle the Intent yourself.
3315 *
3316 * @see #startActivity
3317 * @see #startActivityForResult
3318 */
3319 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3320 if (mParent == null) {
3321 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3322 try {
3323 result = ActivityManagerNative.getDefault()
3324 .startActivity(mMainThread.getApplicationThread(),
3325 intent, intent.resolveTypeIfNeeded(
3326 getContentResolver()),
3327 null, 0,
3328 mToken, mEmbeddedID, requestCode, true, false);
3329 } catch (RemoteException e) {
3330 // Empty
3331 }
3332
3333 Instrumentation.checkStartActivityResult(result, intent);
3334
3335 if (requestCode >= 0) {
3336 // If this start is requesting a result, we can avoid making
3337 // the activity visible until the result is received. Setting
3338 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3339 // activity hidden during this time, to avoid flickering.
3340 // This can only be done when a result is requested because
3341 // that guarantees we will get information back when the
3342 // activity is finished, no matter what happens to it.
3343 mStartedActivity = true;
3344 }
3345 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3346 }
3347
3348 throw new UnsupportedOperationException(
3349 "startActivityIfNeeded can only be called from a top-level activity");
3350 }
3351
3352 /**
3353 * Special version of starting an activity, for use when you are replacing
3354 * other activity components. You can use this to hand the Intent off
3355 * to the next Activity that can handle it. You typically call this in
3356 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3357 *
3358 * @param intent The intent to dispatch to the next activity. For
3359 * correct behavior, this must be the same as the Intent that started
3360 * your own activity; the only changes you can make are to the extras
3361 * inside of it.
3362 *
3363 * @return Returns a boolean indicating whether there was another Activity
3364 * to start: true if there was a next activity to start, false if there
3365 * wasn't. In general, if true is returned you will then want to call
3366 * finish() on yourself.
3367 */
3368 public boolean startNextMatchingActivity(Intent intent) {
3369 if (mParent == null) {
3370 try {
3371 return ActivityManagerNative.getDefault()
3372 .startNextMatchingActivity(mToken, intent);
3373 } catch (RemoteException e) {
3374 // Empty
3375 }
3376 return false;
3377 }
3378
3379 throw new UnsupportedOperationException(
3380 "startNextMatchingActivity can only be called from a top-level activity");
3381 }
3382
3383 /**
3384 * This is called when a child activity of this one calls its
3385 * {@link #startActivity} or {@link #startActivityForResult} method.
3386 *
3387 * <p>This method throws {@link android.content.ActivityNotFoundException}
3388 * if there was no Activity found to run the given Intent.
3389 *
3390 * @param child The activity making the call.
3391 * @param intent The intent to start.
3392 * @param requestCode Reply request code. < 0 if reply is not requested.
3393 *
3394 * @throws android.content.ActivityNotFoundException
3395 *
3396 * @see #startActivity
3397 * @see #startActivityForResult
3398 */
3399 public void startActivityFromChild(Activity child, Intent intent,
3400 int requestCode) {
3401 Instrumentation.ActivityResult ar =
3402 mInstrumentation.execStartActivity(
3403 this, mMainThread.getApplicationThread(), mToken, child,
3404 intent, requestCode);
3405 if (ar != null) {
3406 mMainThread.sendActivityResult(
3407 mToken, child.mEmbeddedID, requestCode,
3408 ar.getResultCode(), ar.getResultData());
3409 }
3410 }
3411
3412 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003413 * This is called when a Fragment in this activity calls its
3414 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3415 * method.
3416 *
3417 * <p>This method throws {@link android.content.ActivityNotFoundException}
3418 * if there was no Activity found to run the given Intent.
3419 *
3420 * @param fragment The fragment making the call.
3421 * @param intent The intent to start.
3422 * @param requestCode Reply request code. < 0 if reply is not requested.
3423 *
3424 * @throws android.content.ActivityNotFoundException
3425 *
3426 * @see Fragment#startActivity
3427 * @see Fragment#startActivityForResult
3428 */
3429 public void startActivityFromFragment(Fragment fragment, Intent intent,
3430 int requestCode) {
3431 Instrumentation.ActivityResult ar =
3432 mInstrumentation.execStartActivity(
3433 this, mMainThread.getApplicationThread(), mToken, fragment,
3434 intent, requestCode);
3435 if (ar != null) {
3436 mMainThread.sendActivityResult(
3437 mToken, fragment.mWho, requestCode,
3438 ar.getResultCode(), ar.getResultData());
3439 }
3440 }
3441
3442 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003443 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003444 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003445 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003446 * for more information.
3447 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003448 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3449 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3450 int extraFlags)
3451 throws IntentSender.SendIntentException {
3452 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003453 flagsMask, flagsValues, child);
3454 }
3455
3456 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003457 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3458 * or {@link #finish} to specify an explicit transition animation to
3459 * perform next.
3460 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003461 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003462 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003463 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003464 */
3465 public void overridePendingTransition(int enterAnim, int exitAnim) {
3466 try {
3467 ActivityManagerNative.getDefault().overridePendingTransition(
3468 mToken, getPackageName(), enterAnim, exitAnim);
3469 } catch (RemoteException e) {
3470 }
3471 }
3472
3473 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 * Call this to set the result that your activity will return to its
3475 * caller.
3476 *
3477 * @param resultCode The result code to propagate back to the originating
3478 * activity, often RESULT_CANCELED or RESULT_OK
3479 *
3480 * @see #RESULT_CANCELED
3481 * @see #RESULT_OK
3482 * @see #RESULT_FIRST_USER
3483 * @see #setResult(int, Intent)
3484 */
3485 public final void setResult(int resultCode) {
3486 synchronized (this) {
3487 mResultCode = resultCode;
3488 mResultData = null;
3489 }
3490 }
3491
3492 /**
3493 * Call this to set the result that your activity will return to its
3494 * caller.
3495 *
3496 * @param resultCode The result code to propagate back to the originating
3497 * activity, often RESULT_CANCELED or RESULT_OK
3498 * @param data The data to propagate back to the originating activity.
3499 *
3500 * @see #RESULT_CANCELED
3501 * @see #RESULT_OK
3502 * @see #RESULT_FIRST_USER
3503 * @see #setResult(int)
3504 */
3505 public final void setResult(int resultCode, Intent data) {
3506 synchronized (this) {
3507 mResultCode = resultCode;
3508 mResultData = data;
3509 }
3510 }
3511
3512 /**
3513 * Return the name of the package that invoked this activity. This is who
3514 * the data in {@link #setResult setResult()} will be sent to. You can
3515 * use this information to validate that the recipient is allowed to
3516 * receive the data.
3517 *
3518 * <p>Note: if the calling activity is not expecting a result (that is it
3519 * did not use the {@link #startActivityForResult}
3520 * form that includes a request code), then the calling package will be
3521 * null.
3522 *
3523 * @return The package of the activity that will receive your
3524 * reply, or null if none.
3525 */
3526 public String getCallingPackage() {
3527 try {
3528 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3529 } catch (RemoteException e) {
3530 return null;
3531 }
3532 }
3533
3534 /**
3535 * Return the name of the activity that invoked this activity. This is
3536 * who the data in {@link #setResult setResult()} will be sent to. You
3537 * can use this information to validate that the recipient is allowed to
3538 * receive the data.
3539 *
3540 * <p>Note: if the calling activity is not expecting a result (that is it
3541 * did not use the {@link #startActivityForResult}
3542 * form that includes a request code), then the calling package will be
3543 * null.
3544 *
3545 * @return String The full name of the activity that will receive your
3546 * reply, or null if none.
3547 */
3548 public ComponentName getCallingActivity() {
3549 try {
3550 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3551 } catch (RemoteException e) {
3552 return null;
3553 }
3554 }
3555
3556 /**
3557 * Control whether this activity's main window is visible. This is intended
3558 * only for the special case of an activity that is not going to show a
3559 * UI itself, but can't just finish prior to onResume() because it needs
3560 * to wait for a service binding or such. Setting this to false allows
3561 * you to prevent your UI from being shown during that time.
3562 *
3563 * <p>The default value for this is taken from the
3564 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3565 */
3566 public void setVisible(boolean visible) {
3567 if (mVisibleFromClient != visible) {
3568 mVisibleFromClient = visible;
3569 if (mVisibleFromServer) {
3570 if (visible) makeVisible();
3571 else mDecor.setVisibility(View.INVISIBLE);
3572 }
3573 }
3574 }
3575
3576 void makeVisible() {
3577 if (!mWindowAdded) {
3578 ViewManager wm = getWindowManager();
3579 wm.addView(mDecor, getWindow().getAttributes());
3580 mWindowAdded = true;
3581 }
3582 mDecor.setVisibility(View.VISIBLE);
3583 }
3584
3585 /**
3586 * Check to see whether this activity is in the process of finishing,
3587 * either because you called {@link #finish} on it or someone else
3588 * has requested that it finished. This is often used in
3589 * {@link #onPause} to determine whether the activity is simply pausing or
3590 * completely finishing.
3591 *
3592 * @return If the activity is finishing, returns true; else returns false.
3593 *
3594 * @see #finish
3595 */
3596 public boolean isFinishing() {
3597 return mFinished;
3598 }
3599
3600 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003601 * Check to see whether this activity is in the process of being destroyed in order to be
3602 * recreated with a new configuration. This is often used in
3603 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3604 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3605 *
3606 * @return If the activity is being torn down in order to be recreated with a new configuration,
3607 * returns true; else returns false.
3608 */
3609 public boolean isChangingConfigurations() {
3610 return mChangingConfigurations;
3611 }
3612
3613 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003614 * Cause this Activity to be recreated with a new instance. This results
3615 * in essentially the same flow as when the Activity is created due to
3616 * a configuration change -- the current instance will go through its
3617 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3618 */
3619 public void recreate() {
3620 if (mParent != null) {
3621 throw new IllegalStateException("Can only be called on top-level activity");
3622 }
3623 if (Looper.myLooper() != mMainThread.getLooper()) {
3624 throw new IllegalStateException("Must be called from main thread");
3625 }
3626 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3627 }
3628
3629 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 * Call this when your activity is done and should be closed. The
3631 * ActivityResult is propagated back to whoever launched you via
3632 * onActivityResult().
3633 */
3634 public void finish() {
3635 if (mParent == null) {
3636 int resultCode;
3637 Intent resultData;
3638 synchronized (this) {
3639 resultCode = mResultCode;
3640 resultData = mResultData;
3641 }
Joe Onorato43a17652011-04-06 19:22:23 -07003642 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 try {
3644 if (ActivityManagerNative.getDefault()
3645 .finishActivity(mToken, resultCode, resultData)) {
3646 mFinished = true;
3647 }
3648 } catch (RemoteException e) {
3649 // Empty
3650 }
3651 } else {
3652 mParent.finishFromChild(this);
3653 }
3654 }
3655
3656 /**
3657 * This is called when a child activity of this one calls its
3658 * {@link #finish} method. The default implementation simply calls
3659 * finish() on this activity (the parent), finishing the entire group.
3660 *
3661 * @param child The activity making the call.
3662 *
3663 * @see #finish
3664 */
3665 public void finishFromChild(Activity child) {
3666 finish();
3667 }
3668
3669 /**
3670 * Force finish another activity that you had previously started with
3671 * {@link #startActivityForResult}.
3672 *
3673 * @param requestCode The request code of the activity that you had
3674 * given to startActivityForResult(). If there are multiple
3675 * activities started with this request code, they
3676 * will all be finished.
3677 */
3678 public void finishActivity(int requestCode) {
3679 if (mParent == null) {
3680 try {
3681 ActivityManagerNative.getDefault()
3682 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3683 } catch (RemoteException e) {
3684 // Empty
3685 }
3686 } else {
3687 mParent.finishActivityFromChild(this, requestCode);
3688 }
3689 }
3690
3691 /**
3692 * This is called when a child activity of this one calls its
3693 * finishActivity().
3694 *
3695 * @param child The activity making the call.
3696 * @param requestCode Request code that had been used to start the
3697 * activity.
3698 */
3699 public void finishActivityFromChild(Activity child, int requestCode) {
3700 try {
3701 ActivityManagerNative.getDefault()
3702 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3703 } catch (RemoteException e) {
3704 // Empty
3705 }
3706 }
3707
3708 /**
3709 * Called when an activity you launched exits, giving you the requestCode
3710 * you started it with, the resultCode it returned, and any additional
3711 * data from it. The <var>resultCode</var> will be
3712 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3713 * didn't return any result, or crashed during its operation.
3714 *
3715 * <p>You will receive this call immediately before onResume() when your
3716 * activity is re-starting.
3717 *
3718 * @param requestCode The integer request code originally supplied to
3719 * startActivityForResult(), allowing you to identify who this
3720 * result came from.
3721 * @param resultCode The integer result code returned by the child activity
3722 * through its setResult().
3723 * @param data An Intent, which can return result data to the caller
3724 * (various data can be attached to Intent "extras").
3725 *
3726 * @see #startActivityForResult
3727 * @see #createPendingResult
3728 * @see #setResult(int)
3729 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003730 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 }
3732
3733 /**
3734 * Create a new PendingIntent object which you can hand to others
3735 * for them to use to send result data back to your
3736 * {@link #onActivityResult} callback. The created object will be either
3737 * one-shot (becoming invalid after a result is sent back) or multiple
3738 * (allowing any number of results to be sent through it).
3739 *
3740 * @param requestCode Private request code for the sender that will be
3741 * associated with the result data when it is returned. The sender can not
3742 * modify this value, allowing you to identify incoming results.
3743 * @param data Default data to supply in the result, which may be modified
3744 * by the sender.
3745 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3746 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3747 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3748 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3749 * or any of the flags as supported by
3750 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3751 * of the intent that can be supplied when the actual send happens.
3752 *
3753 * @return Returns an existing or new PendingIntent matching the given
3754 * parameters. May return null only if
3755 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3756 * supplied.
3757 *
3758 * @see PendingIntent
3759 */
3760 public PendingIntent createPendingResult(int requestCode, Intent data,
3761 int flags) {
3762 String packageName = getPackageName();
3763 try {
3764 IIntentSender target =
3765 ActivityManagerNative.getDefault().getIntentSender(
3766 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3767 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003768 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 return target != null ? new PendingIntent(target) : null;
3770 } catch (RemoteException e) {
3771 // Empty
3772 }
3773 return null;
3774 }
3775
3776 /**
3777 * Change the desired orientation of this activity. If the activity
3778 * is currently in the foreground or otherwise impacting the screen
3779 * orientation, the screen will immediately be changed (possibly causing
3780 * the activity to be restarted). Otherwise, this will be used the next
3781 * time the activity is visible.
3782 *
3783 * @param requestedOrientation An orientation constant as used in
3784 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3785 */
3786 public void setRequestedOrientation(int requestedOrientation) {
3787 if (mParent == null) {
3788 try {
3789 ActivityManagerNative.getDefault().setRequestedOrientation(
3790 mToken, requestedOrientation);
3791 } catch (RemoteException e) {
3792 // Empty
3793 }
3794 } else {
3795 mParent.setRequestedOrientation(requestedOrientation);
3796 }
3797 }
3798
3799 /**
3800 * Return the current requested orientation of the activity. This will
3801 * either be the orientation requested in its component's manifest, or
3802 * the last requested orientation given to
3803 * {@link #setRequestedOrientation(int)}.
3804 *
3805 * @return Returns an orientation constant as used in
3806 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3807 */
3808 public int getRequestedOrientation() {
3809 if (mParent == null) {
3810 try {
3811 return ActivityManagerNative.getDefault()
3812 .getRequestedOrientation(mToken);
3813 } catch (RemoteException e) {
3814 // Empty
3815 }
3816 } else {
3817 return mParent.getRequestedOrientation();
3818 }
3819 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3820 }
3821
3822 /**
3823 * Return the identifier of the task this activity is in. This identifier
3824 * will remain the same for the lifetime of the activity.
3825 *
3826 * @return Task identifier, an opaque integer.
3827 */
3828 public int getTaskId() {
3829 try {
3830 return ActivityManagerNative.getDefault()
3831 .getTaskForActivity(mToken, false);
3832 } catch (RemoteException e) {
3833 return -1;
3834 }
3835 }
3836
3837 /**
3838 * Return whether this activity is the root of a task. The root is the
3839 * first activity in a task.
3840 *
3841 * @return True if this is the root activity, else false.
3842 */
3843 public boolean isTaskRoot() {
3844 try {
3845 return ActivityManagerNative.getDefault()
3846 .getTaskForActivity(mToken, true) >= 0;
3847 } catch (RemoteException e) {
3848 return false;
3849 }
3850 }
3851
3852 /**
3853 * Move the task containing this activity to the back of the activity
3854 * stack. The activity's order within the task is unchanged.
3855 *
3856 * @param nonRoot If false then this only works if the activity is the root
3857 * of a task; if true it will work for any activity in
3858 * a task.
3859 *
3860 * @return If the task was moved (or it was already at the
3861 * back) true is returned, else false.
3862 */
3863 public boolean moveTaskToBack(boolean nonRoot) {
3864 try {
3865 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3866 mToken, nonRoot);
3867 } catch (RemoteException e) {
3868 // Empty
3869 }
3870 return false;
3871 }
3872
3873 /**
3874 * Returns class name for this activity with the package prefix removed.
3875 * This is the default name used to read and write settings.
3876 *
3877 * @return The local class name.
3878 */
3879 public String getLocalClassName() {
3880 final String pkg = getPackageName();
3881 final String cls = mComponent.getClassName();
3882 int packageLen = pkg.length();
3883 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3884 || cls.charAt(packageLen) != '.') {
3885 return cls;
3886 }
3887 return cls.substring(packageLen+1);
3888 }
3889
3890 /**
3891 * Returns complete component name of this activity.
3892 *
3893 * @return Returns the complete component name for this activity
3894 */
3895 public ComponentName getComponentName()
3896 {
3897 return mComponent;
3898 }
3899
3900 /**
3901 * Retrieve a {@link SharedPreferences} object for accessing preferences
3902 * that are private to this activity. This simply calls the underlying
3903 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3904 * class name as the preferences name.
3905 *
3906 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3907 * operation, {@link #MODE_WORLD_READABLE} and
3908 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3909 *
3910 * @return Returns the single SharedPreferences instance that can be used
3911 * to retrieve and modify the preference values.
3912 */
3913 public SharedPreferences getPreferences(int mode) {
3914 return getSharedPreferences(getLocalClassName(), mode);
3915 }
3916
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003917 private void ensureSearchManager() {
3918 if (mSearchManager != null) {
3919 return;
3920 }
3921
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003922 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003923 }
3924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 @Override
3926 public Object getSystemService(String name) {
3927 if (getBaseContext() == null) {
3928 throw new IllegalStateException(
3929 "System services not available to Activities before onCreate()");
3930 }
3931
3932 if (WINDOW_SERVICE.equals(name)) {
3933 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003934 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003935 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003936 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 }
3938 return super.getSystemService(name);
3939 }
3940
3941 /**
3942 * Change the title associated with this activity. If this is a
3943 * top-level activity, the title for its window will change. If it
3944 * is an embedded activity, the parent can do whatever it wants
3945 * with it.
3946 */
3947 public void setTitle(CharSequence title) {
3948 mTitle = title;
3949 onTitleChanged(title, mTitleColor);
3950
3951 if (mParent != null) {
3952 mParent.onChildTitleChanged(this, title);
3953 }
3954 }
3955
3956 /**
3957 * Change the title associated with this activity. If this is a
3958 * top-level activity, the title for its window will change. If it
3959 * is an embedded activity, the parent can do whatever it wants
3960 * with it.
3961 */
3962 public void setTitle(int titleId) {
3963 setTitle(getText(titleId));
3964 }
3965
3966 public void setTitleColor(int textColor) {
3967 mTitleColor = textColor;
3968 onTitleChanged(mTitle, textColor);
3969 }
3970
3971 public final CharSequence getTitle() {
3972 return mTitle;
3973 }
3974
3975 public final int getTitleColor() {
3976 return mTitleColor;
3977 }
3978
3979 protected void onTitleChanged(CharSequence title, int color) {
3980 if (mTitleReady) {
3981 final Window win = getWindow();
3982 if (win != null) {
3983 win.setTitle(title);
3984 if (color != 0) {
3985 win.setTitleColor(color);
3986 }
3987 }
3988 }
3989 }
3990
3991 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3992 }
3993
3994 /**
3995 * Sets the visibility of the progress bar in the title.
3996 * <p>
3997 * In order for the progress bar to be shown, the feature must be requested
3998 * via {@link #requestWindowFeature(int)}.
3999 *
4000 * @param visible Whether to show the progress bars in the title.
4001 */
4002 public final void setProgressBarVisibility(boolean visible) {
4003 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
4004 Window.PROGRESS_VISIBILITY_OFF);
4005 }
4006
4007 /**
4008 * Sets the visibility of the indeterminate progress bar in the title.
4009 * <p>
4010 * In order for the progress bar to be shown, the feature must be requested
4011 * via {@link #requestWindowFeature(int)}.
4012 *
4013 * @param visible Whether to show the progress bars in the title.
4014 */
4015 public final void setProgressBarIndeterminateVisibility(boolean visible) {
4016 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
4017 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
4018 }
4019
4020 /**
4021 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
4022 * is always indeterminate).
4023 * <p>
4024 * In order for the progress bar to be shown, the feature must be requested
4025 * via {@link #requestWindowFeature(int)}.
4026 *
4027 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
4028 */
4029 public final void setProgressBarIndeterminate(boolean indeterminate) {
4030 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4031 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
4032 }
4033
4034 /**
4035 * Sets the progress for the progress bars in the title.
4036 * <p>
4037 * In order for the progress bar to be shown, the feature must be requested
4038 * via {@link #requestWindowFeature(int)}.
4039 *
4040 * @param progress The progress for the progress bar. Valid ranges are from
4041 * 0 to 10000 (both inclusive). If 10000 is given, the progress
4042 * bar will be completely filled and will fade out.
4043 */
4044 public final void setProgress(int progress) {
4045 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
4046 }
4047
4048 /**
4049 * Sets the secondary progress for the progress bar in the title. This
4050 * progress is drawn between the primary progress (set via
4051 * {@link #setProgress(int)} and the background. It can be ideal for media
4052 * scenarios such as showing the buffering progress while the default
4053 * progress shows the play progress.
4054 * <p>
4055 * In order for the progress bar to be shown, the feature must be requested
4056 * via {@link #requestWindowFeature(int)}.
4057 *
4058 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
4059 * 0 to 10000 (both inclusive).
4060 */
4061 public final void setSecondaryProgress(int secondaryProgress) {
4062 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4063 secondaryProgress + Window.PROGRESS_SECONDARY_START);
4064 }
4065
4066 /**
4067 * Suggests an audio stream whose volume should be changed by the hardware
4068 * volume controls.
4069 * <p>
4070 * The suggested audio stream will be tied to the window of this Activity.
4071 * If the Activity is switched, the stream set here is no longer the
4072 * suggested stream. The client does not need to save and restore the old
4073 * suggested stream value in onPause and onResume.
4074 *
4075 * @param streamType The type of the audio stream whose volume should be
4076 * changed by the hardware volume controls. It is not guaranteed that
4077 * the hardware volume controls will always change this stream's
4078 * volume (for example, if a call is in progress, its stream's volume
4079 * may be changed instead). To reset back to the default, use
4080 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4081 */
4082 public final void setVolumeControlStream(int streamType) {
4083 getWindow().setVolumeControlStream(streamType);
4084 }
4085
4086 /**
4087 * Gets the suggested audio stream whose volume should be changed by the
4088 * harwdare volume controls.
4089 *
4090 * @return The suggested audio stream type whose volume should be changed by
4091 * the hardware volume controls.
4092 * @see #setVolumeControlStream(int)
4093 */
4094 public final int getVolumeControlStream() {
4095 return getWindow().getVolumeControlStream();
4096 }
4097
4098 /**
4099 * Runs the specified action on the UI thread. If the current thread is the UI
4100 * thread, then the action is executed immediately. If the current thread is
4101 * not the UI thread, the action is posted to the event queue of the UI thread.
4102 *
4103 * @param action the action to run on the UI thread
4104 */
4105 public final void runOnUiThread(Runnable action) {
4106 if (Thread.currentThread() != mUiThread) {
4107 mHandler.post(action);
4108 } else {
4109 action.run();
4110 }
4111 }
4112
4113 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004114 * Standard implementation of
4115 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4116 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004117 * This implementation does nothing and is for
4118 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4119 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4120 *
4121 * @see android.view.LayoutInflater#createView
4122 * @see android.view.Window#getLayoutInflater
4123 */
4124 public View onCreateView(String name, Context context, AttributeSet attrs) {
4125 return null;
4126 }
4127
4128 /**
4129 * Standard implementation of
4130 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4131 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004132 * This implementation handles <fragment> tags to embed fragments inside
4133 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 *
4135 * @see android.view.LayoutInflater#createView
4136 * @see android.view.Window#getLayoutInflater
4137 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004138 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004139 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004140 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004141 }
4142
Dianne Hackborndef15372010-08-15 12:43:52 -07004143 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004144 TypedArray a =
4145 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004146 if (fname == null) {
4147 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4148 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004149 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004150 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4151 a.recycle();
4152
Dianne Hackborn625ac272010-09-17 18:29:22 -07004153 int containerId = parent != null ? parent.getId() : 0;
4154 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004155 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004156 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004157 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004158
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004159 // If we restored from a previous state, we may already have
4160 // instantiated this fragment from the state and should use
4161 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004162 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4163 if (fragment == null && tag != null) {
4164 fragment = mFragments.findFragmentByTag(tag);
4165 }
4166 if (fragment == null && containerId != View.NO_ID) {
4167 fragment = mFragments.findFragmentById(containerId);
4168 }
4169
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004170 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4171 + Integer.toHexString(id) + " fname=" + fname
4172 + " existing=" + fragment);
4173 if (fragment == null) {
4174 fragment = Fragment.instantiate(this, fname);
4175 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004176 fragment.mFragmentId = id != 0 ? id : containerId;
4177 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004178 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004179 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004180 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004181 fragment.mFragmentManager = mFragments;
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004182 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004183 mFragments.addFragment(fragment, true);
4184
4185 } else if (fragment.mInLayout) {
4186 // A fragment already exists and it is not one we restored from
4187 // previous state.
4188 throw new IllegalArgumentException(attrs.getPositionDescription()
4189 + ": Duplicate id 0x" + Integer.toHexString(id)
4190 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4191 + " with another fragment for " + fname);
4192 } else {
4193 // This fragment was retained from a previous instance; get it
4194 // going now.
4195 fragment.mInLayout = true;
4196 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004197 // If this fragment is newly instantiated (either right now, or
4198 // from last saved state), then give it the attributes to
4199 // initialize itself.
4200 if (!fragment.mRetaining) {
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004201 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborndef15372010-08-15 12:43:52 -07004202 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004203 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004204 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004205
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004206 if (fragment.mView == null) {
4207 throw new IllegalStateException("Fragment " + fname
4208 + " did not create a view.");
4209 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004210 if (id != 0) {
4211 fragment.mView.setId(id);
4212 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004213 if (fragment.mView.getTag() == null) {
4214 fragment.mView.setTag(tag);
4215 }
4216 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 }
4218
Daniel Sandler69a48172010-06-23 16:29:36 -04004219 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004220 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004221 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004222 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004223 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004224 * @param fd The raw file descriptor that the dump is being sent to.
4225 * @param writer The PrintWriter to which you should dump your state. This will be
4226 * closed for you after you return.
4227 * @param args additional arguments to the dump request.
4228 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004229 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4230 writer.print(prefix); writer.print("Local Activity ");
4231 writer.print(Integer.toHexString(System.identityHashCode(this)));
4232 writer.println(" State:");
4233 String innerPrefix = prefix + " ";
4234 writer.print(innerPrefix); writer.print("mResumed=");
4235 writer.print(mResumed); writer.print(" mStopped=");
4236 writer.print(mStopped); writer.print(" mFinished=");
4237 writer.println(mFinished);
4238 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4239 writer.println(mLoadersStarted);
4240 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4241 writer.println(mChangingConfigurations);
4242 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4243 writer.println(mCurrentConfig);
4244 if (mLoaderManager != null) {
4245 writer.print(prefix); writer.print("Loader Manager ");
4246 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4247 writer.println(":");
4248 mLoaderManager.dump(prefix + " ", fd, writer, args);
4249 }
4250 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004251 }
4252
4253 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004254 * Bit indicating that this activity is "immersive" and should not be
4255 * interrupted by notifications if possible.
4256 *
4257 * This value is initially set by the manifest property
4258 * <code>android:immersive</code> but may be changed at runtime by
4259 * {@link #setImmersive}.
4260 *
4261 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004262 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004263 */
4264 public boolean isImmersive() {
4265 try {
4266 return ActivityManagerNative.getDefault().isImmersive(mToken);
4267 } catch (RemoteException e) {
4268 return false;
4269 }
4270 }
4271
4272 /**
4273 * Adjust the current immersive mode setting.
4274 *
4275 * Note that changing this value will have no effect on the activity's
4276 * {@link android.content.pm.ActivityInfo} structure; that is, if
4277 * <code>android:immersive</code> is set to <code>true</code>
4278 * in the application's manifest entry for this activity, the {@link
4279 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4280 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4281 * FLAG_IMMERSIVE} bit set.
4282 *
4283 * @see #isImmersive
4284 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004285 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004286 */
4287 public void setImmersive(boolean i) {
4288 try {
4289 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4290 } catch (RemoteException e) {
4291 // pass
4292 }
4293 }
4294
Adam Powell6e346362010-07-23 10:18:23 -07004295 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004296 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004297 *
4298 * @param callback Callback that will manage lifecycle events for this context mode
4299 * @return The ContextMode that was started, or null if it was canceled
4300 *
4301 * @see ActionMode
4302 */
Adam Powell5d279772010-07-27 16:34:07 -07004303 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004304 return mWindow.getDecorView().startActionMode(callback);
4305 }
4306
Adam Powelldebf3be2010-11-15 18:58:48 -08004307 /**
4308 * Give the Activity a chance to control the UI for an action mode requested
4309 * by the system.
4310 *
4311 * <p>Note: If you are looking for a notification callback that an action mode
4312 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4313 *
4314 * @param callback The callback that should control the new action mode
4315 * @return The new action mode, or <code>null</code> if the activity does not want to
4316 * provide special handling for this action mode. (It will be handled by the system.)
4317 */
4318 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004319 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004320 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004321 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004322 }
4323 return null;
4324 }
4325
Adam Powelldebf3be2010-11-15 18:58:48 -08004326 /**
4327 * Notifies the Activity that an action mode has been started.
4328 * Activity subclasses overriding this method should call the superclass implementation.
4329 *
4330 * @param mode The new action mode.
4331 */
4332 public void onActionModeStarted(ActionMode mode) {
4333 }
4334
4335 /**
4336 * Notifies the activity that an action mode has finished.
4337 * Activity subclasses overriding this method should call the superclass implementation.
4338 *
4339 * @param mode The action mode that just finished.
4340 */
4341 public void onActionModeFinished(ActionMode mode) {
4342 }
4343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 // ------------------ Internal API ------------------
4345
4346 final void setParent(Activity parent) {
4347 mParent = parent;
4348 }
4349
4350 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4351 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004352 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004354 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004355 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 }
4357
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004358 final void attach(Context context, ActivityThread aThread,
4359 Instrumentation instr, IBinder token, int ident,
4360 Application application, Intent intent, ActivityInfo info,
4361 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004362 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004363 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 attachBaseContext(context);
4365
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004366 mFragments.attachActivity(this);
4367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 mWindow = PolicyManager.makeNewWindow(this);
4369 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08004370 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4372 mWindow.setSoftInputMode(info.softInputMode);
4373 }
4374 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 mMainThread = aThread;
4377 mInstrumentation = instr;
4378 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004379 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 mApplication = application;
4381 mIntent = intent;
4382 mComponent = intent.getComponent();
4383 mActivityInfo = info;
4384 mTitle = title;
4385 mParent = parent;
4386 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004387 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388
Romain Guy529b60a2010-08-03 18:05:47 -07004389 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4390 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 if (mParent != null) {
4392 mWindow.setContainer(mParent.getWindow());
4393 }
4394 mWindowManager = mWindow.getWindowManager();
4395 mCurrentConfig = config;
4396 }
4397
4398 final IBinder getActivityToken() {
4399 return mParent != null ? mParent.getActivityToken() : mToken;
4400 }
4401
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004402 final void performCreate(Bundle icicle) {
4403 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004404 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4405 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004406 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004407 }
4408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004410 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004412 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413 mInstrumentation.callActivityOnStart(this);
4414 if (!mCalled) {
4415 throw new SuperNotCalledException(
4416 "Activity " + mComponent.toShortString() +
4417 " did not call through to super.onStart()");
4418 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004419 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004420 if (mAllLoaderManagers != null) {
4421 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackbornafc4b282011-06-10 17:03:42 -07004422 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
4423 lm.finishRetain();
4424 lm.doReportStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004425 }
4426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 }
4428
4429 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004430 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 if (mStopped) {
4433 mStopped = false;
Dianne Hackbornce418e62011-03-01 14:31:38 -08004434 if (mToken != null && mParent == null) {
4435 WindowManagerImpl.getDefault().setStoppedState(mToken, false);
4436 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07004437
4438 synchronized (mManagedCursors) {
4439 final int N = mManagedCursors.size();
4440 for (int i=0; i<N; i++) {
4441 ManagedCursor mc = mManagedCursors.get(i);
4442 if (mc.mReleased || mc.mUpdated) {
4443 if (!mc.mCursor.requery()) {
4444 throw new IllegalStateException(
4445 "trying to requery an already closed cursor "
4446 + mc.mCursor);
4447 }
4448 mc.mReleased = false;
4449 mc.mUpdated = false;
4450 }
4451 }
4452 }
4453
4454 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 mInstrumentation.callActivityOnRestart(this);
4456 if (!mCalled) {
4457 throw new SuperNotCalledException(
4458 "Activity " + mComponent.toShortString() +
4459 " did not call through to super.onRestart()");
4460 }
4461 performStart();
4462 }
4463 }
4464
4465 final void performResume() {
4466 performRestart();
4467
Dianne Hackborn445646c2010-06-25 15:52:59 -07004468 mFragments.execPendingActions();
4469
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004470 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06004473 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 mInstrumentation.callActivityOnResume(this);
4475 if (!mCalled) {
4476 throw new SuperNotCalledException(
4477 "Activity " + mComponent.toShortString() +
4478 " did not call through to super.onResume()");
4479 }
4480
4481 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004483
4484 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004485 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 onPostResume();
4488 if (!mCalled) {
4489 throw new SuperNotCalledException(
4490 "Activity " + mComponent.toShortString() +
4491 " did not call through to super.onPostResume()");
4492 }
4493 }
4494
4495 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004496 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004497 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004499 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004500 if (!mCalled && getApplicationInfo().targetSdkVersion
4501 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4502 throw new SuperNotCalledException(
4503 "Activity " + mComponent.toShortString() +
4504 " did not call through to super.onPause()");
4505 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06004506 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 }
4508
4509 final void performUserLeaving() {
4510 onUserInteraction();
4511 onUserLeaveHint();
4512 }
4513
4514 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004515 if (mLoadersStarted) {
4516 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004517 if (mLoaderManager != null) {
4518 if (!mChangingConfigurations) {
4519 mLoaderManager.doStop();
4520 } else {
4521 mLoaderManager.doRetain();
4522 }
4523 }
4524 }
4525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 if (!mStopped) {
4527 if (mWindow != null) {
4528 mWindow.closeAllPanels();
4529 }
4530
Dianne Hackbornce418e62011-03-01 14:31:38 -08004531 if (mToken != null && mParent == null) {
4532 WindowManagerImpl.getDefault().setStoppedState(mToken, true);
4533 }
4534
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004535 mFragments.dispatchStop();
4536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 mCalled = false;
4538 mInstrumentation.callActivityOnStop(this);
4539 if (!mCalled) {
4540 throw new SuperNotCalledException(
4541 "Activity " + mComponent.toShortString() +
4542 " did not call through to super.onStop()");
4543 }
4544
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004545 synchronized (mManagedCursors) {
4546 final int N = mManagedCursors.size();
4547 for (int i=0; i<N; i++) {
4548 ManagedCursor mc = mManagedCursors.get(i);
4549 if (!mc.mReleased) {
4550 mc.mCursor.deactivate();
4551 mc.mReleased = true;
4552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 }
4554 }
4555
4556 mStopped = true;
4557 }
4558 mResumed = false;
4559 }
4560
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004561 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004562 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004563 mFragments.dispatchDestroy();
4564 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004565 if (mLoaderManager != null) {
4566 mLoaderManager.doDestroy();
4567 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004568 }
4569
Jeff Hamilton52d32032011-01-08 15:31:26 -06004570 /**
4571 * @hide
4572 */
4573 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 return mResumed;
4575 }
4576
4577 void dispatchActivityResult(String who, int requestCode,
4578 int resultCode, Intent data) {
Joe Onorato43a17652011-04-06 19:22:23 -07004579 if (false) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4581 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004582 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 if (who == null) {
4584 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004585 } else {
4586 Fragment frag = mFragments.findFragmentByWho(who);
4587 if (frag != null) {
4588 frag.onActivityResult(requestCode, resultCode, data);
4589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 }
4591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592}