blob: fc4d12ca57cadca8b570080ff57f6c525ebb690c [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;
54import android.util.Config;
55import android.util.EventLog;
56import android.util.Log;
57import android.util.SparseArray;
Adam Powell6e346362010-07-23 10:18:23 -070058import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070060import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.ContextThemeWrapper;
62import android.view.KeyEvent;
63import android.view.LayoutInflater;
64import android.view.Menu;
65import android.view.MenuInflater;
66import android.view.MenuItem;
67import android.view.MotionEvent;
68import android.view.View;
Dianne Hackbornce418e62011-03-01 14:31:38 -080069import android.view.WindowManagerImpl;
Adam Powell6e346362010-07-23 10:18:23 -070070import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070072import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.view.ViewManager;
74import android.view.Window;
75import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070076import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.widget.AdapterView;
78
Dianne Hackborn625ac272010-09-17 18:29:22 -070079import java.io.FileDescriptor;
80import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070081import java.util.ArrayList;
82import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84/**
85 * An activity is a single, focused thing that the user can do. Almost all
86 * activities interact with the user, so the Activity class takes care of
87 * creating a window for you in which you can place your UI with
88 * {@link #setContentView}. While activities are often presented to the user
89 * as full-screen windows, they can also be used in other ways: as floating
90 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
91 * or embedded inside of another activity (using {@link ActivityGroup}).
92 *
93 * There are two methods almost all subclasses of Activity will implement:
94 *
95 * <ul>
96 * <li> {@link #onCreate} is where you initialize your activity. Most
97 * importantly, here you will usually call {@link #setContentView(int)}
98 * with a layout resource defining your UI, and using {@link #findViewById}
99 * to retrieve the widgets in that UI that you need to interact with
100 * programmatically.
101 *
102 * <li> {@link #onPause} is where you deal with the user leaving your
103 * activity. Most importantly, any changes made by the user should at this
104 * point be committed (usually to the
105 * {@link android.content.ContentProvider} holding the data).
106 * </ul>
107 *
108 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
109 * activity classes must have a corresponding
110 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
111 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
112 *
113 * <p>The Activity class is an important part of an application's overall lifecycle,
114 * and the way activities are launched and put together is a fundamental
Scott Main7aee61f2011-02-08 11:25:01 -0800115 * part of the platform's application model. For a detailed perspective on the structure of an
116 * Android application and how activities behave, please read the
117 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
118 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
119 * documents.</p>
120 *
121 * <p>You can also find a detailed discussion about how to create activities in the
122 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
123 * document.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 *
125 * <p>Topics covered here:
126 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700127 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
129 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
130 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
131 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
132 * <li><a href="#Permissions">Permissions</a>
133 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
134 * </ol>
135 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700136 * <a name="Fragments"></a>
137 * <h3>Fragments</h3>
138 *
139 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
140 * implementations can make use of the {@link Fragment} class to better
141 * modularize their code, build more sophisticated user interfaces for larger
142 * screens, and help scale their application between small and large screens.
143 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 * <a name="ActivityLifecycle"></a>
145 * <h3>Activity Lifecycle</h3>
146 *
147 * <p>Activities in the system are managed as an <em>activity stack</em>.
148 * When a new activity is started, it is placed on the top of the stack
149 * and becomes the running activity -- the previous activity always remains
150 * below it in the stack, and will not come to the foreground again until
151 * the new activity exits.</p>
152 *
153 * <p>An activity has essentially four states:</p>
154 * <ul>
155 * <li> If an activity in the foreground of the screen (at the top of
156 * the stack),
157 * it is <em>active</em> or <em>running</em>. </li>
158 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
159 * or transparent activity has focus on top of your activity), it
160 * is <em>paused</em>. A paused activity is completely alive (it
161 * maintains all state and member information and remains attached to
162 * the window manager), but can be killed by the system in extreme
163 * low memory situations.
164 * <li>If an activity is completely obscured by another activity,
165 * it is <em>stopped</em>. It still retains all state and member information,
166 * however, it is no longer visible to the user so its window is hidden
167 * and it will often be killed by the system when memory is needed
168 * elsewhere.</li>
169 * <li>If an activity is paused or stopped, the system can drop the activity
170 * from memory by either asking it to finish, or simply killing its
171 * process. When it is displayed again to the user, it must be
172 * completely restarted and restored to its previous state.</li>
173 * </ul>
174 *
175 * <p>The following diagram shows the important state paths of an Activity.
176 * The square rectangles represent callback methods you can implement to
177 * perform operations when the Activity moves between states. The colored
178 * ovals are major states the Activity can be in.</p>
179 *
180 * <p><img src="../../../images/activity_lifecycle.png"
181 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
182 *
183 * <p>There are three key loops you may be interested in monitoring within your
184 * activity:
185 *
186 * <ul>
187 * <li>The <b>entire lifetime</b> of an activity happens between the first call
188 * to {@link android.app.Activity#onCreate} through to a single final call
189 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
190 * of "global" state in onCreate(), and release all remaining resources in
191 * onDestroy(). For example, if it has a thread running in the background
192 * to download data from the network, it may create that thread in onCreate()
193 * and then stop the thread in onDestroy().
194 *
195 * <li>The <b>visible lifetime</b> of an activity happens between a call to
196 * {@link android.app.Activity#onStart} until a corresponding call to
197 * {@link android.app.Activity#onStop}. During this time the user can see the
198 * activity on-screen, though it may not be in the foreground and interacting
199 * with the user. Between these two methods you can maintain resources that
200 * are needed to show the activity to the user. For example, you can register
201 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
202 * that impact your UI, and unregister it in onStop() when the user an no
203 * longer see what you are displaying. The onStart() and onStop() methods
204 * can be called multiple times, as the activity becomes visible and hidden
205 * to the user.
206 *
207 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
208 * {@link android.app.Activity#onResume} until a corresponding call to
209 * {@link android.app.Activity#onPause}. During this time the activity is
210 * in front of all other activities and interacting with the user. An activity
211 * can frequently go between the resumed and paused states -- for example when
212 * the device goes to sleep, when an activity result is delivered, when a new
213 * intent is delivered -- so the code in these methods should be fairly
214 * lightweight.
215 * </ul>
216 *
217 * <p>The entire lifecycle of an activity is defined by the following
218 * Activity methods. All of these are hooks that you can override
219 * to do appropriate work when the activity changes state. All
220 * activities will implement {@link android.app.Activity#onCreate}
221 * to do their initial setup; many will also implement
222 * {@link android.app.Activity#onPause} to commit changes to data and
223 * otherwise prepare to stop interacting with the user. You should always
224 * call up to your superclass when implementing these methods.</p>
225 *
226 * </p>
227 * <pre class="prettyprint">
228 * public class Activity extends ApplicationContext {
229 * protected void onCreate(Bundle savedInstanceState);
230 *
231 * protected void onStart();
232 *
233 * protected void onRestart();
234 *
235 * protected void onResume();
236 *
237 * protected void onPause();
238 *
239 * protected void onStop();
240 *
241 * protected void onDestroy();
242 * }
243 * </pre>
244 *
245 * <p>In general the movement through an activity's lifecycle looks like
246 * this:</p>
247 *
248 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
249 * <colgroup align="left" span="3" />
250 * <colgroup align="left" />
251 * <colgroup align="center" />
252 * <colgroup align="center" />
253 *
254 * <thead>
255 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
256 * </thead>
257 *
258 * <tbody>
259 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
260 * <td>Called when the activity is first created.
261 * This is where you should do all of your normal static set up:
262 * create views, bind data to lists, etc. This method also
263 * provides you with a Bundle containing the activity's previously
264 * frozen state, if there was one.
265 * <p>Always followed by <code>onStart()</code>.</td>
266 * <td align="center">No</td>
267 * <td align="center"><code>onStart()</code></td>
268 * </tr>
269 *
270 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
271 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
272 * <td>Called after your activity has been stopped, prior to it being
273 * started again.
274 * <p>Always followed by <code>onStart()</code></td>
275 * <td align="center">No</td>
276 * <td align="center"><code>onStart()</code></td>
277 * </tr>
278 *
279 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
280 * <td>Called when the activity is becoming visible to the user.
281 * <p>Followed by <code>onResume()</code> if the activity comes
282 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
283 * <td align="center">No</td>
284 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
285 * </tr>
286 *
287 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
288 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
289 * <td>Called when the activity will start
290 * interacting with the user. At this point your activity is at
291 * the top of the activity stack, with user input going to it.
292 * <p>Always followed by <code>onPause()</code>.</td>
293 * <td align="center">No</td>
294 * <td align="center"><code>onPause()</code></td>
295 * </tr>
296 *
297 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
298 * <td>Called when the system is about to start resuming a previous
299 * activity. This is typically used to commit unsaved changes to
300 * persistent data, stop animations and other things that may be consuming
301 * CPU, etc. Implementations of this method must be very quick because
302 * the next activity will not be resumed until this method returns.
303 * <p>Followed by either <code>onResume()</code> if the activity
304 * returns back to the front, or <code>onStop()</code> if it becomes
305 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800306 * <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 -0800307 * <td align="center"><code>onResume()</code> or<br>
308 * <code>onStop()</code></td>
309 * </tr>
310 *
311 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
312 * <td>Called when the activity is no longer visible to the user, because
313 * another activity has been resumed and is covering this one. This
314 * may happen either because a new activity is being started, an existing
315 * one is being brought in front of this one, or this one is being
316 * destroyed.
317 * <p>Followed by either <code>onRestart()</code> if
318 * this activity is coming back to interact with the user, or
319 * <code>onDestroy()</code> if this activity is going away.</td>
320 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
321 * <td align="center"><code>onRestart()</code> or<br>
322 * <code>onDestroy()</code></td>
323 * </tr>
324 *
325 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
326 * <td>The final call you receive before your
327 * activity is destroyed. This can happen either because the
328 * activity is finishing (someone called {@link Activity#finish} on
329 * it, or because the system is temporarily destroying this
330 * instance of the activity to save space. You can distinguish
331 * between these two scenarios with the {@link
332 * Activity#isFinishing} method.</td>
333 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
334 * <td align="center"><em>nothing</em></td>
335 * </tr>
336 * </tbody>
337 * </table>
338 *
339 * <p>Note the "Killable" column in the above table -- for those methods that
340 * are marked as being killable, after that method returns the process hosting the
341 * activity may killed by the system <em>at any time</em> without another line
342 * of its code being executed. Because of this, you should use the
343 * {@link #onPause} method to write any persistent data (such as user edits)
344 * to storage. In addition, the method
345 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
346 * in such a background state, allowing you to save away any dynamic instance
347 * state in your activity into the given Bundle, to be later received in
348 * {@link #onCreate} if the activity needs to be re-created.
349 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
350 * section for more information on how the lifecycle of a process is tied
351 * to the activities it is hosting. Note that it is important to save
352 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
Daisuke Miyakawa5c40f3f2011-02-15 13:24:36 -0800353 * because the latter is not part of the lifecycle callbacks, so will not
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 * be called in every situation as described in its documentation.</p>
355 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800356 * <p class="note">Be aware that these semantics will change slightly between
357 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
358 * vs. those targeting prior platforms. Starting with Honeycomb, an application
359 * is not in the killable state until its {@link #onStop} has returned. This
360 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
361 * safely called after {@link #onPause()} and allows and application to safely
362 * wait until {@link #onStop()} to save persistent state.</p>
363 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 * <p>For those methods that are not marked as being killable, the activity's
365 * process will not be killed by the system starting from the time the method
366 * is called and continuing after it returns. Thus an activity is in the killable
367 * state, for example, between after <code>onPause()</code> to the start of
368 * <code>onResume()</code>.</p>
369 *
370 * <a name="ConfigurationChanges"></a>
371 * <h3>Configuration Changes</h3>
372 *
373 * <p>If the configuration of the device (as defined by the
374 * {@link Configuration Resources.Configuration} class) changes,
375 * then anything displaying a user interface will need to update to match that
376 * configuration. Because Activity is the primary mechanism for interacting
377 * with the user, it includes special support for handling configuration
378 * changes.</p>
379 *
380 * <p>Unless you specify otherwise, a configuration change (such as a change
381 * in screen orientation, language, input devices, etc) will cause your
382 * current activity to be <em>destroyed</em>, going through the normal activity
383 * lifecycle process of {@link #onPause},
384 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
385 * had been in the foreground or visible to the user, once {@link #onDestroy} is
386 * called in that instance then a new instance of the activity will be
387 * created, with whatever savedInstanceState the previous instance had generated
388 * from {@link #onSaveInstanceState}.</p>
389 *
390 * <p>This is done because any application resource,
391 * including layout files, can change based on any configuration value. Thus
392 * the only safe way to handle a configuration change is to re-retrieve all
393 * resources, including layouts, drawables, and strings. Because activities
394 * must already know how to save their state and re-create themselves from
395 * that state, this is a convenient way to have an activity restart itself
396 * with a new configuration.</p>
397 *
398 * <p>In some special cases, you may want to bypass restarting of your
399 * activity based on one or more types of configuration changes. This is
400 * done with the {@link android.R.attr#configChanges android:configChanges}
401 * attribute in its manifest. For any types of configuration changes you say
402 * that you handle there, you will receive a call to your current activity's
403 * {@link #onConfigurationChanged} method instead of being restarted. If
404 * a configuration change involves any that you do not handle, however, the
405 * activity will still be restarted and {@link #onConfigurationChanged}
406 * will not be called.</p>
407 *
408 * <a name="StartingActivities"></a>
409 * <h3>Starting Activities and Getting Results</h3>
410 *
411 * <p>The {@link android.app.Activity#startActivity}
412 * method is used to start a
413 * new activity, which will be placed at the top of the activity stack. It
414 * takes a single argument, an {@link android.content.Intent Intent},
415 * which describes the activity
416 * to be executed.</p>
417 *
418 * <p>Sometimes you want to get a result back from an activity when it
419 * ends. For example, you may start an activity that lets the user pick
420 * a person in a list of contacts; when it ends, it returns the person
421 * that was selected. To do this, you call the
422 * {@link android.app.Activity#startActivityForResult(Intent, int)}
423 * version with a second integer parameter identifying the call. The result
424 * will come back through your {@link android.app.Activity#onActivityResult}
425 * method.</p>
426 *
427 * <p>When an activity exits, it can call
428 * {@link android.app.Activity#setResult(int)}
429 * to return data back to its parent. It must always supply a result code,
430 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
431 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
432 * return back an Intent containing any additional data it wants. All of this
433 * information appears back on the
434 * parent's <code>Activity.onActivityResult()</code>, along with the integer
435 * identifier it originally supplied.</p>
436 *
437 * <p>If a child activity fails for any reason (such as crashing), the parent
438 * activity will receive a result with the code RESULT_CANCELED.</p>
439 *
440 * <pre class="prettyprint">
441 * public class MyActivity extends Activity {
442 * ...
443 *
444 * static final int PICK_CONTACT_REQUEST = 0;
445 *
446 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
447 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
448 * // When the user center presses, let them pick a contact.
449 * startActivityForResult(
450 * new Intent(Intent.ACTION_PICK,
451 * new Uri("content://contacts")),
452 * PICK_CONTACT_REQUEST);
453 * return true;
454 * }
455 * return false;
456 * }
457 *
458 * protected void onActivityResult(int requestCode, int resultCode,
459 * Intent data) {
460 * if (requestCode == PICK_CONTACT_REQUEST) {
461 * if (resultCode == RESULT_OK) {
462 * // A contact was picked. Here we will just display it
463 * // to the user.
464 * startActivity(new Intent(Intent.ACTION_VIEW, data));
465 * }
466 * }
467 * }
468 * }
469 * </pre>
470 *
471 * <a name="SavingPersistentState"></a>
472 * <h3>Saving Persistent State</h3>
473 *
474 * <p>There are generally two kinds of persistent state than an activity
475 * will deal with: shared document-like data (typically stored in a SQLite
476 * database using a {@linkplain android.content.ContentProvider content provider})
477 * and internal state such as user preferences.</p>
478 *
479 * <p>For content provider data, we suggest that activities use a
480 * "edit in place" user model. That is, any edits a user makes are effectively
481 * made immediately without requiring an additional confirmation step.
482 * Supporting this model is generally a simple matter of following two rules:</p>
483 *
484 * <ul>
485 * <li> <p>When creating a new document, the backing database entry or file for
486 * it is created immediately. For example, if the user chooses to write
487 * a new e-mail, a new entry for that e-mail is created as soon as they
488 * start entering data, so that if they go to any other activity after
489 * that point this e-mail will now appear in the list of drafts.</p>
490 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
491 * commit to the backing content provider or file any changes the user
492 * has made. This ensures that those changes will be seen by any other
493 * activity that is about to run. You will probably want to commit
494 * your data even more aggressively at key times during your
495 * activity's lifecycle: for example before starting a new
496 * activity, before finishing your own activity, when the user
497 * switches between input fields, etc.</p>
498 * </ul>
499 *
500 * <p>This model is designed to prevent data loss when a user is navigating
501 * between activities, and allows the system to safely kill an activity (because
502 * system resources are needed somewhere else) at any time after it has been
503 * paused. Note this implies
504 * that the user pressing BACK from your activity does <em>not</em>
505 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800506 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
508 *
509 * <p>See the {@linkplain android.content.ContentProvider content package} for
510 * more information about content providers. These are a key aspect of how
511 * different activities invoke and propagate data between themselves.</p>
512 *
513 * <p>The Activity class also provides an API for managing internal persistent state
514 * associated with an activity. This can be used, for example, to remember
515 * the user's preferred initial display in a calendar (day view or week view)
516 * or the user's default home page in a web browser.</p>
517 *
518 * <p>Activity persistent state is managed
519 * with the method {@link #getPreferences},
520 * allowing you to retrieve and
521 * modify a set of name/value pairs associated with the activity. To use
522 * preferences that are shared across multiple application components
523 * (activities, receivers, services, providers), you can use the underlying
524 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
525 * to retrieve a preferences
526 * object stored under a specific name.
527 * (Note that it is not possible to share settings data across application
528 * packages -- for that you will need a content provider.)</p>
529 *
530 * <p>Here is an excerpt from a calendar activity that stores the user's
531 * preferred view mode in its persistent settings:</p>
532 *
533 * <pre class="prettyprint">
534 * public class CalendarActivity extends Activity {
535 * ...
536 *
537 * static final int DAY_VIEW_MODE = 0;
538 * static final int WEEK_VIEW_MODE = 1;
539 *
540 * private SharedPreferences mPrefs;
541 * private int mCurViewMode;
542 *
543 * protected void onCreate(Bundle savedInstanceState) {
544 * super.onCreate(savedInstanceState);
545 *
546 * SharedPreferences mPrefs = getSharedPreferences();
547 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
548 * }
549 *
550 * protected void onPause() {
551 * super.onPause();
552 *
553 * SharedPreferences.Editor ed = mPrefs.edit();
554 * ed.putInt("view_mode", mCurViewMode);
555 * ed.commit();
556 * }
557 * }
558 * </pre>
559 *
560 * <a name="Permissions"></a>
561 * <h3>Permissions</h3>
562 *
563 * <p>The ability to start a particular Activity can be enforced when it is
564 * declared in its
565 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
566 * tag. By doing so, other applications will need to declare a corresponding
567 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
568 * element in their own manifest to be able to start that activity.
569 *
570 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
571 * document for more information on permissions and security in general.
572 *
573 * <a name="ProcessLifecycle"></a>
574 * <h3>Process Lifecycle</h3>
575 *
576 * <p>The Android system attempts to keep application process around for as
577 * long as possible, but eventually will need to remove old processes when
578 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
579 * Lifecycle</a>, the decision about which process to remove is intimately
580 * tied to the state of the user's interaction with it. In general, there
581 * are four states a process can be in based on the activities running in it,
582 * listed here in order of importance. The system will kill less important
583 * processes (the last ones) before it resorts to killing more important
584 * processes (the first ones).
585 *
586 * <ol>
587 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
588 * that the user is currently interacting with) is considered the most important.
589 * Its process will only be killed as a last resort, if it uses more memory
590 * than is available on the device. Generally at this point the device has
591 * reached a memory paging state, so this is required in order to keep the user
592 * interface responsive.
593 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
594 * but not in the foreground, such as one sitting behind a foreground dialog)
595 * is considered extremely important and will not be killed unless that is
596 * required to keep the foreground activity running.
597 * <li> <p>A <b>background activity</b> (an activity that is not visible to
598 * the user and has been paused) is no longer critical, so the system may
599 * safely kill its process to reclaim memory for other foreground or
600 * visible processes. If its process needs to be killed, when the user navigates
601 * back to the activity (making it visible on the screen again), its
602 * {@link #onCreate} method will be called with the savedInstanceState it had previously
603 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
604 * state as the user last left it.
605 * <li> <p>An <b>empty process</b> is one hosting no activities or other
606 * application components (such as {@link Service} or
607 * {@link android.content.BroadcastReceiver} classes). These are killed very
608 * quickly by the system as memory becomes low. For this reason, any
609 * background operation you do outside of an activity must be executed in the
610 * context of an activity BroadcastReceiver or Service to ensure that the system
611 * knows it needs to keep your process around.
612 * </ol>
613 *
614 * <p>Sometimes an Activity may need to do a long-running operation that exists
615 * independently of the activity lifecycle itself. An example may be a camera
616 * application that allows you to upload a picture to a web site. The upload
617 * may take a long time, and the application should allow the user to leave
618 * the application will it is executing. To accomplish this, your Activity
619 * should start a {@link Service} in which the upload takes place. This allows
620 * the system to properly prioritize your process (considering it to be more
621 * important than other non-visible applications) for the duration of the
622 * upload, independent of whether the original activity is paused, stopped,
623 * or finished.
624 */
625public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700626 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 Window.Callback, KeyEvent.Callback,
628 OnCreateContextMenuListener, ComponentCallbacks {
629 private static final String TAG = "Activity";
630
631 /** Standard activity result: operation canceled. */
632 public static final int RESULT_CANCELED = 0;
633 /** Standard activity result: operation succeeded. */
634 public static final int RESULT_OK = -1;
635 /** Start of user-defined activity results. */
636 public static final int RESULT_FIRST_USER = 1;
637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700639 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
641 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
642 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800643 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800645 private static class ManagedDialog {
646 Dialog mDialog;
647 Bundle mArgs;
648 }
649 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650
651 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
652 private Instrumentation mInstrumentation;
653 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700654 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 /*package*/ String mEmbeddedID;
656 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700657 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 private ComponentName mComponent;
659 /*package*/ ActivityInfo mActivityInfo;
660 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 Activity mParent;
662 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700663 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700664 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600665 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 private boolean mStopped;
667 boolean mFinished;
668 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700669 /** true if the activity is going through a transient pause */
670 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500671 /** true if the activity is being destroyed in order to recreate it with a new configuration */
672 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 /*package*/ int mConfigChangeFlags;
674 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100675 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700677 static final class NonConfigurationInstances {
678 Object activity;
679 HashMap<String, Object> children;
680 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700681 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700682 }
683 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 private Window mWindow;
686
687 private WindowManager mWindowManager;
688 /*package*/ View mDecor = null;
689 /*package*/ boolean mWindowAdded = false;
690 /*package*/ boolean mVisibleFromServer = false;
691 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700692 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693
694 private CharSequence mTitle;
695 private int mTitleColor = 0;
696
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700697 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700698
Dianne Hackborn4911b782010-07-15 12:54:39 -0700699 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
700 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 private static final class ManagedCursor {
703 ManagedCursor(Cursor cursor) {
704 mCursor = cursor;
705 mReleased = false;
706 mUpdated = false;
707 }
708
709 private final Cursor mCursor;
710 private boolean mReleased;
711 private boolean mUpdated;
712 }
713 private final ArrayList<ManagedCursor> mManagedCursors =
714 new ArrayList<ManagedCursor>();
715
716 // protected by synchronized (this)
717 int mResultCode = RESULT_CANCELED;
718 Intent mResultData = null;
719
720 private boolean mTitleReady = false;
721
722 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
723 private SpannableStringBuilder mDefaultKeySsb = null;
724
725 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
726
727 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700728 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 /** Return the intent that started this activity. */
731 public Intent getIntent() {
732 return mIntent;
733 }
734
735 /**
736 * Change the intent returned by {@link #getIntent}. This holds a
737 * reference to the given intent; it does not copy it. Often used in
738 * conjunction with {@link #onNewIntent}.
739 *
740 * @param newIntent The new Intent object to return from getIntent
741 *
742 * @see #getIntent
743 * @see #onNewIntent
744 */
745 public void setIntent(Intent newIntent) {
746 mIntent = newIntent;
747 }
748
749 /** Return the application that owns this activity. */
750 public final Application getApplication() {
751 return mApplication;
752 }
753
754 /** Is this activity embedded inside of another activity? */
755 public final boolean isChild() {
756 return mParent != null;
757 }
758
759 /** Return the parent activity if this view is an embedded child. */
760 public final Activity getParent() {
761 return mParent;
762 }
763
764 /** Retrieve the window manager for showing custom windows. */
765 public WindowManager getWindowManager() {
766 return mWindowManager;
767 }
768
769 /**
770 * Retrieve the current {@link android.view.Window} for the activity.
771 * This can be used to directly access parts of the Window API that
772 * are not available through Activity/Screen.
773 *
774 * @return Window The current window, or null if the activity is not
775 * visual.
776 */
777 public Window getWindow() {
778 return mWindow;
779 }
780
781 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700782 * Return the LoaderManager for this fragment, creating it if needed.
783 */
784 public LoaderManager getLoaderManager() {
785 if (mLoaderManager != null) {
786 return mLoaderManager;
787 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700788 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700789 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700790 return mLoaderManager;
791 }
792
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700793 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700794 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700795 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700796 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700797 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700798 if (lm == null) {
799 if (create) {
800 lm = new LoaderManagerImpl(this, started);
801 mAllLoaderManagers.put(index, lm);
802 }
803 } else {
804 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700805 }
806 return lm;
807 }
808
809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 * Calls {@link android.view.Window#getCurrentFocus} on the
811 * Window of this Activity to return the currently focused view.
812 *
813 * @return View The current View with focus or null.
814 *
815 * @see #getWindow
816 * @see android.view.Window#getCurrentFocus
817 */
818 public View getCurrentFocus() {
819 return mWindow != null ? mWindow.getCurrentFocus() : null;
820 }
821
822 @Override
823 public int getWallpaperDesiredMinimumWidth() {
824 int width = super.getWallpaperDesiredMinimumWidth();
825 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
826 }
827
828 @Override
829 public int getWallpaperDesiredMinimumHeight() {
830 int height = super.getWallpaperDesiredMinimumHeight();
831 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
832 }
833
834 /**
835 * Called when the activity is starting. This is where most initialization
836 * should go: calling {@link #setContentView(int)} to inflate the
837 * activity's UI, using {@link #findViewById} to programmatically interact
838 * with widgets in the UI, calling
839 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
840 * cursors for data being displayed, etc.
841 *
842 * <p>You can call {@link #finish} from within this function, in
843 * which case onDestroy() will be immediately called without any of the rest
844 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
845 * {@link #onPause}, etc) executing.
846 *
847 * <p><em>Derived classes must call through to the super class's
848 * implementation of this method. If they do not, an exception will be
849 * thrown.</em></p>
850 *
851 * @param savedInstanceState If the activity is being re-initialized after
852 * previously being shut down then this Bundle contains the data it most
853 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
854 *
855 * @see #onStart
856 * @see #onSaveInstanceState
857 * @see #onRestoreInstanceState
858 * @see #onPostCreate
859 */
860 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700861 if (mLastNonConfigurationInstances != null) {
862 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
863 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700864 if (savedInstanceState != null) {
865 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
866 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
867 ? mLastNonConfigurationInstances.fragments : null);
868 }
869 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 mCalled = true;
871 }
872
873 /**
874 * The hook for {@link ActivityThread} to restore the state of this activity.
875 *
876 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
877 * {@link #restoreManagedDialogs(android.os.Bundle)}.
878 *
879 * @param savedInstanceState contains the saved state
880 */
881 final void performRestoreInstanceState(Bundle savedInstanceState) {
882 onRestoreInstanceState(savedInstanceState);
883 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 }
885
886 /**
887 * This method is called after {@link #onStart} when the activity is
888 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800889 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 * to restore their state, but it is sometimes convenient to do it here
891 * after all of the initialization has been done or to allow subclasses to
892 * decide whether to use your default implementation. The default
893 * implementation of this method performs a restore of any view state that
894 * had previously been frozen by {@link #onSaveInstanceState}.
895 *
896 * <p>This method is called between {@link #onStart} and
897 * {@link #onPostCreate}.
898 *
899 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
900 *
901 * @see #onCreate
902 * @see #onPostCreate
903 * @see #onResume
904 * @see #onSaveInstanceState
905 */
906 protected void onRestoreInstanceState(Bundle savedInstanceState) {
907 if (mWindow != null) {
908 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
909 if (windowState != null) {
910 mWindow.restoreHierarchyState(windowState);
911 }
912 }
913 }
914
915 /**
916 * Restore the state of any saved managed dialogs.
917 *
918 * @param savedInstanceState The bundle to restore from.
919 */
920 private void restoreManagedDialogs(Bundle savedInstanceState) {
921 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
922 if (b == null) {
923 return;
924 }
925
926 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
927 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800928 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 for (int i = 0; i < numDialogs; i++) {
930 final Integer dialogId = ids[i];
931 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
932 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700933 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
934 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800935 final ManagedDialog md = new ManagedDialog();
936 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
937 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
938 if (md.mDialog != null) {
939 mManagedDialogs.put(dialogId, md);
940 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
941 md.mDialog.onRestoreInstanceState(dialogState);
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
944 }
945 }
946
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800947 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
948 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700949 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800950 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700951 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700952 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700953 return dialog;
954 }
955
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800956 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 return SAVED_DIALOG_KEY_PREFIX + key;
958 }
959
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800960 private static String savedDialogArgsKeyFor(int key) {
961 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963
964 /**
965 * Called when activity start-up is complete (after {@link #onStart}
966 * and {@link #onRestoreInstanceState} have been called). Applications will
967 * generally not implement this method; it is intended for system
968 * classes to do final initialization after application code has run.
969 *
970 * <p><em>Derived classes must call through to the super class's
971 * implementation of this method. If they do not, an exception will be
972 * thrown.</em></p>
973 *
974 * @param savedInstanceState If the activity is being re-initialized after
975 * previously being shut down then this Bundle contains the data it most
976 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
977 * @see #onCreate
978 */
979 protected void onPostCreate(Bundle savedInstanceState) {
980 if (!isChild()) {
981 mTitleReady = true;
982 onTitleChanged(getTitle(), getTitleColor());
983 }
984 mCalled = true;
985 }
986
987 /**
988 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
989 * the activity had been stopped, but is now again being displayed to the
990 * user. It will be followed by {@link #onResume}.
991 *
992 * <p><em>Derived classes must call through to the super class's
993 * implementation of this method. If they do not, an exception will be
994 * thrown.</em></p>
995 *
996 * @see #onCreate
997 * @see #onStop
998 * @see #onResume
999 */
1000 protected void onStart() {
1001 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07001002
1003 if (!mLoadersStarted) {
1004 mLoadersStarted = true;
1005 if (mLoaderManager != null) {
1006 mLoaderManager.doStart();
1007 } else if (!mCheckedForLoaderManager) {
1008 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
1009 }
1010 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
1014 /**
1015 * Called after {@link #onStop} when the current activity is being
1016 * re-displayed to the user (the user has navigated back to it). It will
1017 * be followed by {@link #onStart} and then {@link #onResume}.
1018 *
1019 * <p>For activities that are using raw {@link Cursor} objects (instead of
1020 * creating them through
1021 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1022 * this is usually the place
1023 * where the cursor should be requeried (because you had deactivated it in
1024 * {@link #onStop}.
1025 *
1026 * <p><em>Derived classes must call through to the super class's
1027 * implementation of this method. If they do not, an exception will be
1028 * thrown.</em></p>
1029 *
1030 * @see #onStop
1031 * @see #onStart
1032 * @see #onResume
1033 */
1034 protected void onRestart() {
1035 mCalled = true;
1036 }
1037
1038 /**
1039 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1040 * {@link #onPause}, for your activity to start interacting with the user.
1041 * This is a good place to begin animations, open exclusive-access devices
1042 * (such as the camera), etc.
1043 *
1044 * <p>Keep in mind that onResume is not the best indicator that your activity
1045 * is visible to the user; a system window such as the keyguard may be in
1046 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1047 * activity is visible to the user (for example, to resume a game).
1048 *
1049 * <p><em>Derived classes must call through to the super class's
1050 * implementation of this method. If they do not, an exception will be
1051 * thrown.</em></p>
1052 *
1053 * @see #onRestoreInstanceState
1054 * @see #onRestart
1055 * @see #onPostResume
1056 * @see #onPause
1057 */
1058 protected void onResume() {
1059 mCalled = true;
1060 }
1061
1062 /**
1063 * Called when activity resume is complete (after {@link #onResume} has
1064 * been called). Applications will generally not implement this method;
1065 * it is intended for system classes to do final setup after application
1066 * resume code has run.
1067 *
1068 * <p><em>Derived classes must call through to the super class's
1069 * implementation of this method. If they do not, an exception will be
1070 * thrown.</em></p>
1071 *
1072 * @see #onResume
1073 */
1074 protected void onPostResume() {
1075 final Window win = getWindow();
1076 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001077 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 mCalled = true;
1079 }
1080
1081 /**
1082 * This is called for activities that set launchMode to "singleTop" in
1083 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1084 * flag when calling {@link #startActivity}. In either case, when the
1085 * activity is re-launched while at the top of the activity stack instead
1086 * of a new instance of the activity being started, onNewIntent() will be
1087 * called on the existing instance with the Intent that was used to
1088 * re-launch it.
1089 *
1090 * <p>An activity will always be paused before receiving a new intent, so
1091 * you can count on {@link #onResume} being called after this method.
1092 *
1093 * <p>Note that {@link #getIntent} still returns the original Intent. You
1094 * can use {@link #setIntent} to update it to this new Intent.
1095 *
1096 * @param intent The new intent that was started for the activity.
1097 *
1098 * @see #getIntent
1099 * @see #setIntent
1100 * @see #onResume
1101 */
1102 protected void onNewIntent(Intent intent) {
1103 }
1104
1105 /**
1106 * The hook for {@link ActivityThread} to save the state of this activity.
1107 *
1108 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1109 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1110 *
1111 * @param outState The bundle to save the state to.
1112 */
1113 final void performSaveInstanceState(Bundle outState) {
1114 onSaveInstanceState(outState);
1115 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117
1118 /**
1119 * Called to retrieve per-instance state from an activity before being killed
1120 * so that the state can be restored in {@link #onCreate} or
1121 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1122 * will be passed to both).
1123 *
1124 * <p>This method is called before an activity may be killed so that when it
1125 * comes back some time in the future it can restore its state. For example,
1126 * if activity B is launched in front of activity A, and at some point activity
1127 * A is killed to reclaim resources, activity A will have a chance to save the
1128 * current state of its user interface via this method so that when the user
1129 * returns to activity A, the state of the user interface can be restored
1130 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1131 *
1132 * <p>Do not confuse this method with activity lifecycle callbacks such as
1133 * {@link #onPause}, which is always called when an activity is being placed
1134 * in the background or on its way to destruction, or {@link #onStop} which
1135 * is called before destruction. One example of when {@link #onPause} and
1136 * {@link #onStop} is called and not this method is when a user navigates back
1137 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1138 * on B because that particular instance will never be restored, so the
1139 * system avoids calling it. An example when {@link #onPause} is called and
1140 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1141 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1142 * killed during the lifetime of B since the state of the user interface of
1143 * A will stay intact.
1144 *
1145 * <p>The default implementation takes care of most of the UI per-instance
1146 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1147 * view in the hierarchy that has an id, and by saving the id of the currently
1148 * focused view (all of which is restored by the default implementation of
1149 * {@link #onRestoreInstanceState}). If you override this method to save additional
1150 * information not captured by each individual view, you will likely want to
1151 * call through to the default implementation, otherwise be prepared to save
1152 * all of the state of each view yourself.
1153 *
1154 * <p>If called, this method will occur before {@link #onStop}. There are
1155 * no guarantees about whether it will occur before or after {@link #onPause}.
1156 *
1157 * @param outState Bundle in which to place your saved state.
1158 *
1159 * @see #onCreate
1160 * @see #onRestoreInstanceState
1161 * @see #onPause
1162 */
1163 protected void onSaveInstanceState(Bundle outState) {
1164 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001165 Parcelable p = mFragments.saveAllState();
1166 if (p != null) {
1167 outState.putParcelable(FRAGMENTS_TAG, p);
1168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
1171 /**
1172 * Save the state of any managed dialogs.
1173 *
1174 * @param outState place to store the saved state.
1175 */
1176 private void saveManagedDialogs(Bundle outState) {
1177 if (mManagedDialogs == null) {
1178 return;
1179 }
1180
1181 final int numDialogs = mManagedDialogs.size();
1182 if (numDialogs == 0) {
1183 return;
1184 }
1185
1186 Bundle dialogState = new Bundle();
1187
1188 int[] ids = new int[mManagedDialogs.size()];
1189
1190 // save each dialog's bundle, gather the ids
1191 for (int i = 0; i < numDialogs; i++) {
1192 final int key = mManagedDialogs.keyAt(i);
1193 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001194 final ManagedDialog md = mManagedDialogs.valueAt(i);
1195 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1196 if (md.mArgs != null) {
1197 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
1200
1201 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1202 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1203 }
1204
1205
1206 /**
1207 * Called as part of the activity lifecycle when an activity is going into
1208 * the background, but has not (yet) been killed. The counterpart to
1209 * {@link #onResume}.
1210 *
1211 * <p>When activity B is launched in front of activity A, this callback will
1212 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1213 * so be sure to not do anything lengthy here.
1214 *
1215 * <p>This callback is mostly used for saving any persistent state the
1216 * activity is editing, to present a "edit in place" model to the user and
1217 * making sure nothing is lost if there are not enough resources to start
1218 * the new activity without first killing this one. This is also a good
1219 * place to do things like stop animations and other things that consume a
1220 * noticeable mount of CPU in order to make the switch to the next activity
1221 * as fast as possible, or to close resources that are exclusive access
1222 * such as the camera.
1223 *
1224 * <p>In situations where the system needs more memory it may kill paused
1225 * processes to reclaim resources. Because of this, you should be sure
1226 * that all of your state is saved by the time you return from
1227 * this function. In general {@link #onSaveInstanceState} is used to save
1228 * per-instance state in the activity and this method is used to store
1229 * global persistent data (in content providers, files, etc.)
1230 *
1231 * <p>After receiving this call you will usually receive a following call
1232 * to {@link #onStop} (after the next activity has been resumed and
1233 * displayed), however in some cases there will be a direct call back to
1234 * {@link #onResume} without going through the stopped state.
1235 *
1236 * <p><em>Derived classes must call through to the super class's
1237 * implementation of this method. If they do not, an exception will be
1238 * thrown.</em></p>
1239 *
1240 * @see #onResume
1241 * @see #onSaveInstanceState
1242 * @see #onStop
1243 */
1244 protected void onPause() {
1245 mCalled = true;
1246 }
1247
1248 /**
1249 * Called as part of the activity lifecycle when an activity is about to go
1250 * into the background as the result of user choice. For example, when the
1251 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1252 * when an incoming phone call causes the in-call Activity to be automatically
1253 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1254 * the activity being interrupted. In cases when it is invoked, this method
1255 * is called right before the activity's {@link #onPause} callback.
1256 *
1257 * <p>This callback and {@link #onUserInteraction} are intended to help
1258 * activities manage status bar notifications intelligently; specifically,
1259 * for helping activities determine the proper time to cancel a notfication.
1260 *
1261 * @see #onUserInteraction()
1262 */
1263 protected void onUserLeaveHint() {
1264 }
1265
1266 /**
1267 * Generate a new thumbnail for this activity. This method is called before
1268 * pausing the activity, and should draw into <var>outBitmap</var> the
1269 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1270 * can use the given <var>canvas</var>, which is configured to draw into the
1271 * bitmap, for rendering if desired.
1272 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001273 * <p>The default implementation returns fails and does not draw a thumbnail;
1274 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 *
1276 * @param outBitmap The bitmap to contain the thumbnail.
1277 * @param canvas Can be used to render into the bitmap.
1278 *
1279 * @return Return true if you have drawn into the bitmap; otherwise after
1280 * you return it will be filled with a default thumbnail.
1281 *
1282 * @see #onCreateDescription
1283 * @see #onSaveInstanceState
1284 * @see #onPause
1285 */
1286 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001287 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289
1290 /**
1291 * Generate a new description for this activity. This method is called
1292 * before pausing the activity and can, if desired, return some textual
1293 * description of its current state to be displayed to the user.
1294 *
1295 * <p>The default implementation returns null, which will cause you to
1296 * inherit the description from the previous activity. If all activities
1297 * return null, generally the label of the top activity will be used as the
1298 * description.
1299 *
1300 * @return A description of what the user is doing. It should be short and
1301 * sweet (only a few words).
1302 *
1303 * @see #onCreateThumbnail
1304 * @see #onSaveInstanceState
1305 * @see #onPause
1306 */
1307 public CharSequence onCreateDescription() {
1308 return null;
1309 }
1310
1311 /**
1312 * Called when you are no longer visible to the user. You will next
1313 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1314 * depending on later user activity.
1315 *
1316 * <p>Note that this method may never be called, in low memory situations
1317 * where the system does not have enough memory to keep your activity's
1318 * process running after its {@link #onPause} method is called.
1319 *
1320 * <p><em>Derived classes must call through to the super class's
1321 * implementation of this method. If they do not, an exception will be
1322 * thrown.</em></p>
1323 *
1324 * @see #onRestart
1325 * @see #onResume
1326 * @see #onSaveInstanceState
1327 * @see #onDestroy
1328 */
1329 protected void onStop() {
Adam Powell50efbed2011-02-08 16:20:15 -08001330 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 mCalled = true;
1332 }
1333
1334 /**
1335 * Perform any final cleanup before an activity is destroyed. This can
1336 * happen either because the activity is finishing (someone called
1337 * {@link #finish} on it, or because the system is temporarily destroying
1338 * this instance of the activity to save space. You can distinguish
1339 * between these two scenarios with the {@link #isFinishing} method.
1340 *
1341 * <p><em>Note: do not count on this method being called as a place for
1342 * saving data! For example, if an activity is editing data in a content
1343 * provider, those edits should be committed in either {@link #onPause} or
1344 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1345 * free resources like threads that are associated with an activity, so
1346 * that a destroyed activity does not leave such things around while the
1347 * rest of its application is still running. There are situations where
1348 * the system will simply kill the activity's hosting process without
1349 * calling this method (or any others) in it, so it should not be used to
1350 * do things that are intended to remain around after the process goes
1351 * away.
1352 *
1353 * <p><em>Derived classes must call through to the super class's
1354 * implementation of this method. If they do not, an exception will be
1355 * thrown.</em></p>
1356 *
1357 * @see #onPause
1358 * @see #onStop
1359 * @see #finish
1360 * @see #isFinishing
1361 */
1362 protected void onDestroy() {
1363 mCalled = true;
1364
1365 // dismiss any dialogs we are managing.
1366 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 final int numDialogs = mManagedDialogs.size();
1368 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001369 final ManagedDialog md = mManagedDialogs.valueAt(i);
1370 if (md.mDialog.isShowing()) {
1371 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001374 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
1377 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001378 synchronized (mManagedCursors) {
1379 int numCursors = mManagedCursors.size();
1380 for (int i = 0; i < numCursors; i++) {
1381 ManagedCursor c = mManagedCursors.get(i);
1382 if (c != null) {
1383 c.mCursor.close();
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001386 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Amith Yamasani49860442010-03-17 20:54:10 -07001388
1389 // Close any open search dialog
1390 if (mSearchManager != null) {
1391 mSearchManager.stopSearch();
1392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394
1395 /**
1396 * Called by the system when the device configuration changes while your
1397 * activity is running. Note that this will <em>only</em> be called if
1398 * you have selected configurations you would like to handle with the
1399 * {@link android.R.attr#configChanges} attribute in your manifest. If
1400 * any configuration change occurs that is not selected to be reported
1401 * by that attribute, then instead of reporting it the system will stop
1402 * and restart the activity (to have it launched with the new
1403 * configuration).
1404 *
1405 * <p>At the time that this function has been called, your Resources
1406 * object will have been updated to return resource values matching the
1407 * new configuration.
1408 *
1409 * @param newConfig The new device configuration.
1410 */
1411 public void onConfigurationChanged(Configuration newConfig) {
1412 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001413
Dianne Hackborn9d071802010-12-08 14:49:15 -08001414 mFragments.dispatchConfigurationChanged(newConfig);
1415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (mWindow != null) {
1417 // Pass the configuration changed event to the window
1418 mWindow.onConfigurationChanged(newConfig);
1419 }
1420 }
1421
1422 /**
1423 * If this activity is being destroyed because it can not handle a
1424 * configuration parameter being changed (and thus its
1425 * {@link #onConfigurationChanged(Configuration)} method is
1426 * <em>not</em> being called), then you can use this method to discover
1427 * the set of changes that have occurred while in the process of being
1428 * destroyed. Note that there is no guarantee that these will be
1429 * accurate (other changes could have happened at any time), so you should
1430 * only use this as an optimization hint.
1431 *
1432 * @return Returns a bit field of the configuration parameters that are
1433 * changing, as defined by the {@link android.content.res.Configuration}
1434 * class.
1435 */
1436 public int getChangingConfigurations() {
1437 return mConfigChangeFlags;
1438 }
1439
1440 /**
1441 * Retrieve the non-configuration instance data that was previously
1442 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1443 * be available from the initial {@link #onCreate} and
1444 * {@link #onStart} calls to the new instance, allowing you to extract
1445 * any useful dynamic state from the previous instance.
1446 *
1447 * <p>Note that the data you retrieve here should <em>only</em> be used
1448 * as an optimization for handling configuration changes. You should always
1449 * be able to handle getting a null pointer back, and an activity must
1450 * still be able to restore itself to its previous state (through the
1451 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1452 * function returns null.
1453 *
1454 * @return Returns the object previously returned by
1455 * {@link #onRetainNonConfigurationInstance()}.
1456 */
1457 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001458 return mLastNonConfigurationInstances != null
1459 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461
1462 /**
1463 * Called by the system, as part of destroying an
1464 * activity due to a configuration change, when it is known that a new
1465 * instance will immediately be created for the new configuration. You
1466 * can return any object you like here, including the activity instance
1467 * itself, which can later be retrieved by calling
1468 * {@link #getLastNonConfigurationInstance()} in the new activity
1469 * instance.
1470 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001471 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1472 * or later, consider instead using a {@link Fragment} with
1473 * {@link Fragment#setRetainInstance(boolean)
1474 * Fragment.setRetainInstance(boolean}.</em>
1475 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 * <p>This function is called purely as an optimization, and you must
1477 * not rely on it being called. When it is called, a number of guarantees
1478 * will be made to help optimize configuration switching:
1479 * <ul>
1480 * <li> The function will be called between {@link #onStop} and
1481 * {@link #onDestroy}.
1482 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001483 * created after this one's {@link #onDestroy()} is called. In particular,
1484 * <em>no</em> messages will be dispatched during this time (when the returned
1485 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 * <li> The object you return here will <em>always</em> be available from
1487 * the {@link #getLastNonConfigurationInstance()} method of the following
1488 * activity instance as described there.
1489 * </ul>
1490 *
1491 * <p>These guarantees are designed so that an activity can use this API
1492 * to propagate extensive state from the old to new activity instance, from
1493 * loaded bitmaps, to network connections, to evenly actively running
1494 * threads. Note that you should <em>not</em> propagate any data that
1495 * may change based on the configuration, including any data loaded from
1496 * resources such as strings, layouts, or drawables.
1497 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001498 * <p>The guarantee of no message handling during the switch to the next
1499 * activity simplifies use with active objects. For example if your retained
1500 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1501 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1502 * not be called from the call here until you execute the next instance's
1503 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1504 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1505 * running in a separate thread.)
1506 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 * @return Return any Object holding the desired state to propagate to the
1508 * next activity instance.
1509 */
1510 public Object onRetainNonConfigurationInstance() {
1511 return null;
1512 }
1513
1514 /**
1515 * Retrieve the non-configuration instance data that was previously
1516 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1517 * be available from the initial {@link #onCreate} and
1518 * {@link #onStart} calls to the new instance, allowing you to extract
1519 * any useful dynamic state from the previous instance.
1520 *
1521 * <p>Note that the data you retrieve here should <em>only</em> be used
1522 * as an optimization for handling configuration changes. You should always
1523 * be able to handle getting a null pointer back, and an activity must
1524 * still be able to restore itself to its previous state (through the
1525 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1526 * function returns null.
1527 *
1528 * @return Returns the object previously returned by
1529 * {@link #onRetainNonConfigurationChildInstances()}
1530 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001531 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1532 return mLastNonConfigurationInstances != null
1533 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
1536 /**
1537 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1538 * it should return either a mapping from child activity id strings to arbitrary objects,
1539 * or null. This method is intended to be used by Activity framework subclasses that control a
1540 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1541 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1542 */
1543 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1544 return null;
1545 }
1546
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001547 NonConfigurationInstances retainNonConfigurationInstances() {
1548 Object activity = onRetainNonConfigurationInstance();
1549 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1550 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001551 boolean retainLoaders = false;
1552 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001553 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001554 // have nothing useful to retain.
1555 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001556 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001557 if (lm.mRetaining) {
1558 retainLoaders = true;
1559 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001560 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001561 mAllLoaderManagers.removeAt(i);
1562 }
1563 }
1564 }
1565 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001566 return null;
1567 }
1568
1569 NonConfigurationInstances nci = new NonConfigurationInstances();
1570 nci.activity = activity;
1571 nci.children = children;
1572 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001573 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001574 return nci;
1575 }
1576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 public void onLowMemory() {
1578 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001579 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
1582 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001583 * Return the FragmentManager for interacting with fragments associated
1584 * with this activity.
1585 */
1586 public FragmentManager getFragmentManager() {
1587 return mFragments;
1588 }
1589
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001590 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001591 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001592 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001593 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1594 if (lm != null) {
1595 lm.doDestroy();
1596 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001597 mAllLoaderManagers.remove(index);
1598 }
1599 }
1600
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001601 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001602 * Called when a Fragment is being attached to this activity, immediately
1603 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1604 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1605 */
1606 public void onAttachFragment(Fragment fragment) {
1607 }
1608
1609 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 * Wrapper around
1611 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1612 * that gives the resulting {@link Cursor} to call
1613 * {@link #startManagingCursor} so that the activity will manage its
1614 * lifecycle for you.
1615 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001616 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1617 * or later, consider instead using {@link LoaderManager} instead, available
1618 * via {@link #getLoaderManager()}.</em>
1619 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 * @param uri The URI of the content provider to query.
1621 * @param projection List of columns to return.
1622 * @param selection SQL WHERE clause.
1623 * @param sortOrder SQL ORDER BY clause.
1624 *
1625 * @return The Cursor that was returned by query().
1626 *
1627 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1628 * @see #startManagingCursor
1629 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001630 *
1631 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 */
Jason parks6ed50de2010-08-25 10:18:50 -05001633 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001634 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1635 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1637 if (c != null) {
1638 startManagingCursor(c);
1639 }
1640 return c;
1641 }
1642
1643 /**
1644 * Wrapper around
1645 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1646 * that gives the resulting {@link Cursor} to call
1647 * {@link #startManagingCursor} so that the activity will manage its
1648 * lifecycle for you.
1649 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001650 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1651 * or later, consider instead using {@link LoaderManager} instead, available
1652 * via {@link #getLoaderManager()}.</em>
1653 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 * @param uri The URI of the content provider to query.
1655 * @param projection List of columns to return.
1656 * @param selection SQL WHERE clause.
1657 * @param selectionArgs The arguments to selection, if any ?s are pesent
1658 * @param sortOrder SQL ORDER BY clause.
1659 *
1660 * @return The Cursor that was returned by query().
1661 *
1662 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1663 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001664 *
1665 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 */
Jason parks6ed50de2010-08-25 10:18:50 -05001667 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001668 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1669 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1671 if (c != null) {
1672 startManagingCursor(c);
1673 }
1674 return c;
1675 }
1676
1677 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 * This method allows the activity to take care of managing the given
1679 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1680 * That is, when the activity is stopped it will automatically call
1681 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1682 * it will call {@link Cursor#requery} for you. When the activity is
1683 * destroyed, all managed Cursors will be closed automatically.
1684 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001685 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1686 * or later, consider instead using {@link LoaderManager} instead, available
1687 * via {@link #getLoaderManager()}.</em>
1688 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 * @param c The Cursor to be managed.
1690 *
1691 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1692 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001693 *
1694 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 */
Jason parks6ed50de2010-08-25 10:18:50 -05001696 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 public void startManagingCursor(Cursor c) {
1698 synchronized (mManagedCursors) {
1699 mManagedCursors.add(new ManagedCursor(c));
1700 }
1701 }
1702
1703 /**
1704 * Given a Cursor that was previously given to
1705 * {@link #startManagingCursor}, stop the activity's management of that
1706 * cursor.
1707 *
1708 * @param c The Cursor that was being managed.
1709 *
1710 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001711 *
1712 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 */
Jason parks6ed50de2010-08-25 10:18:50 -05001714 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 public void stopManagingCursor(Cursor c) {
1716 synchronized (mManagedCursors) {
1717 final int N = mManagedCursors.size();
1718 for (int i=0; i<N; i++) {
1719 ManagedCursor mc = mManagedCursors.get(i);
1720 if (mc.mCursor == c) {
1721 mManagedCursors.remove(i);
1722 break;
1723 }
1724 }
1725 }
1726 }
1727
1728 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001729 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1730 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001731 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001733 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736
1737 /**
1738 * Finds a view that was identified by the id attribute from the XML that
1739 * was processed in {@link #onCreate}.
1740 *
1741 * @return The view if found or null otherwise.
1742 */
1743 public View findViewById(int id) {
1744 return getWindow().findViewById(id);
1745 }
Adam Powell33b97432010-04-20 10:01:14 -07001746
1747 /**
1748 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001749 *
Adam Powell33b97432010-04-20 10:01:14 -07001750 * @return The Activity's ActionBar, or null if it does not have one.
1751 */
1752 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001753 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001754 return mActionBar;
1755 }
1756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 /**
Adam Powell33b97432010-04-20 10:01:14 -07001758 * Creates a new ActionBar, locates the inflated ActionBarView,
1759 * initializes the ActionBar with the view, and sets mActionBar.
1760 */
1761 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001762 Window window = getWindow();
Adam Powella593d982011-05-13 14:09:54 -07001763
1764 // Initializing the window decor can change window feature flags.
1765 // Make sure that we have the correct set before performing the test below.
1766 window.getDecorView();
1767
Adam Powell9b4c8042010-08-10 15:36:44 -07001768 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001769 return;
1770 }
1771
Adam Powell661c9082010-07-02 10:09:44 -07001772 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001773 }
1774
1775 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 * Set the activity content from a layout resource. The resource will be
1777 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08001778 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a62011-01-20 10:59:28 -08001780 *
1781 * @see #setContentView(android.view.View)
1782 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 */
1784 public void setContentView(int layoutResID) {
1785 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001786 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788
1789 /**
1790 * Set the activity content to an explicit view. This view is placed
1791 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001792 * view hierarchy. When calling this method, the layout parameters of the
1793 * specified view are ignored. Both the width and the height of the view are
1794 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1795 * your own layout parameters, invoke
1796 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1797 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 *
1799 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08001800 *
1801 * @see #setContentView(int)
1802 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 */
1804 public void setContentView(View view) {
1805 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001806 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808
1809 /**
1810 * Set the activity content to an explicit view. This view is placed
1811 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001812 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 *
1814 * @param view The desired content to display.
1815 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08001816 *
1817 * @see #setContentView(android.view.View)
1818 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 */
1820 public void setContentView(View view, ViewGroup.LayoutParams params) {
1821 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001822 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
1825 /**
1826 * Add an additional content view to the activity. Added after any existing
1827 * ones in the activity -- existing views are NOT removed.
1828 *
1829 * @param view The desired content to display.
1830 * @param params Layout parameters for the view.
1831 */
1832 public void addContentView(View view, ViewGroup.LayoutParams params) {
1833 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001834 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836
1837 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001838 * Sets whether this activity is finished when touched outside its window's
1839 * bounds.
1840 */
1841 public void setFinishOnTouchOutside(boolean finish) {
1842 mWindow.setCloseOnTouchOutside(finish);
1843 }
1844
1845 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1847 * keys.
1848 *
1849 * @see #setDefaultKeyMode
1850 */
1851 static public final int DEFAULT_KEYS_DISABLE = 0;
1852 /**
1853 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1854 * key handling.
1855 *
1856 * @see #setDefaultKeyMode
1857 */
1858 static public final int DEFAULT_KEYS_DIALER = 1;
1859 /**
1860 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1861 * default key handling.
1862 *
1863 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1864 *
1865 * @see #setDefaultKeyMode
1866 */
1867 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1868 /**
1869 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1870 * will start an application-defined search. (If the application or activity does not
1871 * actually define a search, the the keys will be ignored.)
1872 *
1873 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1874 *
1875 * @see #setDefaultKeyMode
1876 */
1877 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1878
1879 /**
1880 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1881 * will start a global search (typically web search, but some platforms may define alternate
1882 * methods for global search)
1883 *
1884 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1885 *
1886 * @see #setDefaultKeyMode
1887 */
1888 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1889
1890 /**
1891 * Select the default key handling for this activity. This controls what
1892 * will happen to key events that are not otherwise handled. The default
1893 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1894 * floor. Other modes allow you to launch the dialer
1895 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1896 * menu without requiring the menu key be held down
1897 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1898 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1899 *
1900 * <p>Note that the mode selected here does not impact the default
1901 * handling of system keys, such as the "back" and "menu" keys, and your
1902 * activity and its views always get a first chance to receive and handle
1903 * all application keys.
1904 *
1905 * @param mode The desired default key mode constant.
1906 *
1907 * @see #DEFAULT_KEYS_DISABLE
1908 * @see #DEFAULT_KEYS_DIALER
1909 * @see #DEFAULT_KEYS_SHORTCUT
1910 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1911 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1912 * @see #onKeyDown
1913 */
1914 public final void setDefaultKeyMode(int mode) {
1915 mDefaultKeyMode = mode;
1916
1917 // Some modes use a SpannableStringBuilder to track & dispatch input events
1918 // This list must remain in sync with the switch in onKeyDown()
1919 switch (mode) {
1920 case DEFAULT_KEYS_DISABLE:
1921 case DEFAULT_KEYS_SHORTCUT:
1922 mDefaultKeySsb = null; // not used in these modes
1923 break;
1924 case DEFAULT_KEYS_DIALER:
1925 case DEFAULT_KEYS_SEARCH_LOCAL:
1926 case DEFAULT_KEYS_SEARCH_GLOBAL:
1927 mDefaultKeySsb = new SpannableStringBuilder();
1928 Selection.setSelection(mDefaultKeySsb,0);
1929 break;
1930 default:
1931 throw new IllegalArgumentException();
1932 }
1933 }
1934
1935 /**
1936 * Called when a key was pressed down and not handled by any of the views
1937 * inside of the activity. So, for example, key presses while the cursor
1938 * is inside a TextView will not trigger the event (unless it is a navigation
1939 * to another object) because TextView handles its own key presses.
1940 *
1941 * <p>If the focused view didn't want this event, this method is called.
1942 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001943 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1944 * by calling {@link #onBackPressed()}, though the behavior varies based
1945 * on the application compatibility mode: for
1946 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1947 * it will set up the dispatch to call {@link #onKeyUp} where the action
1948 * will be performed; for earlier applications, it will perform the
1949 * action immediately in on-down, as those versions of the platform
1950 * behaved.
1951 *
1952 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001953 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 *
1955 * @return Return <code>true</code> to prevent this event from being propagated
1956 * further, or <code>false</code> to indicate that you have not handled
1957 * this event and it should continue to be propagated.
1958 * @see #onKeyUp
1959 * @see android.view.KeyEvent
1960 */
1961 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001962 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001963 if (getApplicationInfo().targetSdkVersion
1964 >= Build.VERSION_CODES.ECLAIR) {
1965 event.startTracking();
1966 } else {
1967 onBackPressed();
1968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 return true;
1970 }
1971
1972 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1973 return false;
1974 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001975 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1976 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1977 return true;
1978 }
1979 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 } else {
1981 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1982 boolean clearSpannable = false;
1983 boolean handled;
1984 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1985 clearSpannable = true;
1986 handled = false;
1987 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001988 handled = TextKeyListener.getInstance().onKeyDown(
1989 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if (handled && mDefaultKeySsb.length() > 0) {
1991 // something useable has been typed - dispatch it now.
1992
1993 final String str = mDefaultKeySsb.toString();
1994 clearSpannable = true;
1995
1996 switch (mDefaultKeyMode) {
1997 case DEFAULT_KEYS_DIALER:
1998 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1999 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2000 startActivity(intent);
2001 break;
2002 case DEFAULT_KEYS_SEARCH_LOCAL:
2003 startSearch(str, false, null, false);
2004 break;
2005 case DEFAULT_KEYS_SEARCH_GLOBAL:
2006 startSearch(str, false, null, true);
2007 break;
2008 }
2009 }
2010 }
2011 if (clearSpannable) {
2012 mDefaultKeySsb.clear();
2013 mDefaultKeySsb.clearSpans();
2014 Selection.setSelection(mDefaultKeySsb,0);
2015 }
2016 return handled;
2017 }
2018 }
2019
2020 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002021 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2022 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2023 * the event).
2024 */
2025 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2026 return false;
2027 }
2028
2029 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 * Called when a key was released and not handled by any of the views
2031 * inside of the activity. So, for example, key presses while the cursor
2032 * is inside a TextView will not trigger the event (unless it is a navigation
2033 * to another object) because TextView handles its own key presses.
2034 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002035 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2036 * and go back.
2037 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 * @return Return <code>true</code> to prevent this event from being propagated
2039 * further, or <code>false</code> to indicate that you have not handled
2040 * this event and it should continue to be propagated.
2041 * @see #onKeyDown
2042 * @see KeyEvent
2043 */
2044 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002045 if (getApplicationInfo().targetSdkVersion
2046 >= Build.VERSION_CODES.ECLAIR) {
2047 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2048 && !event.isCanceled()) {
2049 onBackPressed();
2050 return true;
2051 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 return false;
2054 }
2055
2056 /**
2057 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2058 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2059 * the event).
2060 */
2061 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2062 return false;
2063 }
2064
2065 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002066 * Called when the activity has detected the user's press of the back
2067 * key. The default implementation simply finishes the current activity,
2068 * but you can override this to do whatever you want.
2069 */
2070 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002071 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002072 finish();
2073 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002074 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002075
2076 /**
2077 * Called when a key shortcut event is not handled by any of the views in the Activity.
2078 * Override this method to implement global key shortcuts for the Activity.
2079 * Key shortcuts can also be implemented by setting the
2080 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2081 *
2082 * @param keyCode The value in event.getKeyCode().
2083 * @param event Description of the key event.
2084 * @return True if the key shortcut was handled.
2085 */
2086 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2087 return false;
2088 }
2089
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002090 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 * Called when a touch screen event was not handled by any of the views
2092 * under it. This is most useful to process touch events that happen
2093 * outside of your window bounds, where there is no view to receive it.
2094 *
2095 * @param event The touch screen event being processed.
2096 *
2097 * @return Return true if you have consumed the event, false if you haven't.
2098 * The default implementation always returns false.
2099 */
2100 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002101 if (mWindow.shouldCloseOnTouch(this, event)) {
2102 finish();
2103 return true;
2104 }
2105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 return false;
2107 }
2108
2109 /**
2110 * Called when the trackball was moved and not handled by any of the
2111 * views inside of the activity. So, for example, if the trackball moves
2112 * while focus is on a button, you will receive a call here because
2113 * buttons do not normally do anything with trackball events. The call
2114 * here happens <em>before</em> trackball movements are converted to
2115 * DPAD key events, which then get sent back to the view hierarchy, and
2116 * will be processed at the point for things like focus navigation.
2117 *
2118 * @param event The trackball event being processed.
2119 *
2120 * @return Return true if you have consumed the event, false if you haven't.
2121 * The default implementation always returns false.
2122 */
2123 public boolean onTrackballEvent(MotionEvent event) {
2124 return false;
2125 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002126
2127 /**
2128 * Called when a generic motion event was not handled by any of the
2129 * views inside of the activity.
2130 * <p>
Jeff Brown33bbfd22011-02-24 20:55:35 -08002131 * Generic motion events describe joystick movements, mouse hovers, track pad
2132 * touches, scroll wheel movements and other input events. The
Jeff Browncb1404e2011-01-15 18:14:15 -08002133 * {@link MotionEvent#getSource() source} of the motion event specifies
2134 * the class of input that was received. Implementations of this method
2135 * must examine the bits in the source before processing the event.
2136 * The following code example shows how this is done.
Jeff Brown33bbfd22011-02-24 20:55:35 -08002137 * </p><p>
2138 * Generic motion events with source class
2139 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2140 * are delivered to the view under the pointer. All other generic motion events are
2141 * delivered to the focused view.
2142 * </p><p>
2143 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2144 * handle this event.
Jeff Browncb1404e2011-01-15 18:14:15 -08002145 * </p>
Jeff Browncb1404e2011-01-15 18:14:15 -08002146 *
2147 * @param event The generic motion event being processed.
2148 *
2149 * @return Return true if you have consumed the event, false if you haven't.
2150 * The default implementation always returns false.
2151 */
2152 public boolean onGenericMotionEvent(MotionEvent event) {
2153 return false;
2154 }
2155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 /**
2157 * Called whenever a key, touch, or trackball event is dispatched to the
2158 * activity. Implement this method if you wish to know that the user has
2159 * interacted with the device in some way while your activity is running.
2160 * This callback and {@link #onUserLeaveHint} are intended to help
2161 * activities manage status bar notifications intelligently; specifically,
2162 * for helping activities determine the proper time to cancel a notfication.
2163 *
2164 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2165 * be accompanied by calls to {@link #onUserInteraction}. This
2166 * ensures that your activity will be told of relevant user activity such
2167 * as pulling down the notification pane and touching an item there.
2168 *
2169 * <p>Note that this callback will be invoked for the touch down action
2170 * that begins a touch gesture, but may not be invoked for the touch-moved
2171 * and touch-up actions that follow.
2172 *
2173 * @see #onUserLeaveHint()
2174 */
2175 public void onUserInteraction() {
2176 }
2177
2178 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2179 // Update window manager if: we have a view, that view is
2180 // attached to its parent (which will be a RootView), and
2181 // this activity is not embedded.
2182 if (mParent == null) {
2183 View decor = mDecor;
2184 if (decor != null && decor.getParent() != null) {
2185 getWindowManager().updateViewLayout(decor, params);
2186 }
2187 }
2188 }
2189
2190 public void onContentChanged() {
2191 }
2192
2193 /**
2194 * Called when the current {@link Window} of the activity gains or loses
2195 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002196 * to the user. The default implementation clears the key tracking
2197 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002199 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 * is managed independently of activity lifecycles. As such, while focus
2201 * changes will generally have some relation to lifecycle changes (an
2202 * activity that is stopped will not generally get window focus), you
2203 * should not rely on any particular order between the callbacks here and
2204 * those in the other lifecycle methods such as {@link #onResume}.
2205 *
2206 * <p>As a general rule, however, a resumed activity will have window
2207 * focus... unless it has displayed other dialogs or popups that take
2208 * input focus, in which case the activity itself will not have focus
2209 * when the other windows have it. Likewise, the system may display
2210 * system-level windows (such as the status bar notification panel or
2211 * a system alert) which will temporarily take window input focus without
2212 * pausing the foreground activity.
2213 *
2214 * @param hasFocus Whether the window of this activity has focus.
2215 *
2216 * @see #hasWindowFocus()
2217 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002218 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 */
2220 public void onWindowFocusChanged(boolean hasFocus) {
2221 }
2222
2223 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002224 * Called when the main window associated with the activity has been
2225 * attached to the window manager.
2226 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2227 * for more information.
2228 * @see View#onAttachedToWindow
2229 */
2230 public void onAttachedToWindow() {
2231 }
2232
2233 /**
2234 * Called when the main window associated with the activity has been
2235 * detached from the window manager.
2236 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2237 * for more information.
2238 * @see View#onDetachedFromWindow
2239 */
2240 public void onDetachedFromWindow() {
2241 }
2242
2243 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 * Returns true if this activity's <em>main</em> window currently has window focus.
2245 * Note that this is not the same as the view itself having focus.
2246 *
2247 * @return True if this activity's main window currently has window focus.
2248 *
2249 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2250 */
2251 public boolean hasWindowFocus() {
2252 Window w = getWindow();
2253 if (w != null) {
2254 View d = w.getDecorView();
2255 if (d != null) {
2256 return d.hasWindowFocus();
2257 }
2258 }
2259 return false;
2260 }
2261
2262 /**
2263 * Called to process key events. You can override this to intercept all
2264 * key events before they are dispatched to the window. Be sure to call
2265 * this implementation for key events that should be handled normally.
2266 *
2267 * @param event The key event.
2268 *
2269 * @return boolean Return true if this event was consumed.
2270 */
2271 public boolean dispatchKeyEvent(KeyEvent event) {
2272 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002273 Window win = getWindow();
2274 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 return true;
2276 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002277 View decor = mDecor;
2278 if (decor == null) decor = win.getDecorView();
2279 return event.dispatch(this, decor != null
2280 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282
2283 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002284 * Called to process a key shortcut event.
2285 * You can override this to intercept all key shortcut events before they are
2286 * dispatched to the window. Be sure to call this implementation for key shortcut
2287 * events that should be handled normally.
2288 *
2289 * @param event The key shortcut event.
2290 * @return True if this event was consumed.
2291 */
2292 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2293 onUserInteraction();
2294 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2295 return true;
2296 }
2297 return onKeyShortcut(event.getKeyCode(), event);
2298 }
2299
2300 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 * Called to process touch screen events. You can override this to
2302 * intercept all touch screen events before they are dispatched to the
2303 * window. Be sure to call this implementation for touch screen events
2304 * that should be handled normally.
2305 *
2306 * @param ev The touch screen event.
2307 *
2308 * @return boolean Return true if this event was consumed.
2309 */
2310 public boolean dispatchTouchEvent(MotionEvent ev) {
2311 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2312 onUserInteraction();
2313 }
2314 if (getWindow().superDispatchTouchEvent(ev)) {
2315 return true;
2316 }
2317 return onTouchEvent(ev);
2318 }
2319
2320 /**
2321 * Called to process trackball events. You can override this to
2322 * intercept all trackball events before they are dispatched to the
2323 * window. Be sure to call this implementation for trackball events
2324 * that should be handled normally.
2325 *
2326 * @param ev The trackball event.
2327 *
2328 * @return boolean Return true if this event was consumed.
2329 */
2330 public boolean dispatchTrackballEvent(MotionEvent ev) {
2331 onUserInteraction();
2332 if (getWindow().superDispatchTrackballEvent(ev)) {
2333 return true;
2334 }
2335 return onTrackballEvent(ev);
2336 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002337
Jeff Browncb1404e2011-01-15 18:14:15 -08002338 /**
2339 * Called to process generic motion events. You can override this to
2340 * intercept all generic motion events before they are dispatched to the
2341 * window. Be sure to call this implementation for generic motion events
2342 * that should be handled normally.
2343 *
2344 * @param ev The generic motion event.
2345 *
2346 * @return boolean Return true if this event was consumed.
2347 */
2348 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2349 onUserInteraction();
2350 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2351 return true;
2352 }
2353 return onGenericMotionEvent(ev);
2354 }
2355
svetoslavganov75986cf2009-05-14 22:28:01 -07002356 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2357 event.setClassName(getClass().getName());
2358 event.setPackageName(getPackageName());
2359
2360 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002361 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2362 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002363 event.setFullScreen(isFullScreen);
2364
2365 CharSequence title = getTitle();
2366 if (!TextUtils.isEmpty(title)) {
2367 event.getText().add(title);
2368 }
2369
2370 return true;
2371 }
2372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 /**
2374 * Default implementation of
2375 * {@link android.view.Window.Callback#onCreatePanelView}
2376 * for activities. This
2377 * simply returns null so that all panel sub-windows will have the default
2378 * menu behavior.
2379 */
2380 public View onCreatePanelView(int featureId) {
2381 return null;
2382 }
2383
2384 /**
2385 * Default implementation of
2386 * {@link android.view.Window.Callback#onCreatePanelMenu}
2387 * for activities. This calls through to the new
2388 * {@link #onCreateOptionsMenu} method for the
2389 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2390 * so that subclasses of Activity don't need to deal with feature codes.
2391 */
2392 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2393 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002394 boolean show = onCreateOptionsMenu(menu);
2395 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2396 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 return false;
2399 }
2400
2401 /**
2402 * Default implementation of
2403 * {@link android.view.Window.Callback#onPreparePanel}
2404 * for activities. This
2405 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2406 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2407 * panel, so that subclasses of
2408 * Activity don't need to deal with feature codes.
2409 */
2410 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2411 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2412 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002413 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 return goforit && menu.hasVisibleItems();
2415 }
2416 return true;
2417 }
2418
2419 /**
2420 * {@inheritDoc}
2421 *
2422 * @return The default implementation returns true.
2423 */
2424 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002425 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell763cbb12011-03-01 10:45:34 -08002426 initActionBar();
Adam Powell049dd3d2010-12-02 13:43:59 -08002427 if (mActionBar != null) {
2428 mActionBar.dispatchMenuVisibilityChanged(true);
2429 } else {
2430 Log.e(TAG, "Tried to open action bar menu with no action bar");
2431 }
Adam Powell8515ee82010-11-30 14:09:55 -08002432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 return true;
2434 }
2435
2436 /**
2437 * Default implementation of
2438 * {@link android.view.Window.Callback#onMenuItemSelected}
2439 * for activities. This calls through to the new
2440 * {@link #onOptionsItemSelected} method for the
2441 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2442 * panel, so that subclasses of
2443 * Activity don't need to deal with feature codes.
2444 */
2445 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2446 switch (featureId) {
2447 case Window.FEATURE_OPTIONS_PANEL:
2448 // Put event logging here so it gets called even if subclass
2449 // doesn't call through to superclass's implmeentation of each
2450 // of these methods below
2451 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002452 if (onOptionsItemSelected(item)) {
2453 return true;
2454 }
2455 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456
2457 case Window.FEATURE_CONTEXT_MENU:
2458 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002459 if (onContextItemSelected(item)) {
2460 return true;
2461 }
2462 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 default:
2465 return false;
2466 }
2467 }
2468
2469 /**
2470 * Default implementation of
2471 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2472 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2473 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2474 * so that subclasses of Activity don't need to deal with feature codes.
2475 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2476 * {@link #onContextMenuClosed(Menu)} will be called.
2477 */
2478 public void onPanelClosed(int featureId, Menu menu) {
2479 switch (featureId) {
2480 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002481 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 onOptionsMenuClosed(menu);
2483 break;
2484
2485 case Window.FEATURE_CONTEXT_MENU:
2486 onContextMenuClosed(menu);
2487 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002488
2489 case Window.FEATURE_ACTION_BAR:
2490 mActionBar.dispatchMenuVisibilityChanged(false);
2491 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493 }
2494
2495 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002496 * Declare that the options menu has changed, so should be recreated.
2497 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2498 * time it needs to be displayed.
2499 */
2500 public void invalidateOptionsMenu() {
2501 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2502 }
2503
2504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 * Initialize the contents of the Activity's standard options menu. You
2506 * should place your menu items in to <var>menu</var>.
2507 *
2508 * <p>This is only called once, the first time the options menu is
2509 * displayed. To update the menu every time it is displayed, see
2510 * {@link #onPrepareOptionsMenu}.
2511 *
2512 * <p>The default implementation populates the menu with standard system
2513 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2514 * they will be correctly ordered with application-defined menu items.
2515 * Deriving classes should always call through to the base implementation.
2516 *
2517 * <p>You can safely hold on to <var>menu</var> (and any items created
2518 * from it), making modifications to it as desired, until the next
2519 * time onCreateOptionsMenu() is called.
2520 *
2521 * <p>When you add items to the menu, you can implement the Activity's
2522 * {@link #onOptionsItemSelected} method to handle them there.
2523 *
2524 * @param menu The options menu in which you place your items.
2525 *
2526 * @return You must return true for the menu to be displayed;
2527 * if you return false it will not be shown.
2528 *
2529 * @see #onPrepareOptionsMenu
2530 * @see #onOptionsItemSelected
2531 */
2532 public boolean onCreateOptionsMenu(Menu menu) {
2533 if (mParent != null) {
2534 return mParent.onCreateOptionsMenu(menu);
2535 }
2536 return true;
2537 }
2538
2539 /**
2540 * Prepare the Screen's standard options menu to be displayed. This is
2541 * called right before the menu is shown, every time it is shown. You can
2542 * use this method to efficiently enable/disable items or otherwise
2543 * dynamically modify the contents.
2544 *
2545 * <p>The default implementation updates the system menu items based on the
2546 * activity's state. Deriving classes should always call through to the
2547 * base class implementation.
2548 *
2549 * @param menu The options menu as last shown or first initialized by
2550 * onCreateOptionsMenu().
2551 *
2552 * @return You must return true for the menu to be displayed;
2553 * if you return false it will not be shown.
2554 *
2555 * @see #onCreateOptionsMenu
2556 */
2557 public boolean onPrepareOptionsMenu(Menu menu) {
2558 if (mParent != null) {
2559 return mParent.onPrepareOptionsMenu(menu);
2560 }
2561 return true;
2562 }
2563
2564 /**
2565 * This hook is called whenever an item in your options menu is selected.
2566 * The default implementation simply returns false to have the normal
2567 * processing happen (calling the item's Runnable or sending a message to
2568 * its Handler as appropriate). You can use this method for any items
2569 * for which you would like to do processing without those other
2570 * facilities.
2571 *
2572 * <p>Derived classes should call through to the base class for it to
2573 * perform the default menu handling.
2574 *
2575 * @param item The menu item that was selected.
2576 *
2577 * @return boolean Return false to allow normal menu processing to
2578 * proceed, true to consume it here.
2579 *
2580 * @see #onCreateOptionsMenu
2581 */
2582 public boolean onOptionsItemSelected(MenuItem item) {
2583 if (mParent != null) {
2584 return mParent.onOptionsItemSelected(item);
2585 }
2586 return false;
2587 }
2588
2589 /**
2590 * This hook is called whenever the options menu is being closed (either by the user canceling
2591 * the menu with the back/menu button, or when an item is selected).
2592 *
2593 * @param menu The options menu as last shown or first initialized by
2594 * onCreateOptionsMenu().
2595 */
2596 public void onOptionsMenuClosed(Menu menu) {
2597 if (mParent != null) {
2598 mParent.onOptionsMenuClosed(menu);
2599 }
2600 }
2601
2602 /**
2603 * Programmatically opens the options menu. If the options menu is already
2604 * open, this method does nothing.
2605 */
2606 public void openOptionsMenu() {
2607 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2608 }
2609
2610 /**
2611 * Progammatically closes the options menu. If the options menu is already
2612 * closed, this method does nothing.
2613 */
2614 public void closeOptionsMenu() {
2615 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2616 }
2617
2618 /**
2619 * Called when a context menu for the {@code view} is about to be shown.
2620 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2621 * time the context menu is about to be shown and should be populated for
2622 * the view (or item inside the view for {@link AdapterView} subclasses,
2623 * this can be found in the {@code menuInfo})).
2624 * <p>
2625 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2626 * item has been selected.
2627 * <p>
2628 * It is not safe to hold onto the context menu after this method returns.
2629 * {@inheritDoc}
2630 */
2631 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2632 }
2633
2634 /**
2635 * Registers a context menu to be shown for the given view (multiple views
2636 * can show the context menu). This method will set the
2637 * {@link OnCreateContextMenuListener} on the view to this activity, so
2638 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2639 * called when it is time to show the context menu.
2640 *
2641 * @see #unregisterForContextMenu(View)
2642 * @param view The view that should show a context menu.
2643 */
2644 public void registerForContextMenu(View view) {
2645 view.setOnCreateContextMenuListener(this);
2646 }
2647
2648 /**
2649 * Prevents a context menu to be shown for the given view. This method will remove the
2650 * {@link OnCreateContextMenuListener} on the view.
2651 *
2652 * @see #registerForContextMenu(View)
2653 * @param view The view that should stop showing a context menu.
2654 */
2655 public void unregisterForContextMenu(View view) {
2656 view.setOnCreateContextMenuListener(null);
2657 }
2658
2659 /**
2660 * Programmatically opens the context menu for a particular {@code view}.
2661 * The {@code view} should have been added via
2662 * {@link #registerForContextMenu(View)}.
2663 *
2664 * @param view The view to show the context menu for.
2665 */
2666 public void openContextMenu(View view) {
2667 view.showContextMenu();
2668 }
2669
2670 /**
2671 * Programmatically closes the most recently opened context menu, if showing.
2672 */
2673 public void closeContextMenu() {
2674 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2675 }
2676
2677 /**
2678 * This hook is called whenever an item in a context menu is selected. The
2679 * default implementation simply returns false to have the normal processing
2680 * happen (calling the item's Runnable or sending a message to its Handler
2681 * as appropriate). You can use this method for any items for which you
2682 * would like to do processing without those other facilities.
2683 * <p>
2684 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2685 * View that added this menu item.
2686 * <p>
2687 * Derived classes should call through to the base class for it to perform
2688 * the default menu handling.
2689 *
2690 * @param item The context menu item that was selected.
2691 * @return boolean Return false to allow normal context menu processing to
2692 * proceed, true to consume it here.
2693 */
2694 public boolean onContextItemSelected(MenuItem item) {
2695 if (mParent != null) {
2696 return mParent.onContextItemSelected(item);
2697 }
2698 return false;
2699 }
2700
2701 /**
2702 * This hook is called whenever the context menu is being closed (either by
2703 * the user canceling the menu with the back/menu button, or when an item is
2704 * selected).
2705 *
2706 * @param menu The context menu that is being closed.
2707 */
2708 public void onContextMenuClosed(Menu menu) {
2709 if (mParent != null) {
2710 mParent.onContextMenuClosed(menu);
2711 }
2712 }
2713
2714 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002715 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002717 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 protected Dialog onCreateDialog(int id) {
2719 return null;
2720 }
2721
2722 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002723 * Callback for creating dialogs that are managed (saved and restored) for you
2724 * by the activity. The default implementation calls through to
2725 * {@link #onCreateDialog(int)} for compatibility.
2726 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002727 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2728 * or later, consider instead using a {@link DialogFragment} instead.</em>
2729 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002730 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2731 * this method the first time, and hang onto it thereafter. Any dialog
2732 * that is created by this method will automatically be saved and restored
2733 * for you, including whether it is showing.
2734 *
2735 * <p>If you would like the activity to manage saving and restoring dialogs
2736 * for you, you should override this method and handle any ids that are
2737 * passed to {@link #showDialog}.
2738 *
2739 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2740 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2741 *
2742 * @param id The id of the dialog.
2743 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2744 * @return The dialog. If you return null, the dialog will not be created.
2745 *
2746 * @see #onPrepareDialog(int, Dialog, Bundle)
2747 * @see #showDialog(int, Bundle)
2748 * @see #dismissDialog(int)
2749 * @see #removeDialog(int)
2750 */
2751 protected Dialog onCreateDialog(int id, Bundle args) {
2752 return onCreateDialog(id);
2753 }
2754
2755 /**
2756 * @deprecated Old no-arguments version of
2757 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2758 */
2759 @Deprecated
2760 protected void onPrepareDialog(int id, Dialog dialog) {
2761 dialog.setOwnerActivity(this);
2762 }
2763
2764 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002766 * shown. The default implementation calls through to
2767 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2768 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 * <p>
2770 * Override this if you need to update a managed dialog based on the state
2771 * of the application each time it is shown. For example, a time picker
2772 * dialog might want to be updated with the current time. You should call
2773 * through to the superclass's implementation. The default implementation
2774 * will set this Activity as the owner activity on the Dialog.
2775 *
2776 * @param id The id of the managed dialog.
2777 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002778 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2779 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 * @see #showDialog(int)
2781 * @see #dismissDialog(int)
2782 * @see #removeDialog(int)
2783 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002784 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2785 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
2787
2788 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002789 * Simple version of {@link #showDialog(int, Bundle)} that does not
2790 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2791 * with null arguments.
2792 */
2793 public final void showDialog(int id) {
2794 showDialog(id, null);
2795 }
2796
2797 /**
2798 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 * will be made with the same id the first time this is called for a given
2800 * id. From thereafter, the dialog will be automatically saved and restored.
2801 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002802 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2803 * or later, consider instead using a {@link DialogFragment} instead.</em>
2804 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002805 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 * be made to provide an opportunity to do any timely preparation.
2807 *
2808 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002809 * @param args Arguments to pass through to the dialog. These will be saved
2810 * and restored for you. Note that if the dialog is already created,
2811 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2812 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002813 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002814 * @return Returns true if the Dialog was created; false is returned if
2815 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2816 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002817 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002818 * @see #onCreateDialog(int, Bundle)
2819 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 * @see #dismissDialog(int)
2821 * @see #removeDialog(int)
2822 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002823 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002825 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002827 ManagedDialog md = mManagedDialogs.get(id);
2828 if (md == null) {
2829 md = new ManagedDialog();
2830 md.mDialog = createDialog(id, null, args);
2831 if (md.mDialog == null) {
2832 return false;
2833 }
2834 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002837 md.mArgs = args;
2838 onPrepareDialog(id, md.mDialog, args);
2839 md.mDialog.show();
2840 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842
2843 /**
2844 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2845 *
2846 * @param id The id of the managed dialog.
2847 *
2848 * @throws IllegalArgumentException if the id was not previously shown via
2849 * {@link #showDialog(int)}.
2850 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002851 * @see #onCreateDialog(int, Bundle)
2852 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 * @see #showDialog(int)
2854 * @see #removeDialog(int)
2855 */
2856 public final void dismissDialog(int id) {
2857 if (mManagedDialogs == null) {
2858 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002860
2861 final ManagedDialog md = mManagedDialogs.get(id);
2862 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 throw missingDialog(id);
2864 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002865 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
2868 /**
2869 * Creates an exception to throw if a user passed in a dialog id that is
2870 * unexpected.
2871 */
2872 private IllegalArgumentException missingDialog(int id) {
2873 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2874 + "shown via Activity#showDialog");
2875 }
2876
2877 /**
2878 * Removes any internal references to a dialog managed by this Activity.
2879 * If the dialog is showing, it will dismiss it as part of the clean up.
2880 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002881 * <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 -08002882 * want to avoid the overhead of saving and restoring it in the future.
2883 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002884 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2885 * will not throw an exception if you try to remove an ID that does not
2886 * currently have an associated dialog.</p>
2887 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 * @param id The id of the managed dialog.
2889 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002890 * @see #onCreateDialog(int, Bundle)
2891 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 * @see #showDialog(int)
2893 * @see #dismissDialog(int)
2894 */
2895 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002896 if (mManagedDialogs != null) {
2897 final ManagedDialog md = mManagedDialogs.get(id);
2898 if (md != null) {
2899 md.mDialog.dismiss();
2900 mManagedDialogs.remove(id);
2901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 }
2904
2905 /**
2906 * This hook is called when the user signals the desire to start a search.
2907 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002908 * <p>You can use this function as a simple way to launch the search UI, in response to a
2909 * menu item, search button, or other widgets within your activity. Unless overidden,
2910 * calling this function is the same as calling
2911 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2912 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 *
2914 * <p>You can override this function to force global search, e.g. in response to a dedicated
2915 * search key, or to block search entirely (by simply returning false).
2916 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002917 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2918 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 *
2920 * @see android.app.SearchManager
2921 */
2922 public boolean onSearchRequested() {
2923 startSearch(null, false, null, false);
2924 return true;
2925 }
2926
2927 /**
2928 * This hook is called to launch the search UI.
2929 *
2930 * <p>It is typically called from onSearchRequested(), either directly from
2931 * Activity.onSearchRequested() or from an overridden version in any given
2932 * Activity. If your goal is simply to activate search, it is preferred to call
2933 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2934 * is to inject specific data such as context data, it is preferred to <i>override</i>
2935 * onSearchRequested(), so that any callers to it will benefit from the override.
2936 *
2937 * @param initialQuery Any non-null non-empty string will be inserted as
2938 * pre-entered text in the search query box.
2939 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2940 * any further typing will replace it. This is useful for cases where an entire pre-formed
2941 * query is being inserted. If false, the selection point will be placed at the end of the
2942 * inserted query. This is useful when the inserted query is text that the user entered,
2943 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2944 * if initialQuery is a non-empty string.</i>
2945 * @param appSearchData An application can insert application-specific
2946 * context here, in order to improve quality or specificity of its own
2947 * searches. This data will be returned with SEARCH intent(s). Null if
2948 * no extra data is required.
2949 * @param globalSearch If false, this will only launch the search that has been specifically
2950 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002951 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2953 *
2954 * @see android.app.SearchManager
2955 * @see #onSearchRequested
2956 */
2957 public void startSearch(String initialQuery, boolean selectInitialQuery,
2958 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002959 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002960 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 appSearchData, globalSearch);
2962 }
2963
2964 /**
krosaend2d60142009-08-17 08:56:48 -07002965 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2966 * the search dialog. Made available for testing purposes.
2967 *
2968 * @param query The query to trigger. If empty, the request will be ignored.
2969 * @param appSearchData An application can insert application-specific
2970 * context here, in order to improve quality or specificity of its own
2971 * searches. This data will be returned with SEARCH intent(s). Null if
2972 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002973 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002974 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002975 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002976 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002977 }
2978
2979 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 * Request that key events come to this activity. Use this if your
2981 * activity has no views with focus, but the activity still wants
2982 * a chance to process key events.
2983 *
2984 * @see android.view.Window#takeKeyEvents
2985 */
2986 public void takeKeyEvents(boolean get) {
2987 getWindow().takeKeyEvents(get);
2988 }
2989
2990 /**
2991 * Enable extended window features. This is a convenience for calling
2992 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2993 *
2994 * @param featureId The desired feature as defined in
2995 * {@link android.view.Window}.
2996 * @return Returns true if the requested feature is supported and now
2997 * enabled.
2998 *
2999 * @see android.view.Window#requestFeature
3000 */
3001 public final boolean requestWindowFeature(int featureId) {
3002 return getWindow().requestFeature(featureId);
3003 }
3004
3005 /**
3006 * Convenience for calling
3007 * {@link android.view.Window#setFeatureDrawableResource}.
3008 */
3009 public final void setFeatureDrawableResource(int featureId, int resId) {
3010 getWindow().setFeatureDrawableResource(featureId, resId);
3011 }
3012
3013 /**
3014 * Convenience for calling
3015 * {@link android.view.Window#setFeatureDrawableUri}.
3016 */
3017 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3018 getWindow().setFeatureDrawableUri(featureId, uri);
3019 }
3020
3021 /**
3022 * Convenience for calling
3023 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3024 */
3025 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3026 getWindow().setFeatureDrawable(featureId, drawable);
3027 }
3028
3029 /**
3030 * Convenience for calling
3031 * {@link android.view.Window#setFeatureDrawableAlpha}.
3032 */
3033 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3034 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3035 }
3036
3037 /**
3038 * Convenience for calling
3039 * {@link android.view.Window#getLayoutInflater}.
3040 */
3041 public LayoutInflater getLayoutInflater() {
3042 return getWindow().getLayoutInflater();
3043 }
3044
3045 /**
3046 * Returns a {@link MenuInflater} with this context.
3047 */
3048 public MenuInflater getMenuInflater() {
3049 return new MenuInflater(this);
3050 }
3051
3052 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003053 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3054 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 if (mParent == null) {
3056 super.onApplyThemeResource(theme, resid, first);
3057 } else {
3058 try {
3059 theme.setTo(mParent.getTheme());
3060 } catch (Exception e) {
3061 // Empty
3062 }
3063 theme.applyStyle(resid, false);
3064 }
3065 }
3066
3067 /**
3068 * Launch an activity for which you would like a result when it finished.
3069 * When this activity exits, your
3070 * onActivityResult() method will be called with the given requestCode.
3071 * Using a negative requestCode is the same as calling
3072 * {@link #startActivity} (the activity is not launched as a sub-activity).
3073 *
3074 * <p>Note that this method should only be used with Intent protocols
3075 * that are defined to return a result. In other protocols (such as
3076 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3077 * not get the result when you expect. For example, if the activity you
3078 * are launching uses the singleTask launch mode, it will not run in your
3079 * task and thus you will immediately receive a cancel result.
3080 *
3081 * <p>As a special case, if you call startActivityForResult() with a requestCode
3082 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3083 * activity, then your window will not be displayed until a result is
3084 * returned back from the started activity. This is to avoid visible
3085 * flickering when redirecting to another activity.
3086 *
3087 * <p>This method throws {@link android.content.ActivityNotFoundException}
3088 * if there was no Activity found to run the given Intent.
3089 *
3090 * @param intent The intent to start.
3091 * @param requestCode If >= 0, this code will be returned in
3092 * onActivityResult() when the activity exits.
3093 *
3094 * @throws android.content.ActivityNotFoundException
3095 *
3096 * @see #startActivity
3097 */
3098 public void startActivityForResult(Intent intent, int requestCode) {
3099 if (mParent == null) {
3100 Instrumentation.ActivityResult ar =
3101 mInstrumentation.execStartActivity(
3102 this, mMainThread.getApplicationThread(), mToken, this,
3103 intent, requestCode);
3104 if (ar != null) {
3105 mMainThread.sendActivityResult(
3106 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3107 ar.getResultData());
3108 }
3109 if (requestCode >= 0) {
3110 // If this start is requesting a result, we can avoid making
3111 // the activity visible until the result is received. Setting
3112 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3113 // activity hidden during this time, to avoid flickering.
3114 // This can only be done when a result is requested because
3115 // that guarantees we will get information back when the
3116 // activity is finished, no matter what happens to it.
3117 mStartedActivity = true;
3118 }
3119 } else {
3120 mParent.startActivityFromChild(this, intent, requestCode);
3121 }
3122 }
3123
3124 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003125 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003126 * to use a IntentSender to describe the activity to be started. If
3127 * the IntentSender is for an activity, that activity will be started
3128 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3129 * here; otherwise, its associated action will be executed (such as
3130 * sending a broadcast) as if you had called
3131 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003132 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003133 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003134 * @param requestCode If >= 0, this code will be returned in
3135 * onActivityResult() when the activity exits.
3136 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003137 * intent parameter to {@link IntentSender#sendIntent}.
3138 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003139 * would like to change.
3140 * @param flagsValues Desired values for any bits set in
3141 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003142 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003143 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003144 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3145 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3146 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003147 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003148 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003149 flagsMask, flagsValues, this);
3150 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003151 mParent.startIntentSenderFromChild(this, intent, requestCode,
3152 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003153 }
3154 }
3155
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003156 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003157 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003158 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003159 try {
3160 String resolvedType = null;
3161 if (fillInIntent != null) {
3162 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3163 }
3164 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003165 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003166 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3167 requestCode, flagsMask, flagsValues);
3168 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003169 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003170 }
3171 Instrumentation.checkStartActivityResult(result, null);
3172 } catch (RemoteException e) {
3173 }
3174 if (requestCode >= 0) {
3175 // If this start is requesting a result, we can avoid making
3176 // the activity visible until the result is received. Setting
3177 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3178 // activity hidden during this time, to avoid flickering.
3179 // This can only be done when a result is requested because
3180 // that guarantees we will get information back when the
3181 // activity is finished, no matter what happens to it.
3182 mStartedActivity = true;
3183 }
3184 }
3185
3186 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 * Launch a new activity. You will not receive any information about when
3188 * the activity exits. This implementation overrides the base version,
3189 * providing information about
3190 * the activity performing the launch. Because of this additional
3191 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3192 * required; if not specified, the new activity will be added to the
3193 * task of the caller.
3194 *
3195 * <p>This method throws {@link android.content.ActivityNotFoundException}
3196 * if there was no Activity found to run the given Intent.
3197 *
3198 * @param intent The intent to start.
3199 *
3200 * @throws android.content.ActivityNotFoundException
3201 *
3202 * @see #startActivityForResult
3203 */
3204 @Override
3205 public void startActivity(Intent intent) {
3206 startActivityForResult(intent, -1);
3207 }
3208
3209 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003210 * Launch a new activity. You will not receive any information about when
3211 * the activity exits. This implementation overrides the base version,
3212 * providing information about
3213 * the activity performing the launch. Because of this additional
3214 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3215 * required; if not specified, the new activity will be added to the
3216 * task of the caller.
3217 *
3218 * <p>This method throws {@link android.content.ActivityNotFoundException}
3219 * if there was no Activity found to run the given Intent.
3220 *
3221 * @param intents The intents to start.
3222 *
3223 * @throws android.content.ActivityNotFoundException
3224 *
3225 * @see #startActivityForResult
3226 */
3227 @Override
3228 public void startActivities(Intent[] intents) {
3229 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3230 mToken, this, intents);
3231 }
3232
3233 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003234 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003235 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003236 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003237 * for more information.
3238 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003239 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003240 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003241 * intent parameter to {@link IntentSender#sendIntent}.
3242 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003243 * would like to change.
3244 * @param flagsValues Desired values for any bits set in
3245 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003246 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003247 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003248 public void startIntentSender(IntentSender intent,
3249 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3250 throws IntentSender.SendIntentException {
3251 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3252 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003253 }
3254
3255 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 * A special variation to launch an activity only if a new activity
3257 * instance is needed to handle the given Intent. In other words, this is
3258 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3259 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3260 * singleTask or singleTop
3261 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3262 * and the activity
3263 * that handles <var>intent</var> is the same as your currently running
3264 * activity, then a new instance is not needed. In this case, instead of
3265 * the normal behavior of calling {@link #onNewIntent} this function will
3266 * return and you can handle the Intent yourself.
3267 *
3268 * <p>This function can only be called from a top-level activity; if it is
3269 * called from a child activity, a runtime exception will be thrown.
3270 *
3271 * @param intent The intent to start.
3272 * @param requestCode If >= 0, this code will be returned in
3273 * onActivityResult() when the activity exits, as described in
3274 * {@link #startActivityForResult}.
3275 *
3276 * @return If a new activity was launched then true is returned; otherwise
3277 * false is returned and you must handle the Intent yourself.
3278 *
3279 * @see #startActivity
3280 * @see #startActivityForResult
3281 */
3282 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3283 if (mParent == null) {
3284 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3285 try {
3286 result = ActivityManagerNative.getDefault()
3287 .startActivity(mMainThread.getApplicationThread(),
3288 intent, intent.resolveTypeIfNeeded(
3289 getContentResolver()),
3290 null, 0,
3291 mToken, mEmbeddedID, requestCode, true, false);
3292 } catch (RemoteException e) {
3293 // Empty
3294 }
3295
3296 Instrumentation.checkStartActivityResult(result, intent);
3297
3298 if (requestCode >= 0) {
3299 // If this start is requesting a result, we can avoid making
3300 // the activity visible until the result is received. Setting
3301 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3302 // activity hidden during this time, to avoid flickering.
3303 // This can only be done when a result is requested because
3304 // that guarantees we will get information back when the
3305 // activity is finished, no matter what happens to it.
3306 mStartedActivity = true;
3307 }
3308 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3309 }
3310
3311 throw new UnsupportedOperationException(
3312 "startActivityIfNeeded can only be called from a top-level activity");
3313 }
3314
3315 /**
3316 * Special version of starting an activity, for use when you are replacing
3317 * other activity components. You can use this to hand the Intent off
3318 * to the next Activity that can handle it. You typically call this in
3319 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3320 *
3321 * @param intent The intent to dispatch to the next activity. For
3322 * correct behavior, this must be the same as the Intent that started
3323 * your own activity; the only changes you can make are to the extras
3324 * inside of it.
3325 *
3326 * @return Returns a boolean indicating whether there was another Activity
3327 * to start: true if there was a next activity to start, false if there
3328 * wasn't. In general, if true is returned you will then want to call
3329 * finish() on yourself.
3330 */
3331 public boolean startNextMatchingActivity(Intent intent) {
3332 if (mParent == null) {
3333 try {
3334 return ActivityManagerNative.getDefault()
3335 .startNextMatchingActivity(mToken, intent);
3336 } catch (RemoteException e) {
3337 // Empty
3338 }
3339 return false;
3340 }
3341
3342 throw new UnsupportedOperationException(
3343 "startNextMatchingActivity can only be called from a top-level activity");
3344 }
3345
3346 /**
3347 * This is called when a child activity of this one calls its
3348 * {@link #startActivity} or {@link #startActivityForResult} method.
3349 *
3350 * <p>This method throws {@link android.content.ActivityNotFoundException}
3351 * if there was no Activity found to run the given Intent.
3352 *
3353 * @param child The activity making the call.
3354 * @param intent The intent to start.
3355 * @param requestCode Reply request code. < 0 if reply is not requested.
3356 *
3357 * @throws android.content.ActivityNotFoundException
3358 *
3359 * @see #startActivity
3360 * @see #startActivityForResult
3361 */
3362 public void startActivityFromChild(Activity child, Intent intent,
3363 int requestCode) {
3364 Instrumentation.ActivityResult ar =
3365 mInstrumentation.execStartActivity(
3366 this, mMainThread.getApplicationThread(), mToken, child,
3367 intent, requestCode);
3368 if (ar != null) {
3369 mMainThread.sendActivityResult(
3370 mToken, child.mEmbeddedID, requestCode,
3371 ar.getResultCode(), ar.getResultData());
3372 }
3373 }
3374
3375 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003376 * This is called when a Fragment in this activity calls its
3377 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3378 * method.
3379 *
3380 * <p>This method throws {@link android.content.ActivityNotFoundException}
3381 * if there was no Activity found to run the given Intent.
3382 *
3383 * @param fragment The fragment making the call.
3384 * @param intent The intent to start.
3385 * @param requestCode Reply request code. < 0 if reply is not requested.
3386 *
3387 * @throws android.content.ActivityNotFoundException
3388 *
3389 * @see Fragment#startActivity
3390 * @see Fragment#startActivityForResult
3391 */
3392 public void startActivityFromFragment(Fragment fragment, Intent intent,
3393 int requestCode) {
3394 Instrumentation.ActivityResult ar =
3395 mInstrumentation.execStartActivity(
3396 this, mMainThread.getApplicationThread(), mToken, fragment,
3397 intent, requestCode);
3398 if (ar != null) {
3399 mMainThread.sendActivityResult(
3400 mToken, fragment.mWho, requestCode,
3401 ar.getResultCode(), ar.getResultData());
3402 }
3403 }
3404
3405 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003406 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003407 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003408 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003409 * for more information.
3410 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003411 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3412 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3413 int extraFlags)
3414 throws IntentSender.SendIntentException {
3415 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003416 flagsMask, flagsValues, child);
3417 }
3418
3419 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003420 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3421 * or {@link #finish} to specify an explicit transition animation to
3422 * perform next.
3423 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003424 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003425 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003426 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003427 */
3428 public void overridePendingTransition(int enterAnim, int exitAnim) {
3429 try {
3430 ActivityManagerNative.getDefault().overridePendingTransition(
3431 mToken, getPackageName(), enterAnim, exitAnim);
3432 } catch (RemoteException e) {
3433 }
3434 }
3435
3436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 * Call this to set the result that your activity will return to its
3438 * caller.
3439 *
3440 * @param resultCode The result code to propagate back to the originating
3441 * activity, often RESULT_CANCELED or RESULT_OK
3442 *
3443 * @see #RESULT_CANCELED
3444 * @see #RESULT_OK
3445 * @see #RESULT_FIRST_USER
3446 * @see #setResult(int, Intent)
3447 */
3448 public final void setResult(int resultCode) {
3449 synchronized (this) {
3450 mResultCode = resultCode;
3451 mResultData = null;
3452 }
3453 }
3454
3455 /**
3456 * Call this to set the result that your activity will return to its
3457 * caller.
3458 *
3459 * @param resultCode The result code to propagate back to the originating
3460 * activity, often RESULT_CANCELED or RESULT_OK
3461 * @param data The data to propagate back to the originating activity.
3462 *
3463 * @see #RESULT_CANCELED
3464 * @see #RESULT_OK
3465 * @see #RESULT_FIRST_USER
3466 * @see #setResult(int)
3467 */
3468 public final void setResult(int resultCode, Intent data) {
3469 synchronized (this) {
3470 mResultCode = resultCode;
3471 mResultData = data;
3472 }
3473 }
3474
3475 /**
3476 * Return the name of the package that invoked this activity. This is who
3477 * the data in {@link #setResult setResult()} will be sent to. You can
3478 * use this information to validate that the recipient is allowed to
3479 * receive the data.
3480 *
3481 * <p>Note: if the calling activity is not expecting a result (that is it
3482 * did not use the {@link #startActivityForResult}
3483 * form that includes a request code), then the calling package will be
3484 * null.
3485 *
3486 * @return The package of the activity that will receive your
3487 * reply, or null if none.
3488 */
3489 public String getCallingPackage() {
3490 try {
3491 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3492 } catch (RemoteException e) {
3493 return null;
3494 }
3495 }
3496
3497 /**
3498 * Return the name of the activity that invoked this activity. This is
3499 * who the data in {@link #setResult setResult()} will be sent to. You
3500 * can use this information to validate that the recipient is allowed to
3501 * receive the data.
3502 *
3503 * <p>Note: if the calling activity is not expecting a result (that is it
3504 * did not use the {@link #startActivityForResult}
3505 * form that includes a request code), then the calling package will be
3506 * null.
3507 *
3508 * @return String The full name of the activity that will receive your
3509 * reply, or null if none.
3510 */
3511 public ComponentName getCallingActivity() {
3512 try {
3513 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3514 } catch (RemoteException e) {
3515 return null;
3516 }
3517 }
3518
3519 /**
3520 * Control whether this activity's main window is visible. This is intended
3521 * only for the special case of an activity that is not going to show a
3522 * UI itself, but can't just finish prior to onResume() because it needs
3523 * to wait for a service binding or such. Setting this to false allows
3524 * you to prevent your UI from being shown during that time.
3525 *
3526 * <p>The default value for this is taken from the
3527 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3528 */
3529 public void setVisible(boolean visible) {
3530 if (mVisibleFromClient != visible) {
3531 mVisibleFromClient = visible;
3532 if (mVisibleFromServer) {
3533 if (visible) makeVisible();
3534 else mDecor.setVisibility(View.INVISIBLE);
3535 }
3536 }
3537 }
3538
3539 void makeVisible() {
3540 if (!mWindowAdded) {
3541 ViewManager wm = getWindowManager();
3542 wm.addView(mDecor, getWindow().getAttributes());
3543 mWindowAdded = true;
3544 }
3545 mDecor.setVisibility(View.VISIBLE);
3546 }
3547
3548 /**
3549 * Check to see whether this activity is in the process of finishing,
3550 * either because you called {@link #finish} on it or someone else
3551 * has requested that it finished. This is often used in
3552 * {@link #onPause} to determine whether the activity is simply pausing or
3553 * completely finishing.
3554 *
3555 * @return If the activity is finishing, returns true; else returns false.
3556 *
3557 * @see #finish
3558 */
3559 public boolean isFinishing() {
3560 return mFinished;
3561 }
3562
3563 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003564 * Check to see whether this activity is in the process of being destroyed in order to be
3565 * recreated with a new configuration. This is often used in
3566 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3567 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3568 *
3569 * @return If the activity is being torn down in order to be recreated with a new configuration,
3570 * returns true; else returns false.
3571 */
3572 public boolean isChangingConfigurations() {
3573 return mChangingConfigurations;
3574 }
3575
3576 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003577 * Cause this Activity to be recreated with a new instance. This results
3578 * in essentially the same flow as when the Activity is created due to
3579 * a configuration change -- the current instance will go through its
3580 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3581 */
3582 public void recreate() {
3583 if (mParent != null) {
3584 throw new IllegalStateException("Can only be called on top-level activity");
3585 }
3586 if (Looper.myLooper() != mMainThread.getLooper()) {
3587 throw new IllegalStateException("Must be called from main thread");
3588 }
3589 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3590 }
3591
3592 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 * Call this when your activity is done and should be closed. The
3594 * ActivityResult is propagated back to whoever launched you via
3595 * onActivityResult().
3596 */
3597 public void finish() {
3598 if (mParent == null) {
3599 int resultCode;
3600 Intent resultData;
3601 synchronized (this) {
3602 resultCode = mResultCode;
3603 resultData = mResultData;
3604 }
3605 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3606 try {
3607 if (ActivityManagerNative.getDefault()
3608 .finishActivity(mToken, resultCode, resultData)) {
3609 mFinished = true;
3610 }
3611 } catch (RemoteException e) {
3612 // Empty
3613 }
3614 } else {
3615 mParent.finishFromChild(this);
3616 }
3617 }
3618
3619 /**
3620 * This is called when a child activity of this one calls its
3621 * {@link #finish} method. The default implementation simply calls
3622 * finish() on this activity (the parent), finishing the entire group.
3623 *
3624 * @param child The activity making the call.
3625 *
3626 * @see #finish
3627 */
3628 public void finishFromChild(Activity child) {
3629 finish();
3630 }
3631
3632 /**
3633 * Force finish another activity that you had previously started with
3634 * {@link #startActivityForResult}.
3635 *
3636 * @param requestCode The request code of the activity that you had
3637 * given to startActivityForResult(). If there are multiple
3638 * activities started with this request code, they
3639 * will all be finished.
3640 */
3641 public void finishActivity(int requestCode) {
3642 if (mParent == null) {
3643 try {
3644 ActivityManagerNative.getDefault()
3645 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3646 } catch (RemoteException e) {
3647 // Empty
3648 }
3649 } else {
3650 mParent.finishActivityFromChild(this, requestCode);
3651 }
3652 }
3653
3654 /**
3655 * This is called when a child activity of this one calls its
3656 * finishActivity().
3657 *
3658 * @param child The activity making the call.
3659 * @param requestCode Request code that had been used to start the
3660 * activity.
3661 */
3662 public void finishActivityFromChild(Activity child, int requestCode) {
3663 try {
3664 ActivityManagerNative.getDefault()
3665 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3666 } catch (RemoteException e) {
3667 // Empty
3668 }
3669 }
3670
3671 /**
3672 * Called when an activity you launched exits, giving you the requestCode
3673 * you started it with, the resultCode it returned, and any additional
3674 * data from it. The <var>resultCode</var> will be
3675 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3676 * didn't return any result, or crashed during its operation.
3677 *
3678 * <p>You will receive this call immediately before onResume() when your
3679 * activity is re-starting.
3680 *
3681 * @param requestCode The integer request code originally supplied to
3682 * startActivityForResult(), allowing you to identify who this
3683 * result came from.
3684 * @param resultCode The integer result code returned by the child activity
3685 * through its setResult().
3686 * @param data An Intent, which can return result data to the caller
3687 * (various data can be attached to Intent "extras").
3688 *
3689 * @see #startActivityForResult
3690 * @see #createPendingResult
3691 * @see #setResult(int)
3692 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003693 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 }
3695
3696 /**
3697 * Create a new PendingIntent object which you can hand to others
3698 * for them to use to send result data back to your
3699 * {@link #onActivityResult} callback. The created object will be either
3700 * one-shot (becoming invalid after a result is sent back) or multiple
3701 * (allowing any number of results to be sent through it).
3702 *
3703 * @param requestCode Private request code for the sender that will be
3704 * associated with the result data when it is returned. The sender can not
3705 * modify this value, allowing you to identify incoming results.
3706 * @param data Default data to supply in the result, which may be modified
3707 * by the sender.
3708 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3709 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3710 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3711 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3712 * or any of the flags as supported by
3713 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3714 * of the intent that can be supplied when the actual send happens.
3715 *
3716 * @return Returns an existing or new PendingIntent matching the given
3717 * parameters. May return null only if
3718 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3719 * supplied.
3720 *
3721 * @see PendingIntent
3722 */
3723 public PendingIntent createPendingResult(int requestCode, Intent data,
3724 int flags) {
3725 String packageName = getPackageName();
3726 try {
3727 IIntentSender target =
3728 ActivityManagerNative.getDefault().getIntentSender(
3729 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3730 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003731 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 return target != null ? new PendingIntent(target) : null;
3733 } catch (RemoteException e) {
3734 // Empty
3735 }
3736 return null;
3737 }
3738
3739 /**
3740 * Change the desired orientation of this activity. If the activity
3741 * is currently in the foreground or otherwise impacting the screen
3742 * orientation, the screen will immediately be changed (possibly causing
3743 * the activity to be restarted). Otherwise, this will be used the next
3744 * time the activity is visible.
3745 *
3746 * @param requestedOrientation An orientation constant as used in
3747 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3748 */
3749 public void setRequestedOrientation(int requestedOrientation) {
3750 if (mParent == null) {
3751 try {
3752 ActivityManagerNative.getDefault().setRequestedOrientation(
3753 mToken, requestedOrientation);
3754 } catch (RemoteException e) {
3755 // Empty
3756 }
3757 } else {
3758 mParent.setRequestedOrientation(requestedOrientation);
3759 }
3760 }
3761
3762 /**
3763 * Return the current requested orientation of the activity. This will
3764 * either be the orientation requested in its component's manifest, or
3765 * the last requested orientation given to
3766 * {@link #setRequestedOrientation(int)}.
3767 *
3768 * @return Returns an orientation constant as used in
3769 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3770 */
3771 public int getRequestedOrientation() {
3772 if (mParent == null) {
3773 try {
3774 return ActivityManagerNative.getDefault()
3775 .getRequestedOrientation(mToken);
3776 } catch (RemoteException e) {
3777 // Empty
3778 }
3779 } else {
3780 return mParent.getRequestedOrientation();
3781 }
3782 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3783 }
3784
3785 /**
3786 * Return the identifier of the task this activity is in. This identifier
3787 * will remain the same for the lifetime of the activity.
3788 *
3789 * @return Task identifier, an opaque integer.
3790 */
3791 public int getTaskId() {
3792 try {
3793 return ActivityManagerNative.getDefault()
3794 .getTaskForActivity(mToken, false);
3795 } catch (RemoteException e) {
3796 return -1;
3797 }
3798 }
3799
3800 /**
3801 * Return whether this activity is the root of a task. The root is the
3802 * first activity in a task.
3803 *
3804 * @return True if this is the root activity, else false.
3805 */
3806 public boolean isTaskRoot() {
3807 try {
3808 return ActivityManagerNative.getDefault()
3809 .getTaskForActivity(mToken, true) >= 0;
3810 } catch (RemoteException e) {
3811 return false;
3812 }
3813 }
3814
3815 /**
3816 * Move the task containing this activity to the back of the activity
3817 * stack. The activity's order within the task is unchanged.
3818 *
3819 * @param nonRoot If false then this only works if the activity is the root
3820 * of a task; if true it will work for any activity in
3821 * a task.
3822 *
3823 * @return If the task was moved (or it was already at the
3824 * back) true is returned, else false.
3825 */
3826 public boolean moveTaskToBack(boolean nonRoot) {
3827 try {
3828 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3829 mToken, nonRoot);
3830 } catch (RemoteException e) {
3831 // Empty
3832 }
3833 return false;
3834 }
3835
3836 /**
3837 * Returns class name for this activity with the package prefix removed.
3838 * This is the default name used to read and write settings.
3839 *
3840 * @return The local class name.
3841 */
3842 public String getLocalClassName() {
3843 final String pkg = getPackageName();
3844 final String cls = mComponent.getClassName();
3845 int packageLen = pkg.length();
3846 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3847 || cls.charAt(packageLen) != '.') {
3848 return cls;
3849 }
3850 return cls.substring(packageLen+1);
3851 }
3852
3853 /**
3854 * Returns complete component name of this activity.
3855 *
3856 * @return Returns the complete component name for this activity
3857 */
3858 public ComponentName getComponentName()
3859 {
3860 return mComponent;
3861 }
3862
3863 /**
3864 * Retrieve a {@link SharedPreferences} object for accessing preferences
3865 * that are private to this activity. This simply calls the underlying
3866 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3867 * class name as the preferences name.
3868 *
3869 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3870 * operation, {@link #MODE_WORLD_READABLE} and
3871 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3872 *
3873 * @return Returns the single SharedPreferences instance that can be used
3874 * to retrieve and modify the preference values.
3875 */
3876 public SharedPreferences getPreferences(int mode) {
3877 return getSharedPreferences(getLocalClassName(), mode);
3878 }
3879
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003880 private void ensureSearchManager() {
3881 if (mSearchManager != null) {
3882 return;
3883 }
3884
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003885 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003886 }
3887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 @Override
3889 public Object getSystemService(String name) {
3890 if (getBaseContext() == null) {
3891 throw new IllegalStateException(
3892 "System services not available to Activities before onCreate()");
3893 }
3894
3895 if (WINDOW_SERVICE.equals(name)) {
3896 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003897 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003898 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003899 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 }
3901 return super.getSystemService(name);
3902 }
3903
3904 /**
3905 * Change the title associated with this activity. If this is a
3906 * top-level activity, the title for its window will change. If it
3907 * is an embedded activity, the parent can do whatever it wants
3908 * with it.
3909 */
3910 public void setTitle(CharSequence title) {
3911 mTitle = title;
3912 onTitleChanged(title, mTitleColor);
3913
3914 if (mParent != null) {
3915 mParent.onChildTitleChanged(this, title);
3916 }
3917 }
3918
3919 /**
3920 * Change the title associated with this activity. If this is a
3921 * top-level activity, the title for its window will change. If it
3922 * is an embedded activity, the parent can do whatever it wants
3923 * with it.
3924 */
3925 public void setTitle(int titleId) {
3926 setTitle(getText(titleId));
3927 }
3928
3929 public void setTitleColor(int textColor) {
3930 mTitleColor = textColor;
3931 onTitleChanged(mTitle, textColor);
3932 }
3933
3934 public final CharSequence getTitle() {
3935 return mTitle;
3936 }
3937
3938 public final int getTitleColor() {
3939 return mTitleColor;
3940 }
3941
3942 protected void onTitleChanged(CharSequence title, int color) {
3943 if (mTitleReady) {
3944 final Window win = getWindow();
3945 if (win != null) {
3946 win.setTitle(title);
3947 if (color != 0) {
3948 win.setTitleColor(color);
3949 }
3950 }
3951 }
3952 }
3953
3954 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3955 }
3956
3957 /**
3958 * Sets the visibility of the progress bar in the title.
3959 * <p>
3960 * In order for the progress bar to be shown, the feature must be requested
3961 * via {@link #requestWindowFeature(int)}.
3962 *
3963 * @param visible Whether to show the progress bars in the title.
3964 */
3965 public final void setProgressBarVisibility(boolean visible) {
3966 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3967 Window.PROGRESS_VISIBILITY_OFF);
3968 }
3969
3970 /**
3971 * Sets the visibility of the indeterminate progress bar in the title.
3972 * <p>
3973 * In order for the progress bar to be shown, the feature must be requested
3974 * via {@link #requestWindowFeature(int)}.
3975 *
3976 * @param visible Whether to show the progress bars in the title.
3977 */
3978 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3979 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3980 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3981 }
3982
3983 /**
3984 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3985 * is always indeterminate).
3986 * <p>
3987 * In order for the progress bar to be shown, the feature must be requested
3988 * via {@link #requestWindowFeature(int)}.
3989 *
3990 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3991 */
3992 public final void setProgressBarIndeterminate(boolean indeterminate) {
3993 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3994 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3995 }
3996
3997 /**
3998 * Sets the progress for the progress bars in the title.
3999 * <p>
4000 * In order for the progress bar to be shown, the feature must be requested
4001 * via {@link #requestWindowFeature(int)}.
4002 *
4003 * @param progress The progress for the progress bar. Valid ranges are from
4004 * 0 to 10000 (both inclusive). If 10000 is given, the progress
4005 * bar will be completely filled and will fade out.
4006 */
4007 public final void setProgress(int progress) {
4008 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
4009 }
4010
4011 /**
4012 * Sets the secondary progress for the progress bar in the title. This
4013 * progress is drawn between the primary progress (set via
4014 * {@link #setProgress(int)} and the background. It can be ideal for media
4015 * scenarios such as showing the buffering progress while the default
4016 * progress shows the play progress.
4017 * <p>
4018 * In order for the progress bar to be shown, the feature must be requested
4019 * via {@link #requestWindowFeature(int)}.
4020 *
4021 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
4022 * 0 to 10000 (both inclusive).
4023 */
4024 public final void setSecondaryProgress(int secondaryProgress) {
4025 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4026 secondaryProgress + Window.PROGRESS_SECONDARY_START);
4027 }
4028
4029 /**
4030 * Suggests an audio stream whose volume should be changed by the hardware
4031 * volume controls.
4032 * <p>
4033 * The suggested audio stream will be tied to the window of this Activity.
4034 * If the Activity is switched, the stream set here is no longer the
4035 * suggested stream. The client does not need to save and restore the old
4036 * suggested stream value in onPause and onResume.
4037 *
4038 * @param streamType The type of the audio stream whose volume should be
4039 * changed by the hardware volume controls. It is not guaranteed that
4040 * the hardware volume controls will always change this stream's
4041 * volume (for example, if a call is in progress, its stream's volume
4042 * may be changed instead). To reset back to the default, use
4043 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4044 */
4045 public final void setVolumeControlStream(int streamType) {
4046 getWindow().setVolumeControlStream(streamType);
4047 }
4048
4049 /**
4050 * Gets the suggested audio stream whose volume should be changed by the
4051 * harwdare volume controls.
4052 *
4053 * @return The suggested audio stream type whose volume should be changed by
4054 * the hardware volume controls.
4055 * @see #setVolumeControlStream(int)
4056 */
4057 public final int getVolumeControlStream() {
4058 return getWindow().getVolumeControlStream();
4059 }
4060
4061 /**
4062 * Runs the specified action on the UI thread. If the current thread is the UI
4063 * thread, then the action is executed immediately. If the current thread is
4064 * not the UI thread, the action is posted to the event queue of the UI thread.
4065 *
4066 * @param action the action to run on the UI thread
4067 */
4068 public final void runOnUiThread(Runnable action) {
4069 if (Thread.currentThread() != mUiThread) {
4070 mHandler.post(action);
4071 } else {
4072 action.run();
4073 }
4074 }
4075
4076 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004077 * Standard implementation of
4078 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4079 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004080 * This implementation does nothing and is for
4081 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4082 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4083 *
4084 * @see android.view.LayoutInflater#createView
4085 * @see android.view.Window#getLayoutInflater
4086 */
4087 public View onCreateView(String name, Context context, AttributeSet attrs) {
4088 return null;
4089 }
4090
4091 /**
4092 * Standard implementation of
4093 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4094 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004095 * This implementation handles <fragment> tags to embed fragments inside
4096 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 *
4098 * @see android.view.LayoutInflater#createView
4099 * @see android.view.Window#getLayoutInflater
4100 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004101 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004102 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004103 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004104 }
4105
Dianne Hackborndef15372010-08-15 12:43:52 -07004106 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004107 TypedArray a =
4108 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004109 if (fname == null) {
4110 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4111 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004112 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004113 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4114 a.recycle();
4115
Dianne Hackborn625ac272010-09-17 18:29:22 -07004116 int containerId = parent != null ? parent.getId() : 0;
4117 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004118 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004119 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004120 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004121
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004122 // If we restored from a previous state, we may already have
4123 // instantiated this fragment from the state and should use
4124 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004125 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4126 if (fragment == null && tag != null) {
4127 fragment = mFragments.findFragmentByTag(tag);
4128 }
4129 if (fragment == null && containerId != View.NO_ID) {
4130 fragment = mFragments.findFragmentById(containerId);
4131 }
4132
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004133 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4134 + Integer.toHexString(id) + " fname=" + fname
4135 + " existing=" + fragment);
4136 if (fragment == null) {
4137 fragment = Fragment.instantiate(this, fname);
4138 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004139 fragment.mFragmentId = id != 0 ? id : containerId;
4140 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004141 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004142 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004143 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004144 fragment.mFragmentManager = mFragments;
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004145 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004146 mFragments.addFragment(fragment, true);
4147
4148 } else if (fragment.mInLayout) {
4149 // A fragment already exists and it is not one we restored from
4150 // previous state.
4151 throw new IllegalArgumentException(attrs.getPositionDescription()
4152 + ": Duplicate id 0x" + Integer.toHexString(id)
4153 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4154 + " with another fragment for " + fname);
4155 } else {
4156 // This fragment was retained from a previous instance; get it
4157 // going now.
4158 fragment.mInLayout = true;
4159 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004160 // If this fragment is newly instantiated (either right now, or
4161 // from last saved state), then give it the attributes to
4162 // initialize itself.
4163 if (!fragment.mRetaining) {
Dianne Hackborne3a7f622011-03-03 21:48:24 -08004164 fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
Dianne Hackborndef15372010-08-15 12:43:52 -07004165 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004166 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004167 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004168
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004169 if (fragment.mView == null) {
4170 throw new IllegalStateException("Fragment " + fname
4171 + " did not create a view.");
4172 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004173 if (id != 0) {
4174 fragment.mView.setId(id);
4175 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004176 if (fragment.mView.getTag() == null) {
4177 fragment.mView.setTag(tag);
4178 }
4179 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
4181
Daniel Sandler69a48172010-06-23 16:29:36 -04004182 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004183 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004184 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004185 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004186 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004187 * @param fd The raw file descriptor that the dump is being sent to.
4188 * @param writer The PrintWriter to which you should dump your state. This will be
4189 * closed for you after you return.
4190 * @param args additional arguments to the dump request.
4191 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004192 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4193 writer.print(prefix); writer.print("Local Activity ");
4194 writer.print(Integer.toHexString(System.identityHashCode(this)));
4195 writer.println(" State:");
4196 String innerPrefix = prefix + " ";
4197 writer.print(innerPrefix); writer.print("mResumed=");
4198 writer.print(mResumed); writer.print(" mStopped=");
4199 writer.print(mStopped); writer.print(" mFinished=");
4200 writer.println(mFinished);
4201 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4202 writer.println(mLoadersStarted);
4203 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4204 writer.println(mChangingConfigurations);
4205 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4206 writer.println(mCurrentConfig);
4207 if (mLoaderManager != null) {
4208 writer.print(prefix); writer.print("Loader Manager ");
4209 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4210 writer.println(":");
4211 mLoaderManager.dump(prefix + " ", fd, writer, args);
4212 }
4213 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004214 }
4215
4216 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004217 * Bit indicating that this activity is "immersive" and should not be
4218 * interrupted by notifications if possible.
4219 *
4220 * This value is initially set by the manifest property
4221 * <code>android:immersive</code> but may be changed at runtime by
4222 * {@link #setImmersive}.
4223 *
4224 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004225 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004226 */
4227 public boolean isImmersive() {
4228 try {
4229 return ActivityManagerNative.getDefault().isImmersive(mToken);
4230 } catch (RemoteException e) {
4231 return false;
4232 }
4233 }
4234
4235 /**
4236 * Adjust the current immersive mode setting.
4237 *
4238 * Note that changing this value will have no effect on the activity's
4239 * {@link android.content.pm.ActivityInfo} structure; that is, if
4240 * <code>android:immersive</code> is set to <code>true</code>
4241 * in the application's manifest entry for this activity, the {@link
4242 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4243 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4244 * FLAG_IMMERSIVE} bit set.
4245 *
4246 * @see #isImmersive
4247 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004248 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004249 */
4250 public void setImmersive(boolean i) {
4251 try {
4252 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4253 } catch (RemoteException e) {
4254 // pass
4255 }
4256 }
4257
Adam Powell6e346362010-07-23 10:18:23 -07004258 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004259 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004260 *
4261 * @param callback Callback that will manage lifecycle events for this context mode
4262 * @return The ContextMode that was started, or null if it was canceled
4263 *
4264 * @see ActionMode
4265 */
Adam Powell5d279772010-07-27 16:34:07 -07004266 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004267 return mWindow.getDecorView().startActionMode(callback);
4268 }
4269
Adam Powelldebf3be2010-11-15 18:58:48 -08004270 /**
4271 * Give the Activity a chance to control the UI for an action mode requested
4272 * by the system.
4273 *
4274 * <p>Note: If you are looking for a notification callback that an action mode
4275 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4276 *
4277 * @param callback The callback that should control the new action mode
4278 * @return The new action mode, or <code>null</code> if the activity does not want to
4279 * provide special handling for this action mode. (It will be handled by the system.)
4280 */
4281 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004282 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004283 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004284 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004285 }
4286 return null;
4287 }
4288
Adam Powelldebf3be2010-11-15 18:58:48 -08004289 /**
4290 * Notifies the Activity that an action mode has been started.
4291 * Activity subclasses overriding this method should call the superclass implementation.
4292 *
4293 * @param mode The new action mode.
4294 */
4295 public void onActionModeStarted(ActionMode mode) {
4296 }
4297
4298 /**
4299 * Notifies the activity that an action mode has finished.
4300 * Activity subclasses overriding this method should call the superclass implementation.
4301 *
4302 * @param mode The action mode that just finished.
4303 */
4304 public void onActionModeFinished(ActionMode mode) {
4305 }
4306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 // ------------------ Internal API ------------------
4308
4309 final void setParent(Activity parent) {
4310 mParent = parent;
4311 }
4312
4313 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4314 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004315 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004317 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004318 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 }
4320
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004321 final void attach(Context context, ActivityThread aThread,
4322 Instrumentation instr, IBinder token, int ident,
4323 Application application, Intent intent, ActivityInfo info,
4324 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004325 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004326 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 attachBaseContext(context);
4328
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004329 mFragments.attachActivity(this);
4330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 mWindow = PolicyManager.makeNewWindow(this);
4332 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08004333 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4335 mWindow.setSoftInputMode(info.softInputMode);
4336 }
4337 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 mMainThread = aThread;
4340 mInstrumentation = instr;
4341 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004342 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 mApplication = application;
4344 mIntent = intent;
4345 mComponent = intent.getComponent();
4346 mActivityInfo = info;
4347 mTitle = title;
4348 mParent = parent;
4349 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004350 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351
Romain Guy529b60a2010-08-03 18:05:47 -07004352 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4353 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 if (mParent != null) {
4355 mWindow.setContainer(mParent.getWindow());
4356 }
4357 mWindowManager = mWindow.getWindowManager();
4358 mCurrentConfig = config;
4359 }
4360
4361 final IBinder getActivityToken() {
4362 return mParent != null ? mParent.getActivityToken() : mToken;
4363 }
4364
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004365 final void performCreate(Bundle icicle) {
4366 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004367 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4368 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004369 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004370 }
4371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004373 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004375 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 mInstrumentation.callActivityOnStart(this);
4377 if (!mCalled) {
4378 throw new SuperNotCalledException(
4379 "Activity " + mComponent.toShortString() +
4380 " did not call through to super.onStart()");
4381 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004382 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004383 if (mAllLoaderManagers != null) {
4384 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4385 mAllLoaderManagers.valueAt(i).finishRetain();
4386 }
4387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 }
4389
4390 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004391 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004392
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004393 synchronized (mManagedCursors) {
4394 final int N = mManagedCursors.size();
4395 for (int i=0; i<N; i++) {
4396 ManagedCursor mc = mManagedCursors.get(i);
4397 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004398 if (!mc.mCursor.requery()) {
4399 throw new IllegalStateException(
4400 "trying to requery an already closed cursor");
4401 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004402 mc.mReleased = false;
4403 mc.mUpdated = false;
4404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 }
4406 }
4407
4408 if (mStopped) {
4409 mStopped = false;
4410 mCalled = false;
Dianne Hackbornce418e62011-03-01 14:31:38 -08004411 if (mToken != null && mParent == null) {
4412 WindowManagerImpl.getDefault().setStoppedState(mToken, false);
4413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 mInstrumentation.callActivityOnRestart(this);
4415 if (!mCalled) {
4416 throw new SuperNotCalledException(
4417 "Activity " + mComponent.toShortString() +
4418 " did not call through to super.onRestart()");
4419 }
4420 performStart();
4421 }
4422 }
4423
4424 final void performResume() {
4425 performRestart();
4426
Dianne Hackborn445646c2010-06-25 15:52:59 -07004427 mFragments.execPendingActions();
4428
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004429 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06004432 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 mInstrumentation.callActivityOnResume(this);
4434 if (!mCalled) {
4435 throw new SuperNotCalledException(
4436 "Activity " + mComponent.toShortString() +
4437 " did not call through to super.onResume()");
4438 }
4439
4440 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004442
4443 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004444 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 onPostResume();
4447 if (!mCalled) {
4448 throw new SuperNotCalledException(
4449 "Activity " + mComponent.toShortString() +
4450 " did not call through to super.onPostResume()");
4451 }
4452 }
4453
4454 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004455 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004456 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004458 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004459 if (!mCalled && getApplicationInfo().targetSdkVersion
4460 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4461 throw new SuperNotCalledException(
4462 "Activity " + mComponent.toShortString() +
4463 " did not call through to super.onPause()");
4464 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06004465 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 }
4467
4468 final void performUserLeaving() {
4469 onUserInteraction();
4470 onUserLeaveHint();
4471 }
4472
4473 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004474 if (mLoadersStarted) {
4475 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004476 if (mLoaderManager != null) {
4477 if (!mChangingConfigurations) {
4478 mLoaderManager.doStop();
4479 } else {
4480 mLoaderManager.doRetain();
4481 }
4482 }
4483 }
4484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 if (!mStopped) {
4486 if (mWindow != null) {
4487 mWindow.closeAllPanels();
4488 }
4489
Dianne Hackbornce418e62011-03-01 14:31:38 -08004490 if (mToken != null && mParent == null) {
4491 WindowManagerImpl.getDefault().setStoppedState(mToken, true);
4492 }
4493
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004494 mFragments.dispatchStop();
4495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 mCalled = false;
4497 mInstrumentation.callActivityOnStop(this);
4498 if (!mCalled) {
4499 throw new SuperNotCalledException(
4500 "Activity " + mComponent.toShortString() +
4501 " did not call through to super.onStop()");
4502 }
4503
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004504 synchronized (mManagedCursors) {
4505 final int N = mManagedCursors.size();
4506 for (int i=0; i<N; i++) {
4507 ManagedCursor mc = mManagedCursors.get(i);
4508 if (!mc.mReleased) {
4509 mc.mCursor.deactivate();
4510 mc.mReleased = true;
4511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
4513 }
4514
4515 mStopped = true;
4516 }
4517 mResumed = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08004518
4519 // Check for Activity leaks, if enabled.
4520 StrictMode.conditionallyCheckInstanceCounts();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 }
4522
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004523 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004524 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004525 mFragments.dispatchDestroy();
4526 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004527 if (mLoaderManager != null) {
4528 mLoaderManager.doDestroy();
4529 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004530 }
4531
Jeff Hamilton52d32032011-01-08 15:31:26 -06004532 /**
4533 * @hide
4534 */
4535 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 return mResumed;
4537 }
4538
4539 void dispatchActivityResult(String who, int requestCode,
4540 int resultCode, Intent data) {
4541 if (Config.LOGV) Log.v(
4542 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4543 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004544 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 if (who == null) {
4546 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004547 } else {
4548 Fragment frag = mFragments.findFragmentByWho(who);
4549 if (frag != null) {
4550 frag.onActivityResult(requestCode, resultCode, data);
4551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 }
4553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554}