blob: aed0fa384704d727461c5faaaa9bc965c06e8615 [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;
Adam Powell6e346362010-07-23 10:18:23 -070069import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070071import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.view.ViewManager;
73import android.view.Window;
74import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070075import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.widget.AdapterView;
77
Dianne Hackborn625ac272010-09-17 18:29:22 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070080import java.util.ArrayList;
81import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83/**
84 * An activity is a single, focused thing that the user can do. Almost all
85 * activities interact with the user, so the Activity class takes care of
86 * creating a window for you in which you can place your UI with
87 * {@link #setContentView}. While activities are often presented to the user
88 * as full-screen windows, they can also be used in other ways: as floating
89 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
90 * or embedded inside of another activity (using {@link ActivityGroup}).
91 *
92 * There are two methods almost all subclasses of Activity will implement:
93 *
94 * <ul>
95 * <li> {@link #onCreate} is where you initialize your activity. Most
96 * importantly, here you will usually call {@link #setContentView(int)}
97 * with a layout resource defining your UI, and using {@link #findViewById}
98 * to retrieve the widgets in that UI that you need to interact with
99 * programmatically.
100 *
101 * <li> {@link #onPause} is where you deal with the user leaving your
102 * activity. Most importantly, any changes made by the user should at this
103 * point be committed (usually to the
104 * {@link android.content.ContentProvider} holding the data).
105 * </ul>
106 *
107 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
108 * activity classes must have a corresponding
109 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
110 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
111 *
112 * <p>The Activity class is an important part of an application's overall lifecycle,
113 * and the way activities are launched and put together is a fundamental
114 * part of the platform's application model. For a detailed perspective on the structure of
115 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
116 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
117 *
118 * <p>Topics covered here:
119 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700120 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
122 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
123 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
124 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
125 * <li><a href="#Permissions">Permissions</a>
126 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
127 * </ol>
128 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700129 * <a name="Fragments"></a>
130 * <h3>Fragments</h3>
131 *
132 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
133 * implementations can make use of the {@link Fragment} class to better
134 * modularize their code, build more sophisticated user interfaces for larger
135 * screens, and help scale their application between small and large screens.
136 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 * <a name="ActivityLifecycle"></a>
138 * <h3>Activity Lifecycle</h3>
139 *
140 * <p>Activities in the system are managed as an <em>activity stack</em>.
141 * When a new activity is started, it is placed on the top of the stack
142 * and becomes the running activity -- the previous activity always remains
143 * below it in the stack, and will not come to the foreground again until
144 * the new activity exits.</p>
145 *
146 * <p>An activity has essentially four states:</p>
147 * <ul>
148 * <li> If an activity in the foreground of the screen (at the top of
149 * the stack),
150 * it is <em>active</em> or <em>running</em>. </li>
151 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
152 * or transparent activity has focus on top of your activity), it
153 * is <em>paused</em>. A paused activity is completely alive (it
154 * maintains all state and member information and remains attached to
155 * the window manager), but can be killed by the system in extreme
156 * low memory situations.
157 * <li>If an activity is completely obscured by another activity,
158 * it is <em>stopped</em>. It still retains all state and member information,
159 * however, it is no longer visible to the user so its window is hidden
160 * and it will often be killed by the system when memory is needed
161 * elsewhere.</li>
162 * <li>If an activity is paused or stopped, the system can drop the activity
163 * from memory by either asking it to finish, or simply killing its
164 * process. When it is displayed again to the user, it must be
165 * completely restarted and restored to its previous state.</li>
166 * </ul>
167 *
168 * <p>The following diagram shows the important state paths of an Activity.
169 * The square rectangles represent callback methods you can implement to
170 * perform operations when the Activity moves between states. The colored
171 * ovals are major states the Activity can be in.</p>
172 *
173 * <p><img src="../../../images/activity_lifecycle.png"
174 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
175 *
176 * <p>There are three key loops you may be interested in monitoring within your
177 * activity:
178 *
179 * <ul>
180 * <li>The <b>entire lifetime</b> of an activity happens between the first call
181 * to {@link android.app.Activity#onCreate} through to a single final call
182 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
183 * of "global" state in onCreate(), and release all remaining resources in
184 * onDestroy(). For example, if it has a thread running in the background
185 * to download data from the network, it may create that thread in onCreate()
186 * and then stop the thread in onDestroy().
187 *
188 * <li>The <b>visible lifetime</b> of an activity happens between a call to
189 * {@link android.app.Activity#onStart} until a corresponding call to
190 * {@link android.app.Activity#onStop}. During this time the user can see the
191 * activity on-screen, though it may not be in the foreground and interacting
192 * with the user. Between these two methods you can maintain resources that
193 * are needed to show the activity to the user. For example, you can register
194 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
195 * that impact your UI, and unregister it in onStop() when the user an no
196 * longer see what you are displaying. The onStart() and onStop() methods
197 * can be called multiple times, as the activity becomes visible and hidden
198 * to the user.
199 *
200 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
201 * {@link android.app.Activity#onResume} until a corresponding call to
202 * {@link android.app.Activity#onPause}. During this time the activity is
203 * in front of all other activities and interacting with the user. An activity
204 * can frequently go between the resumed and paused states -- for example when
205 * the device goes to sleep, when an activity result is delivered, when a new
206 * intent is delivered -- so the code in these methods should be fairly
207 * lightweight.
208 * </ul>
209 *
210 * <p>The entire lifecycle of an activity is defined by the following
211 * Activity methods. All of these are hooks that you can override
212 * to do appropriate work when the activity changes state. All
213 * activities will implement {@link android.app.Activity#onCreate}
214 * to do their initial setup; many will also implement
215 * {@link android.app.Activity#onPause} to commit changes to data and
216 * otherwise prepare to stop interacting with the user. You should always
217 * call up to your superclass when implementing these methods.</p>
218 *
219 * </p>
220 * <pre class="prettyprint">
221 * public class Activity extends ApplicationContext {
222 * protected void onCreate(Bundle savedInstanceState);
223 *
224 * protected void onStart();
225 *
226 * protected void onRestart();
227 *
228 * protected void onResume();
229 *
230 * protected void onPause();
231 *
232 * protected void onStop();
233 *
234 * protected void onDestroy();
235 * }
236 * </pre>
237 *
238 * <p>In general the movement through an activity's lifecycle looks like
239 * this:</p>
240 *
241 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
242 * <colgroup align="left" span="3" />
243 * <colgroup align="left" />
244 * <colgroup align="center" />
245 * <colgroup align="center" />
246 *
247 * <thead>
248 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
249 * </thead>
250 *
251 * <tbody>
252 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
253 * <td>Called when the activity is first created.
254 * This is where you should do all of your normal static set up:
255 * create views, bind data to lists, etc. This method also
256 * provides you with a Bundle containing the activity's previously
257 * frozen state, if there was one.
258 * <p>Always followed by <code>onStart()</code>.</td>
259 * <td align="center">No</td>
260 * <td align="center"><code>onStart()</code></td>
261 * </tr>
262 *
263 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
264 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
265 * <td>Called after your activity has been stopped, prior to it being
266 * started again.
267 * <p>Always followed by <code>onStart()</code></td>
268 * <td align="center">No</td>
269 * <td align="center"><code>onStart()</code></td>
270 * </tr>
271 *
272 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
273 * <td>Called when the activity is becoming visible to the user.
274 * <p>Followed by <code>onResume()</code> if the activity comes
275 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
276 * <td align="center">No</td>
277 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
278 * </tr>
279 *
280 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
281 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
282 * <td>Called when the activity will start
283 * interacting with the user. At this point your activity is at
284 * the top of the activity stack, with user input going to it.
285 * <p>Always followed by <code>onPause()</code>.</td>
286 * <td align="center">No</td>
287 * <td align="center"><code>onPause()</code></td>
288 * </tr>
289 *
290 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
291 * <td>Called when the system is about to start resuming a previous
292 * activity. This is typically used to commit unsaved changes to
293 * persistent data, stop animations and other things that may be consuming
294 * CPU, etc. Implementations of this method must be very quick because
295 * the next activity will not be resumed until this method returns.
296 * <p>Followed by either <code>onResume()</code> if the activity
297 * returns back to the front, or <code>onStop()</code> if it becomes
298 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800299 * <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 -0800300 * <td align="center"><code>onResume()</code> or<br>
301 * <code>onStop()</code></td>
302 * </tr>
303 *
304 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
305 * <td>Called when the activity is no longer visible to the user, because
306 * another activity has been resumed and is covering this one. This
307 * may happen either because a new activity is being started, an existing
308 * one is being brought in front of this one, or this one is being
309 * destroyed.
310 * <p>Followed by either <code>onRestart()</code> if
311 * this activity is coming back to interact with the user, or
312 * <code>onDestroy()</code> if this activity is going away.</td>
313 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
314 * <td align="center"><code>onRestart()</code> or<br>
315 * <code>onDestroy()</code></td>
316 * </tr>
317 *
318 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
319 * <td>The final call you receive before your
320 * activity is destroyed. This can happen either because the
321 * activity is finishing (someone called {@link Activity#finish} on
322 * it, or because the system is temporarily destroying this
323 * instance of the activity to save space. You can distinguish
324 * between these two scenarios with the {@link
325 * Activity#isFinishing} method.</td>
326 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
327 * <td align="center"><em>nothing</em></td>
328 * </tr>
329 * </tbody>
330 * </table>
331 *
332 * <p>Note the "Killable" column in the above table -- for those methods that
333 * are marked as being killable, after that method returns the process hosting the
334 * activity may killed by the system <em>at any time</em> without another line
335 * of its code being executed. Because of this, you should use the
336 * {@link #onPause} method to write any persistent data (such as user edits)
337 * to storage. In addition, the method
338 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
339 * in such a background state, allowing you to save away any dynamic instance
340 * state in your activity into the given Bundle, to be later received in
341 * {@link #onCreate} if the activity needs to be re-created.
342 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
343 * section for more information on how the lifecycle of a process is tied
344 * to the activities it is hosting. Note that it is important to save
345 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
346 * because the later is not part of the lifecycle callbacks, so will not
347 * be called in every situation as described in its documentation.</p>
348 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800349 * <p class="note">Be aware that these semantics will change slightly between
350 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
351 * vs. those targeting prior platforms. Starting with Honeycomb, an application
352 * is not in the killable state until its {@link #onStop} has returned. This
353 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
354 * safely called after {@link #onPause()} and allows and application to safely
355 * wait until {@link #onStop()} to save persistent state.</p>
356 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 * <p>For those methods that are not marked as being killable, the activity's
358 * process will not be killed by the system starting from the time the method
359 * is called and continuing after it returns. Thus an activity is in the killable
360 * state, for example, between after <code>onPause()</code> to the start of
361 * <code>onResume()</code>.</p>
362 *
363 * <a name="ConfigurationChanges"></a>
364 * <h3>Configuration Changes</h3>
365 *
366 * <p>If the configuration of the device (as defined by the
367 * {@link Configuration Resources.Configuration} class) changes,
368 * then anything displaying a user interface will need to update to match that
369 * configuration. Because Activity is the primary mechanism for interacting
370 * with the user, it includes special support for handling configuration
371 * changes.</p>
372 *
373 * <p>Unless you specify otherwise, a configuration change (such as a change
374 * in screen orientation, language, input devices, etc) will cause your
375 * current activity to be <em>destroyed</em>, going through the normal activity
376 * lifecycle process of {@link #onPause},
377 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
378 * had been in the foreground or visible to the user, once {@link #onDestroy} is
379 * called in that instance then a new instance of the activity will be
380 * created, with whatever savedInstanceState the previous instance had generated
381 * from {@link #onSaveInstanceState}.</p>
382 *
383 * <p>This is done because any application resource,
384 * including layout files, can change based on any configuration value. Thus
385 * the only safe way to handle a configuration change is to re-retrieve all
386 * resources, including layouts, drawables, and strings. Because activities
387 * must already know how to save their state and re-create themselves from
388 * that state, this is a convenient way to have an activity restart itself
389 * with a new configuration.</p>
390 *
391 * <p>In some special cases, you may want to bypass restarting of your
392 * activity based on one or more types of configuration changes. This is
393 * done with the {@link android.R.attr#configChanges android:configChanges}
394 * attribute in its manifest. For any types of configuration changes you say
395 * that you handle there, you will receive a call to your current activity's
396 * {@link #onConfigurationChanged} method instead of being restarted. If
397 * a configuration change involves any that you do not handle, however, the
398 * activity will still be restarted and {@link #onConfigurationChanged}
399 * will not be called.</p>
400 *
401 * <a name="StartingActivities"></a>
402 * <h3>Starting Activities and Getting Results</h3>
403 *
404 * <p>The {@link android.app.Activity#startActivity}
405 * method is used to start a
406 * new activity, which will be placed at the top of the activity stack. It
407 * takes a single argument, an {@link android.content.Intent Intent},
408 * which describes the activity
409 * to be executed.</p>
410 *
411 * <p>Sometimes you want to get a result back from an activity when it
412 * ends. For example, you may start an activity that lets the user pick
413 * a person in a list of contacts; when it ends, it returns the person
414 * that was selected. To do this, you call the
415 * {@link android.app.Activity#startActivityForResult(Intent, int)}
416 * version with a second integer parameter identifying the call. The result
417 * will come back through your {@link android.app.Activity#onActivityResult}
418 * method.</p>
419 *
420 * <p>When an activity exits, it can call
421 * {@link android.app.Activity#setResult(int)}
422 * to return data back to its parent. It must always supply a result code,
423 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
424 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
425 * return back an Intent containing any additional data it wants. All of this
426 * information appears back on the
427 * parent's <code>Activity.onActivityResult()</code>, along with the integer
428 * identifier it originally supplied.</p>
429 *
430 * <p>If a child activity fails for any reason (such as crashing), the parent
431 * activity will receive a result with the code RESULT_CANCELED.</p>
432 *
433 * <pre class="prettyprint">
434 * public class MyActivity extends Activity {
435 * ...
436 *
437 * static final int PICK_CONTACT_REQUEST = 0;
438 *
439 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
440 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
441 * // When the user center presses, let them pick a contact.
442 * startActivityForResult(
443 * new Intent(Intent.ACTION_PICK,
444 * new Uri("content://contacts")),
445 * PICK_CONTACT_REQUEST);
446 * return true;
447 * }
448 * return false;
449 * }
450 *
451 * protected void onActivityResult(int requestCode, int resultCode,
452 * Intent data) {
453 * if (requestCode == PICK_CONTACT_REQUEST) {
454 * if (resultCode == RESULT_OK) {
455 * // A contact was picked. Here we will just display it
456 * // to the user.
457 * startActivity(new Intent(Intent.ACTION_VIEW, data));
458 * }
459 * }
460 * }
461 * }
462 * </pre>
463 *
464 * <a name="SavingPersistentState"></a>
465 * <h3>Saving Persistent State</h3>
466 *
467 * <p>There are generally two kinds of persistent state than an activity
468 * will deal with: shared document-like data (typically stored in a SQLite
469 * database using a {@linkplain android.content.ContentProvider content provider})
470 * and internal state such as user preferences.</p>
471 *
472 * <p>For content provider data, we suggest that activities use a
473 * "edit in place" user model. That is, any edits a user makes are effectively
474 * made immediately without requiring an additional confirmation step.
475 * Supporting this model is generally a simple matter of following two rules:</p>
476 *
477 * <ul>
478 * <li> <p>When creating a new document, the backing database entry or file for
479 * it is created immediately. For example, if the user chooses to write
480 * a new e-mail, a new entry for that e-mail is created as soon as they
481 * start entering data, so that if they go to any other activity after
482 * that point this e-mail will now appear in the list of drafts.</p>
483 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
484 * commit to the backing content provider or file any changes the user
485 * has made. This ensures that those changes will be seen by any other
486 * activity that is about to run. You will probably want to commit
487 * your data even more aggressively at key times during your
488 * activity's lifecycle: for example before starting a new
489 * activity, before finishing your own activity, when the user
490 * switches between input fields, etc.</p>
491 * </ul>
492 *
493 * <p>This model is designed to prevent data loss when a user is navigating
494 * between activities, and allows the system to safely kill an activity (because
495 * system resources are needed somewhere else) at any time after it has been
496 * paused. Note this implies
497 * that the user pressing BACK from your activity does <em>not</em>
498 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800499 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
501 *
502 * <p>See the {@linkplain android.content.ContentProvider content package} for
503 * more information about content providers. These are a key aspect of how
504 * different activities invoke and propagate data between themselves.</p>
505 *
506 * <p>The Activity class also provides an API for managing internal persistent state
507 * associated with an activity. This can be used, for example, to remember
508 * the user's preferred initial display in a calendar (day view or week view)
509 * or the user's default home page in a web browser.</p>
510 *
511 * <p>Activity persistent state is managed
512 * with the method {@link #getPreferences},
513 * allowing you to retrieve and
514 * modify a set of name/value pairs associated with the activity. To use
515 * preferences that are shared across multiple application components
516 * (activities, receivers, services, providers), you can use the underlying
517 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
518 * to retrieve a preferences
519 * object stored under a specific name.
520 * (Note that it is not possible to share settings data across application
521 * packages -- for that you will need a content provider.)</p>
522 *
523 * <p>Here is an excerpt from a calendar activity that stores the user's
524 * preferred view mode in its persistent settings:</p>
525 *
526 * <pre class="prettyprint">
527 * public class CalendarActivity extends Activity {
528 * ...
529 *
530 * static final int DAY_VIEW_MODE = 0;
531 * static final int WEEK_VIEW_MODE = 1;
532 *
533 * private SharedPreferences mPrefs;
534 * private int mCurViewMode;
535 *
536 * protected void onCreate(Bundle savedInstanceState) {
537 * super.onCreate(savedInstanceState);
538 *
539 * SharedPreferences mPrefs = getSharedPreferences();
540 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
541 * }
542 *
543 * protected void onPause() {
544 * super.onPause();
545 *
546 * SharedPreferences.Editor ed = mPrefs.edit();
547 * ed.putInt("view_mode", mCurViewMode);
548 * ed.commit();
549 * }
550 * }
551 * </pre>
552 *
553 * <a name="Permissions"></a>
554 * <h3>Permissions</h3>
555 *
556 * <p>The ability to start a particular Activity can be enforced when it is
557 * declared in its
558 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
559 * tag. By doing so, other applications will need to declare a corresponding
560 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
561 * element in their own manifest to be able to start that activity.
562 *
563 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
564 * document for more information on permissions and security in general.
565 *
566 * <a name="ProcessLifecycle"></a>
567 * <h3>Process Lifecycle</h3>
568 *
569 * <p>The Android system attempts to keep application process around for as
570 * long as possible, but eventually will need to remove old processes when
571 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
572 * Lifecycle</a>, the decision about which process to remove is intimately
573 * tied to the state of the user's interaction with it. In general, there
574 * are four states a process can be in based on the activities running in it,
575 * listed here in order of importance. The system will kill less important
576 * processes (the last ones) before it resorts to killing more important
577 * processes (the first ones).
578 *
579 * <ol>
580 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
581 * that the user is currently interacting with) is considered the most important.
582 * Its process will only be killed as a last resort, if it uses more memory
583 * than is available on the device. Generally at this point the device has
584 * reached a memory paging state, so this is required in order to keep the user
585 * interface responsive.
586 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
587 * but not in the foreground, such as one sitting behind a foreground dialog)
588 * is considered extremely important and will not be killed unless that is
589 * required to keep the foreground activity running.
590 * <li> <p>A <b>background activity</b> (an activity that is not visible to
591 * the user and has been paused) is no longer critical, so the system may
592 * safely kill its process to reclaim memory for other foreground or
593 * visible processes. If its process needs to be killed, when the user navigates
594 * back to the activity (making it visible on the screen again), its
595 * {@link #onCreate} method will be called with the savedInstanceState it had previously
596 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
597 * state as the user last left it.
598 * <li> <p>An <b>empty process</b> is one hosting no activities or other
599 * application components (such as {@link Service} or
600 * {@link android.content.BroadcastReceiver} classes). These are killed very
601 * quickly by the system as memory becomes low. For this reason, any
602 * background operation you do outside of an activity must be executed in the
603 * context of an activity BroadcastReceiver or Service to ensure that the system
604 * knows it needs to keep your process around.
605 * </ol>
606 *
607 * <p>Sometimes an Activity may need to do a long-running operation that exists
608 * independently of the activity lifecycle itself. An example may be a camera
609 * application that allows you to upload a picture to a web site. The upload
610 * may take a long time, and the application should allow the user to leave
611 * the application will it is executing. To accomplish this, your Activity
612 * should start a {@link Service} in which the upload takes place. This allows
613 * the system to properly prioritize your process (considering it to be more
614 * important than other non-visible applications) for the duration of the
615 * upload, independent of whether the original activity is paused, stopped,
616 * or finished.
617 */
618public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700619 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 Window.Callback, KeyEvent.Callback,
621 OnCreateContextMenuListener, ComponentCallbacks {
622 private static final String TAG = "Activity";
623
624 /** Standard activity result: operation canceled. */
625 public static final int RESULT_CANCELED = 0;
626 /** Standard activity result: operation succeeded. */
627 public static final int RESULT_OK = -1;
628 /** Start of user-defined activity results. */
629 public static final int RESULT_FIRST_USER = 1;
630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700632 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
634 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
635 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800636 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800638 private static class ManagedDialog {
639 Dialog mDialog;
640 Bundle mArgs;
641 }
642 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643
644 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
645 private Instrumentation mInstrumentation;
646 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700647 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 /*package*/ String mEmbeddedID;
649 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700650 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 private ComponentName mComponent;
652 /*package*/ ActivityInfo mActivityInfo;
653 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 Activity mParent;
655 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700656 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700657 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600658 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 private boolean mStopped;
660 boolean mFinished;
661 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700662 /** true if the activity is going through a transient pause */
663 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500664 /** true if the activity is being destroyed in order to recreate it with a new configuration */
665 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 /*package*/ int mConfigChangeFlags;
667 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100668 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700670 static final class NonConfigurationInstances {
671 Object activity;
672 HashMap<String, Object> children;
673 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700674 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700675 }
676 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 private Window mWindow;
679
680 private WindowManager mWindowManager;
681 /*package*/ View mDecor = null;
682 /*package*/ boolean mWindowAdded = false;
683 /*package*/ boolean mVisibleFromServer = false;
684 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700685 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686
687 private CharSequence mTitle;
688 private int mTitleColor = 0;
689
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700690 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700691
Dianne Hackborn4911b782010-07-15 12:54:39 -0700692 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
693 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 private static final class ManagedCursor {
696 ManagedCursor(Cursor cursor) {
697 mCursor = cursor;
698 mReleased = false;
699 mUpdated = false;
700 }
701
702 private final Cursor mCursor;
703 private boolean mReleased;
704 private boolean mUpdated;
705 }
706 private final ArrayList<ManagedCursor> mManagedCursors =
707 new ArrayList<ManagedCursor>();
708
709 // protected by synchronized (this)
710 int mResultCode = RESULT_CANCELED;
711 Intent mResultData = null;
712
713 private boolean mTitleReady = false;
714
715 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
716 private SpannableStringBuilder mDefaultKeySsb = null;
717
718 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
719
720 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700721 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 /** Return the intent that started this activity. */
724 public Intent getIntent() {
725 return mIntent;
726 }
727
728 /**
729 * Change the intent returned by {@link #getIntent}. This holds a
730 * reference to the given intent; it does not copy it. Often used in
731 * conjunction with {@link #onNewIntent}.
732 *
733 * @param newIntent The new Intent object to return from getIntent
734 *
735 * @see #getIntent
736 * @see #onNewIntent
737 */
738 public void setIntent(Intent newIntent) {
739 mIntent = newIntent;
740 }
741
742 /** Return the application that owns this activity. */
743 public final Application getApplication() {
744 return mApplication;
745 }
746
747 /** Is this activity embedded inside of another activity? */
748 public final boolean isChild() {
749 return mParent != null;
750 }
751
752 /** Return the parent activity if this view is an embedded child. */
753 public final Activity getParent() {
754 return mParent;
755 }
756
757 /** Retrieve the window manager for showing custom windows. */
758 public WindowManager getWindowManager() {
759 return mWindowManager;
760 }
761
762 /**
763 * Retrieve the current {@link android.view.Window} for the activity.
764 * This can be used to directly access parts of the Window API that
765 * are not available through Activity/Screen.
766 *
767 * @return Window The current window, or null if the activity is not
768 * visual.
769 */
770 public Window getWindow() {
771 return mWindow;
772 }
773
774 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700775 * Return the LoaderManager for this fragment, creating it if needed.
776 */
777 public LoaderManager getLoaderManager() {
778 if (mLoaderManager != null) {
779 return mLoaderManager;
780 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700781 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700782 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700783 return mLoaderManager;
784 }
785
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700786 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700787 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700788 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700789 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700790 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700791 if (lm == null) {
792 if (create) {
793 lm = new LoaderManagerImpl(this, started);
794 mAllLoaderManagers.put(index, lm);
795 }
796 } else {
797 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700798 }
799 return lm;
800 }
801
802 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 * Calls {@link android.view.Window#getCurrentFocus} on the
804 * Window of this Activity to return the currently focused view.
805 *
806 * @return View The current View with focus or null.
807 *
808 * @see #getWindow
809 * @see android.view.Window#getCurrentFocus
810 */
811 public View getCurrentFocus() {
812 return mWindow != null ? mWindow.getCurrentFocus() : null;
813 }
814
815 @Override
816 public int getWallpaperDesiredMinimumWidth() {
817 int width = super.getWallpaperDesiredMinimumWidth();
818 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
819 }
820
821 @Override
822 public int getWallpaperDesiredMinimumHeight() {
823 int height = super.getWallpaperDesiredMinimumHeight();
824 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
825 }
826
827 /**
828 * Called when the activity is starting. This is where most initialization
829 * should go: calling {@link #setContentView(int)} to inflate the
830 * activity's UI, using {@link #findViewById} to programmatically interact
831 * with widgets in the UI, calling
832 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
833 * cursors for data being displayed, etc.
834 *
835 * <p>You can call {@link #finish} from within this function, in
836 * which case onDestroy() will be immediately called without any of the rest
837 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
838 * {@link #onPause}, etc) executing.
839 *
840 * <p><em>Derived classes must call through to the super class's
841 * implementation of this method. If they do not, an exception will be
842 * thrown.</em></p>
843 *
844 * @param savedInstanceState If the activity is being re-initialized after
845 * previously being shut down then this Bundle contains the data it most
846 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
847 *
848 * @see #onStart
849 * @see #onSaveInstanceState
850 * @see #onRestoreInstanceState
851 * @see #onPostCreate
852 */
853 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700854 if (mLastNonConfigurationInstances != null) {
855 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
856 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700857 if (savedInstanceState != null) {
858 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
859 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
860 ? mLastNonConfigurationInstances.fragments : null);
861 }
862 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 mCalled = true;
864 }
865
866 /**
867 * The hook for {@link ActivityThread} to restore the state of this activity.
868 *
869 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
870 * {@link #restoreManagedDialogs(android.os.Bundle)}.
871 *
872 * @param savedInstanceState contains the saved state
873 */
874 final void performRestoreInstanceState(Bundle savedInstanceState) {
875 onRestoreInstanceState(savedInstanceState);
876 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878
879 /**
880 * This method is called after {@link #onStart} when the activity is
881 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800882 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 * to restore their state, but it is sometimes convenient to do it here
884 * after all of the initialization has been done or to allow subclasses to
885 * decide whether to use your default implementation. The default
886 * implementation of this method performs a restore of any view state that
887 * had previously been frozen by {@link #onSaveInstanceState}.
888 *
889 * <p>This method is called between {@link #onStart} and
890 * {@link #onPostCreate}.
891 *
892 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
893 *
894 * @see #onCreate
895 * @see #onPostCreate
896 * @see #onResume
897 * @see #onSaveInstanceState
898 */
899 protected void onRestoreInstanceState(Bundle savedInstanceState) {
900 if (mWindow != null) {
901 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
902 if (windowState != null) {
903 mWindow.restoreHierarchyState(windowState);
904 }
905 }
906 }
907
908 /**
909 * Restore the state of any saved managed dialogs.
910 *
911 * @param savedInstanceState The bundle to restore from.
912 */
913 private void restoreManagedDialogs(Bundle savedInstanceState) {
914 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
915 if (b == null) {
916 return;
917 }
918
919 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
920 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800921 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 for (int i = 0; i < numDialogs; i++) {
923 final Integer dialogId = ids[i];
924 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
925 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700926 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
927 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800928 final ManagedDialog md = new ManagedDialog();
929 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
930 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
931 if (md.mDialog != null) {
932 mManagedDialogs.put(dialogId, md);
933 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
934 md.mDialog.onRestoreInstanceState(dialogState);
935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937 }
938 }
939
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800940 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
941 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700942 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800943 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700944 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700945 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700946 return dialog;
947 }
948
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800949 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 return SAVED_DIALOG_KEY_PREFIX + key;
951 }
952
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800953 private static String savedDialogArgsKeyFor(int key) {
954 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956
957 /**
958 * Called when activity start-up is complete (after {@link #onStart}
959 * and {@link #onRestoreInstanceState} have been called). Applications will
960 * generally not implement this method; it is intended for system
961 * classes to do final initialization after application code has run.
962 *
963 * <p><em>Derived classes must call through to the super class's
964 * implementation of this method. If they do not, an exception will be
965 * thrown.</em></p>
966 *
967 * @param savedInstanceState If the activity is being re-initialized after
968 * previously being shut down then this Bundle contains the data it most
969 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
970 * @see #onCreate
971 */
972 protected void onPostCreate(Bundle savedInstanceState) {
973 if (!isChild()) {
974 mTitleReady = true;
975 onTitleChanged(getTitle(), getTitleColor());
976 }
977 mCalled = true;
978 }
979
980 /**
981 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
982 * the activity had been stopped, but is now again being displayed to the
983 * user. It will be followed by {@link #onResume}.
984 *
985 * <p><em>Derived classes must call through to the super class's
986 * implementation of this method. If they do not, an exception will be
987 * thrown.</em></p>
988 *
989 * @see #onCreate
990 * @see #onStop
991 * @see #onResume
992 */
993 protected void onStart() {
994 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700995
996 if (!mLoadersStarted) {
997 mLoadersStarted = true;
998 if (mLoaderManager != null) {
999 mLoaderManager.doStart();
1000 } else if (!mCheckedForLoaderManager) {
1001 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
1002 }
1003 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006
1007 /**
1008 * Called after {@link #onStop} when the current activity is being
1009 * re-displayed to the user (the user has navigated back to it). It will
1010 * be followed by {@link #onStart} and then {@link #onResume}.
1011 *
1012 * <p>For activities that are using raw {@link Cursor} objects (instead of
1013 * creating them through
1014 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1015 * this is usually the place
1016 * where the cursor should be requeried (because you had deactivated it in
1017 * {@link #onStop}.
1018 *
1019 * <p><em>Derived classes must call through to the super class's
1020 * implementation of this method. If they do not, an exception will be
1021 * thrown.</em></p>
1022 *
1023 * @see #onStop
1024 * @see #onStart
1025 * @see #onResume
1026 */
1027 protected void onRestart() {
1028 mCalled = true;
1029 }
1030
1031 /**
1032 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1033 * {@link #onPause}, for your activity to start interacting with the user.
1034 * This is a good place to begin animations, open exclusive-access devices
1035 * (such as the camera), etc.
1036 *
1037 * <p>Keep in mind that onResume is not the best indicator that your activity
1038 * is visible to the user; a system window such as the keyguard may be in
1039 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1040 * activity is visible to the user (for example, to resume a game).
1041 *
1042 * <p><em>Derived classes must call through to the super class's
1043 * implementation of this method. If they do not, an exception will be
1044 * thrown.</em></p>
1045 *
1046 * @see #onRestoreInstanceState
1047 * @see #onRestart
1048 * @see #onPostResume
1049 * @see #onPause
1050 */
1051 protected void onResume() {
1052 mCalled = true;
1053 }
1054
1055 /**
1056 * Called when activity resume is complete (after {@link #onResume} has
1057 * been called). Applications will generally not implement this method;
1058 * it is intended for system classes to do final setup after application
1059 * resume code has run.
1060 *
1061 * <p><em>Derived classes must call through to the super class's
1062 * implementation of this method. If they do not, an exception will be
1063 * thrown.</em></p>
1064 *
1065 * @see #onResume
1066 */
1067 protected void onPostResume() {
1068 final Window win = getWindow();
1069 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001070 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 mCalled = true;
1072 }
1073
1074 /**
1075 * This is called for activities that set launchMode to "singleTop" in
1076 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1077 * flag when calling {@link #startActivity}. In either case, when the
1078 * activity is re-launched while at the top of the activity stack instead
1079 * of a new instance of the activity being started, onNewIntent() will be
1080 * called on the existing instance with the Intent that was used to
1081 * re-launch it.
1082 *
1083 * <p>An activity will always be paused before receiving a new intent, so
1084 * you can count on {@link #onResume} being called after this method.
1085 *
1086 * <p>Note that {@link #getIntent} still returns the original Intent. You
1087 * can use {@link #setIntent} to update it to this new Intent.
1088 *
1089 * @param intent The new intent that was started for the activity.
1090 *
1091 * @see #getIntent
1092 * @see #setIntent
1093 * @see #onResume
1094 */
1095 protected void onNewIntent(Intent intent) {
1096 }
1097
1098 /**
1099 * The hook for {@link ActivityThread} to save the state of this activity.
1100 *
1101 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1102 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1103 *
1104 * @param outState The bundle to save the state to.
1105 */
1106 final void performSaveInstanceState(Bundle outState) {
1107 onSaveInstanceState(outState);
1108 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110
1111 /**
1112 * Called to retrieve per-instance state from an activity before being killed
1113 * so that the state can be restored in {@link #onCreate} or
1114 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1115 * will be passed to both).
1116 *
1117 * <p>This method is called before an activity may be killed so that when it
1118 * comes back some time in the future it can restore its state. For example,
1119 * if activity B is launched in front of activity A, and at some point activity
1120 * A is killed to reclaim resources, activity A will have a chance to save the
1121 * current state of its user interface via this method so that when the user
1122 * returns to activity A, the state of the user interface can be restored
1123 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1124 *
1125 * <p>Do not confuse this method with activity lifecycle callbacks such as
1126 * {@link #onPause}, which is always called when an activity is being placed
1127 * in the background or on its way to destruction, or {@link #onStop} which
1128 * is called before destruction. One example of when {@link #onPause} and
1129 * {@link #onStop} is called and not this method is when a user navigates back
1130 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1131 * on B because that particular instance will never be restored, so the
1132 * system avoids calling it. An example when {@link #onPause} is called and
1133 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1134 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1135 * killed during the lifetime of B since the state of the user interface of
1136 * A will stay intact.
1137 *
1138 * <p>The default implementation takes care of most of the UI per-instance
1139 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1140 * view in the hierarchy that has an id, and by saving the id of the currently
1141 * focused view (all of which is restored by the default implementation of
1142 * {@link #onRestoreInstanceState}). If you override this method to save additional
1143 * information not captured by each individual view, you will likely want to
1144 * call through to the default implementation, otherwise be prepared to save
1145 * all of the state of each view yourself.
1146 *
1147 * <p>If called, this method will occur before {@link #onStop}. There are
1148 * no guarantees about whether it will occur before or after {@link #onPause}.
1149 *
1150 * @param outState Bundle in which to place your saved state.
1151 *
1152 * @see #onCreate
1153 * @see #onRestoreInstanceState
1154 * @see #onPause
1155 */
1156 protected void onSaveInstanceState(Bundle outState) {
1157 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001158 Parcelable p = mFragments.saveAllState();
1159 if (p != null) {
1160 outState.putParcelable(FRAGMENTS_TAG, p);
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163
1164 /**
1165 * Save the state of any managed dialogs.
1166 *
1167 * @param outState place to store the saved state.
1168 */
1169 private void saveManagedDialogs(Bundle outState) {
1170 if (mManagedDialogs == null) {
1171 return;
1172 }
1173
1174 final int numDialogs = mManagedDialogs.size();
1175 if (numDialogs == 0) {
1176 return;
1177 }
1178
1179 Bundle dialogState = new Bundle();
1180
1181 int[] ids = new int[mManagedDialogs.size()];
1182
1183 // save each dialog's bundle, gather the ids
1184 for (int i = 0; i < numDialogs; i++) {
1185 final int key = mManagedDialogs.keyAt(i);
1186 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001187 final ManagedDialog md = mManagedDialogs.valueAt(i);
1188 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1189 if (md.mArgs != null) {
1190 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
1193
1194 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1195 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1196 }
1197
1198
1199 /**
1200 * Called as part of the activity lifecycle when an activity is going into
1201 * the background, but has not (yet) been killed. The counterpart to
1202 * {@link #onResume}.
1203 *
1204 * <p>When activity B is launched in front of activity A, this callback will
1205 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1206 * so be sure to not do anything lengthy here.
1207 *
1208 * <p>This callback is mostly used for saving any persistent state the
1209 * activity is editing, to present a "edit in place" model to the user and
1210 * making sure nothing is lost if there are not enough resources to start
1211 * the new activity without first killing this one. This is also a good
1212 * place to do things like stop animations and other things that consume a
1213 * noticeable mount of CPU in order to make the switch to the next activity
1214 * as fast as possible, or to close resources that are exclusive access
1215 * such as the camera.
1216 *
1217 * <p>In situations where the system needs more memory it may kill paused
1218 * processes to reclaim resources. Because of this, you should be sure
1219 * that all of your state is saved by the time you return from
1220 * this function. In general {@link #onSaveInstanceState} is used to save
1221 * per-instance state in the activity and this method is used to store
1222 * global persistent data (in content providers, files, etc.)
1223 *
1224 * <p>After receiving this call you will usually receive a following call
1225 * to {@link #onStop} (after the next activity has been resumed and
1226 * displayed), however in some cases there will be a direct call back to
1227 * {@link #onResume} without going through the stopped state.
1228 *
1229 * <p><em>Derived classes must call through to the super class's
1230 * implementation of this method. If they do not, an exception will be
1231 * thrown.</em></p>
1232 *
1233 * @see #onResume
1234 * @see #onSaveInstanceState
1235 * @see #onStop
1236 */
1237 protected void onPause() {
1238 mCalled = true;
1239 }
1240
1241 /**
1242 * Called as part of the activity lifecycle when an activity is about to go
1243 * into the background as the result of user choice. For example, when the
1244 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1245 * when an incoming phone call causes the in-call Activity to be automatically
1246 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1247 * the activity being interrupted. In cases when it is invoked, this method
1248 * is called right before the activity's {@link #onPause} callback.
1249 *
1250 * <p>This callback and {@link #onUserInteraction} are intended to help
1251 * activities manage status bar notifications intelligently; specifically,
1252 * for helping activities determine the proper time to cancel a notfication.
1253 *
1254 * @see #onUserInteraction()
1255 */
1256 protected void onUserLeaveHint() {
1257 }
1258
1259 /**
1260 * Generate a new thumbnail for this activity. This method is called before
1261 * pausing the activity, and should draw into <var>outBitmap</var> the
1262 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1263 * can use the given <var>canvas</var>, which is configured to draw into the
1264 * bitmap, for rendering if desired.
1265 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001266 * <p>The default implementation returns fails and does not draw a thumbnail;
1267 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 *
1269 * @param outBitmap The bitmap to contain the thumbnail.
1270 * @param canvas Can be used to render into the bitmap.
1271 *
1272 * @return Return true if you have drawn into the bitmap; otherwise after
1273 * you return it will be filled with a default thumbnail.
1274 *
1275 * @see #onCreateDescription
1276 * @see #onSaveInstanceState
1277 * @see #onPause
1278 */
1279 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001280 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282
1283 /**
1284 * Generate a new description for this activity. This method is called
1285 * before pausing the activity and can, if desired, return some textual
1286 * description of its current state to be displayed to the user.
1287 *
1288 * <p>The default implementation returns null, which will cause you to
1289 * inherit the description from the previous activity. If all activities
1290 * return null, generally the label of the top activity will be used as the
1291 * description.
1292 *
1293 * @return A description of what the user is doing. It should be short and
1294 * sweet (only a few words).
1295 *
1296 * @see #onCreateThumbnail
1297 * @see #onSaveInstanceState
1298 * @see #onPause
1299 */
1300 public CharSequence onCreateDescription() {
1301 return null;
1302 }
1303
1304 /**
1305 * Called when you are no longer visible to the user. You will next
1306 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1307 * depending on later user activity.
1308 *
1309 * <p>Note that this method may never be called, in low memory situations
1310 * where the system does not have enough memory to keep your activity's
1311 * process running after its {@link #onPause} method is called.
1312 *
1313 * <p><em>Derived classes must call through to the super class's
1314 * implementation of this method. If they do not, an exception will be
1315 * thrown.</em></p>
1316 *
1317 * @see #onRestart
1318 * @see #onResume
1319 * @see #onSaveInstanceState
1320 * @see #onDestroy
1321 */
1322 protected void onStop() {
Adam Powell50efbed2011-02-08 16:20:15 -08001323 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 mCalled = true;
1325 }
1326
1327 /**
1328 * Perform any final cleanup before an activity is destroyed. This can
1329 * happen either because the activity is finishing (someone called
1330 * {@link #finish} on it, or because the system is temporarily destroying
1331 * this instance of the activity to save space. You can distinguish
1332 * between these two scenarios with the {@link #isFinishing} method.
1333 *
1334 * <p><em>Note: do not count on this method being called as a place for
1335 * saving data! For example, if an activity is editing data in a content
1336 * provider, those edits should be committed in either {@link #onPause} or
1337 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1338 * free resources like threads that are associated with an activity, so
1339 * that a destroyed activity does not leave such things around while the
1340 * rest of its application is still running. There are situations where
1341 * the system will simply kill the activity's hosting process without
1342 * calling this method (or any others) in it, so it should not be used to
1343 * do things that are intended to remain around after the process goes
1344 * away.
1345 *
1346 * <p><em>Derived classes must call through to the super class's
1347 * implementation of this method. If they do not, an exception will be
1348 * thrown.</em></p>
1349 *
1350 * @see #onPause
1351 * @see #onStop
1352 * @see #finish
1353 * @see #isFinishing
1354 */
1355 protected void onDestroy() {
1356 mCalled = true;
1357
1358 // dismiss any dialogs we are managing.
1359 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 final int numDialogs = mManagedDialogs.size();
1361 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001362 final ManagedDialog md = mManagedDialogs.valueAt(i);
1363 if (md.mDialog.isShowing()) {
1364 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001367 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369
1370 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001371 synchronized (mManagedCursors) {
1372 int numCursors = mManagedCursors.size();
1373 for (int i = 0; i < numCursors; i++) {
1374 ManagedCursor c = mManagedCursors.get(i);
1375 if (c != null) {
1376 c.mCursor.close();
1377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001379 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
Amith Yamasani49860442010-03-17 20:54:10 -07001381
1382 // Close any open search dialog
1383 if (mSearchManager != null) {
1384 mSearchManager.stopSearch();
1385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
1387
1388 /**
1389 * Called by the system when the device configuration changes while your
1390 * activity is running. Note that this will <em>only</em> be called if
1391 * you have selected configurations you would like to handle with the
1392 * {@link android.R.attr#configChanges} attribute in your manifest. If
1393 * any configuration change occurs that is not selected to be reported
1394 * by that attribute, then instead of reporting it the system will stop
1395 * and restart the activity (to have it launched with the new
1396 * configuration).
1397 *
1398 * <p>At the time that this function has been called, your Resources
1399 * object will have been updated to return resource values matching the
1400 * new configuration.
1401 *
1402 * @param newConfig The new device configuration.
1403 */
1404 public void onConfigurationChanged(Configuration newConfig) {
1405 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001406
Dianne Hackborn9d071802010-12-08 14:49:15 -08001407 mFragments.dispatchConfigurationChanged(newConfig);
1408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 if (mWindow != null) {
1410 // Pass the configuration changed event to the window
1411 mWindow.onConfigurationChanged(newConfig);
1412 }
1413 }
1414
1415 /**
1416 * If this activity is being destroyed because it can not handle a
1417 * configuration parameter being changed (and thus its
1418 * {@link #onConfigurationChanged(Configuration)} method is
1419 * <em>not</em> being called), then you can use this method to discover
1420 * the set of changes that have occurred while in the process of being
1421 * destroyed. Note that there is no guarantee that these will be
1422 * accurate (other changes could have happened at any time), so you should
1423 * only use this as an optimization hint.
1424 *
1425 * @return Returns a bit field of the configuration parameters that are
1426 * changing, as defined by the {@link android.content.res.Configuration}
1427 * class.
1428 */
1429 public int getChangingConfigurations() {
1430 return mConfigChangeFlags;
1431 }
1432
1433 /**
1434 * Retrieve the non-configuration instance data that was previously
1435 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1436 * be available from the initial {@link #onCreate} and
1437 * {@link #onStart} calls to the new instance, allowing you to extract
1438 * any useful dynamic state from the previous instance.
1439 *
1440 * <p>Note that the data you retrieve here should <em>only</em> be used
1441 * as an optimization for handling configuration changes. You should always
1442 * be able to handle getting a null pointer back, and an activity must
1443 * still be able to restore itself to its previous state (through the
1444 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1445 * function returns null.
1446 *
1447 * @return Returns the object previously returned by
1448 * {@link #onRetainNonConfigurationInstance()}.
1449 */
1450 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001451 return mLastNonConfigurationInstances != null
1452 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
1454
1455 /**
1456 * Called by the system, as part of destroying an
1457 * activity due to a configuration change, when it is known that a new
1458 * instance will immediately be created for the new configuration. You
1459 * can return any object you like here, including the activity instance
1460 * itself, which can later be retrieved by calling
1461 * {@link #getLastNonConfigurationInstance()} in the new activity
1462 * instance.
1463 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001464 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1465 * or later, consider instead using a {@link Fragment} with
1466 * {@link Fragment#setRetainInstance(boolean)
1467 * Fragment.setRetainInstance(boolean}.</em>
1468 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 * <p>This function is called purely as an optimization, and you must
1470 * not rely on it being called. When it is called, a number of guarantees
1471 * will be made to help optimize configuration switching:
1472 * <ul>
1473 * <li> The function will be called between {@link #onStop} and
1474 * {@link #onDestroy}.
1475 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001476 * created after this one's {@link #onDestroy()} is called. In particular,
1477 * <em>no</em> messages will be dispatched during this time (when the returned
1478 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 * <li> The object you return here will <em>always</em> be available from
1480 * the {@link #getLastNonConfigurationInstance()} method of the following
1481 * activity instance as described there.
1482 * </ul>
1483 *
1484 * <p>These guarantees are designed so that an activity can use this API
1485 * to propagate extensive state from the old to new activity instance, from
1486 * loaded bitmaps, to network connections, to evenly actively running
1487 * threads. Note that you should <em>not</em> propagate any data that
1488 * may change based on the configuration, including any data loaded from
1489 * resources such as strings, layouts, or drawables.
1490 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001491 * <p>The guarantee of no message handling during the switch to the next
1492 * activity simplifies use with active objects. For example if your retained
1493 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1494 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1495 * not be called from the call here until you execute the next instance's
1496 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1497 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1498 * running in a separate thread.)
1499 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 * @return Return any Object holding the desired state to propagate to the
1501 * next activity instance.
1502 */
1503 public Object onRetainNonConfigurationInstance() {
1504 return null;
1505 }
1506
1507 /**
1508 * Retrieve the non-configuration instance data that was previously
1509 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1510 * be available from the initial {@link #onCreate} and
1511 * {@link #onStart} calls to the new instance, allowing you to extract
1512 * any useful dynamic state from the previous instance.
1513 *
1514 * <p>Note that the data you retrieve here should <em>only</em> be used
1515 * as an optimization for handling configuration changes. You should always
1516 * be able to handle getting a null pointer back, and an activity must
1517 * still be able to restore itself to its previous state (through the
1518 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1519 * function returns null.
1520 *
1521 * @return Returns the object previously returned by
1522 * {@link #onRetainNonConfigurationChildInstances()}
1523 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001524 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1525 return mLastNonConfigurationInstances != null
1526 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528
1529 /**
1530 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1531 * it should return either a mapping from child activity id strings to arbitrary objects,
1532 * or null. This method is intended to be used by Activity framework subclasses that control a
1533 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1534 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1535 */
1536 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1537 return null;
1538 }
1539
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001540 NonConfigurationInstances retainNonConfigurationInstances() {
1541 Object activity = onRetainNonConfigurationInstance();
1542 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1543 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001544 boolean retainLoaders = false;
1545 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001546 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001547 // have nothing useful to retain.
1548 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001549 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001550 if (lm.mRetaining) {
1551 retainLoaders = true;
1552 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001553 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001554 mAllLoaderManagers.removeAt(i);
1555 }
1556 }
1557 }
1558 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001559 return null;
1560 }
1561
1562 NonConfigurationInstances nci = new NonConfigurationInstances();
1563 nci.activity = activity;
1564 nci.children = children;
1565 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001566 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001567 return nci;
1568 }
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 public void onLowMemory() {
1571 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001572 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
1575 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001576 * Return the FragmentManager for interacting with fragments associated
1577 * with this activity.
1578 */
1579 public FragmentManager getFragmentManager() {
1580 return mFragments;
1581 }
1582
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001583 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001584 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001585 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001586 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1587 if (lm != null) {
1588 lm.doDestroy();
1589 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001590 mAllLoaderManagers.remove(index);
1591 }
1592 }
1593
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001594 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001595 * Called when a Fragment is being attached to this activity, immediately
1596 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1597 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1598 */
1599 public void onAttachFragment(Fragment fragment) {
1600 }
1601
1602 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 * Wrapper around
1604 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1605 * that gives the resulting {@link Cursor} to call
1606 * {@link #startManagingCursor} so that the activity will manage its
1607 * lifecycle for you.
1608 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001609 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1610 * or later, consider instead using {@link LoaderManager} instead, available
1611 * via {@link #getLoaderManager()}.</em>
1612 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 * @param uri The URI of the content provider to query.
1614 * @param projection List of columns to return.
1615 * @param selection SQL WHERE clause.
1616 * @param sortOrder SQL ORDER BY clause.
1617 *
1618 * @return The Cursor that was returned by query().
1619 *
1620 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1621 * @see #startManagingCursor
1622 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001623 *
1624 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 */
Jason parks6ed50de2010-08-25 10:18:50 -05001626 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001627 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1628 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1630 if (c != null) {
1631 startManagingCursor(c);
1632 }
1633 return c;
1634 }
1635
1636 /**
1637 * Wrapper around
1638 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1639 * that gives the resulting {@link Cursor} to call
1640 * {@link #startManagingCursor} so that the activity will manage its
1641 * lifecycle for you.
1642 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001643 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1644 * or later, consider instead using {@link LoaderManager} instead, available
1645 * via {@link #getLoaderManager()}.</em>
1646 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 * @param uri The URI of the content provider to query.
1648 * @param projection List of columns to return.
1649 * @param selection SQL WHERE clause.
1650 * @param selectionArgs The arguments to selection, if any ?s are pesent
1651 * @param sortOrder SQL ORDER BY clause.
1652 *
1653 * @return The Cursor that was returned by query().
1654 *
1655 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1656 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001657 *
1658 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 */
Jason parks6ed50de2010-08-25 10:18:50 -05001660 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001661 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1662 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1664 if (c != null) {
1665 startManagingCursor(c);
1666 }
1667 return c;
1668 }
1669
1670 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 * This method allows the activity to take care of managing the given
1672 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1673 * That is, when the activity is stopped it will automatically call
1674 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1675 * it will call {@link Cursor#requery} for you. When the activity is
1676 * destroyed, all managed Cursors will be closed automatically.
1677 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001678 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1679 * or later, consider instead using {@link LoaderManager} instead, available
1680 * via {@link #getLoaderManager()}.</em>
1681 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 * @param c The Cursor to be managed.
1683 *
1684 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1685 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001686 *
1687 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 */
Jason parks6ed50de2010-08-25 10:18:50 -05001689 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 public void startManagingCursor(Cursor c) {
1691 synchronized (mManagedCursors) {
1692 mManagedCursors.add(new ManagedCursor(c));
1693 }
1694 }
1695
1696 /**
1697 * Given a Cursor that was previously given to
1698 * {@link #startManagingCursor}, stop the activity's management of that
1699 * cursor.
1700 *
1701 * @param c The Cursor that was being managed.
1702 *
1703 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001704 *
1705 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 */
Jason parks6ed50de2010-08-25 10:18:50 -05001707 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 public void stopManagingCursor(Cursor c) {
1709 synchronized (mManagedCursors) {
1710 final int N = mManagedCursors.size();
1711 for (int i=0; i<N; i++) {
1712 ManagedCursor mc = mManagedCursors.get(i);
1713 if (mc.mCursor == c) {
1714 mManagedCursors.remove(i);
1715 break;
1716 }
1717 }
1718 }
1719 }
1720
1721 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001722 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1723 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001724 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001726 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
1730 /**
1731 * Finds a view that was identified by the id attribute from the XML that
1732 * was processed in {@link #onCreate}.
1733 *
1734 * @return The view if found or null otherwise.
1735 */
1736 public View findViewById(int id) {
1737 return getWindow().findViewById(id);
1738 }
Adam Powell33b97432010-04-20 10:01:14 -07001739
1740 /**
1741 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001742 *
Adam Powell33b97432010-04-20 10:01:14 -07001743 * @return The Activity's ActionBar, or null if it does not have one.
1744 */
1745 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001746 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001747 return mActionBar;
1748 }
1749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 /**
Adam Powell33b97432010-04-20 10:01:14 -07001751 * Creates a new ActionBar, locates the inflated ActionBarView,
1752 * initializes the ActionBar with the view, and sets mActionBar.
1753 */
1754 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001755 Window window = getWindow();
Adam Powell9b4c8042010-08-10 15:36:44 -07001756 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001757 return;
1758 }
1759
Adam Powell661c9082010-07-02 10:09:44 -07001760 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001761 }
1762
1763 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 * Set the activity content from a layout resource. The resource will be
1765 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08001766 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a62011-01-20 10:59:28 -08001768 *
1769 * @see #setContentView(android.view.View)
1770 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 */
1772 public void setContentView(int layoutResID) {
1773 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001774 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 }
1776
1777 /**
1778 * Set the activity content to an explicit view. This view is placed
1779 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001780 * view hierarchy. When calling this method, the layout parameters of the
1781 * specified view are ignored. Both the width and the height of the view are
1782 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1783 * your own layout parameters, invoke
1784 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1785 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 *
1787 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08001788 *
1789 * @see #setContentView(int)
1790 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 */
1792 public void setContentView(View view) {
1793 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001794 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 }
1796
1797 /**
1798 * Set the activity content to an explicit view. This view is placed
1799 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001800 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 *
1802 * @param view The desired content to display.
1803 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08001804 *
1805 * @see #setContentView(android.view.View)
1806 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 */
1808 public void setContentView(View view, ViewGroup.LayoutParams params) {
1809 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001810 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812
1813 /**
1814 * Add an additional content view to the activity. Added after any existing
1815 * ones in the activity -- existing views are NOT removed.
1816 *
1817 * @param view The desired content to display.
1818 * @param params Layout parameters for the view.
1819 */
1820 public void addContentView(View view, ViewGroup.LayoutParams params) {
1821 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001822 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824
1825 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001826 * Sets whether this activity is finished when touched outside its window's
1827 * bounds.
1828 */
1829 public void setFinishOnTouchOutside(boolean finish) {
1830 mWindow.setCloseOnTouchOutside(finish);
1831 }
1832
1833 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1835 * keys.
1836 *
1837 * @see #setDefaultKeyMode
1838 */
1839 static public final int DEFAULT_KEYS_DISABLE = 0;
1840 /**
1841 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1842 * key handling.
1843 *
1844 * @see #setDefaultKeyMode
1845 */
1846 static public final int DEFAULT_KEYS_DIALER = 1;
1847 /**
1848 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1849 * default key handling.
1850 *
1851 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1852 *
1853 * @see #setDefaultKeyMode
1854 */
1855 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1856 /**
1857 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1858 * will start an application-defined search. (If the application or activity does not
1859 * actually define a search, the the keys will be ignored.)
1860 *
1861 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1862 *
1863 * @see #setDefaultKeyMode
1864 */
1865 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1866
1867 /**
1868 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1869 * will start a global search (typically web search, but some platforms may define alternate
1870 * methods for global search)
1871 *
1872 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1873 *
1874 * @see #setDefaultKeyMode
1875 */
1876 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1877
1878 /**
1879 * Select the default key handling for this activity. This controls what
1880 * will happen to key events that are not otherwise handled. The default
1881 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1882 * floor. Other modes allow you to launch the dialer
1883 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1884 * menu without requiring the menu key be held down
1885 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1886 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1887 *
1888 * <p>Note that the mode selected here does not impact the default
1889 * handling of system keys, such as the "back" and "menu" keys, and your
1890 * activity and its views always get a first chance to receive and handle
1891 * all application keys.
1892 *
1893 * @param mode The desired default key mode constant.
1894 *
1895 * @see #DEFAULT_KEYS_DISABLE
1896 * @see #DEFAULT_KEYS_DIALER
1897 * @see #DEFAULT_KEYS_SHORTCUT
1898 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1899 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1900 * @see #onKeyDown
1901 */
1902 public final void setDefaultKeyMode(int mode) {
1903 mDefaultKeyMode = mode;
1904
1905 // Some modes use a SpannableStringBuilder to track & dispatch input events
1906 // This list must remain in sync with the switch in onKeyDown()
1907 switch (mode) {
1908 case DEFAULT_KEYS_DISABLE:
1909 case DEFAULT_KEYS_SHORTCUT:
1910 mDefaultKeySsb = null; // not used in these modes
1911 break;
1912 case DEFAULT_KEYS_DIALER:
1913 case DEFAULT_KEYS_SEARCH_LOCAL:
1914 case DEFAULT_KEYS_SEARCH_GLOBAL:
1915 mDefaultKeySsb = new SpannableStringBuilder();
1916 Selection.setSelection(mDefaultKeySsb,0);
1917 break;
1918 default:
1919 throw new IllegalArgumentException();
1920 }
1921 }
1922
1923 /**
1924 * Called when a key was pressed down and not handled by any of the views
1925 * inside of the activity. So, for example, key presses while the cursor
1926 * is inside a TextView will not trigger the event (unless it is a navigation
1927 * to another object) because TextView handles its own key presses.
1928 *
1929 * <p>If the focused view didn't want this event, this method is called.
1930 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001931 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1932 * by calling {@link #onBackPressed()}, though the behavior varies based
1933 * on the application compatibility mode: for
1934 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1935 * it will set up the dispatch to call {@link #onKeyUp} where the action
1936 * will be performed; for earlier applications, it will perform the
1937 * action immediately in on-down, as those versions of the platform
1938 * behaved.
1939 *
1940 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001941 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 *
1943 * @return Return <code>true</code> to prevent this event from being propagated
1944 * further, or <code>false</code> to indicate that you have not handled
1945 * this event and it should continue to be propagated.
1946 * @see #onKeyUp
1947 * @see android.view.KeyEvent
1948 */
1949 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001950 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001951 if (getApplicationInfo().targetSdkVersion
1952 >= Build.VERSION_CODES.ECLAIR) {
1953 event.startTracking();
1954 } else {
1955 onBackPressed();
1956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 return true;
1958 }
1959
1960 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1961 return false;
1962 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001963 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1964 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1965 return true;
1966 }
1967 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 } else {
1969 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1970 boolean clearSpannable = false;
1971 boolean handled;
1972 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1973 clearSpannable = true;
1974 handled = false;
1975 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001976 handled = TextKeyListener.getInstance().onKeyDown(
1977 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if (handled && mDefaultKeySsb.length() > 0) {
1979 // something useable has been typed - dispatch it now.
1980
1981 final String str = mDefaultKeySsb.toString();
1982 clearSpannable = true;
1983
1984 switch (mDefaultKeyMode) {
1985 case DEFAULT_KEYS_DIALER:
1986 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1987 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1988 startActivity(intent);
1989 break;
1990 case DEFAULT_KEYS_SEARCH_LOCAL:
1991 startSearch(str, false, null, false);
1992 break;
1993 case DEFAULT_KEYS_SEARCH_GLOBAL:
1994 startSearch(str, false, null, true);
1995 break;
1996 }
1997 }
1998 }
1999 if (clearSpannable) {
2000 mDefaultKeySsb.clear();
2001 mDefaultKeySsb.clearSpans();
2002 Selection.setSelection(mDefaultKeySsb,0);
2003 }
2004 return handled;
2005 }
2006 }
2007
2008 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002009 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2010 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2011 * the event).
2012 */
2013 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2014 return false;
2015 }
2016
2017 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 * Called when a key was released and not handled by any of the views
2019 * inside of the activity. So, for example, key presses while the cursor
2020 * is inside a TextView will not trigger the event (unless it is a navigation
2021 * to another object) because TextView handles its own key presses.
2022 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002023 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2024 * and go back.
2025 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 * @return Return <code>true</code> to prevent this event from being propagated
2027 * further, or <code>false</code> to indicate that you have not handled
2028 * this event and it should continue to be propagated.
2029 * @see #onKeyDown
2030 * @see KeyEvent
2031 */
2032 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002033 if (getApplicationInfo().targetSdkVersion
2034 >= Build.VERSION_CODES.ECLAIR) {
2035 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2036 && !event.isCanceled()) {
2037 onBackPressed();
2038 return true;
2039 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 return false;
2042 }
2043
2044 /**
2045 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2046 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2047 * the event).
2048 */
2049 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2050 return false;
2051 }
2052
2053 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002054 * Called when the activity has detected the user's press of the back
2055 * key. The default implementation simply finishes the current activity,
2056 * but you can override this to do whatever you want.
2057 */
2058 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002059 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002060 finish();
2061 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002062 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002063
2064 /**
2065 * Called when a key shortcut event is not handled by any of the views in the Activity.
2066 * Override this method to implement global key shortcuts for the Activity.
2067 * Key shortcuts can also be implemented by setting the
2068 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2069 *
2070 * @param keyCode The value in event.getKeyCode().
2071 * @param event Description of the key event.
2072 * @return True if the key shortcut was handled.
2073 */
2074 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2075 return false;
2076 }
2077
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002078 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 * Called when a touch screen event was not handled by any of the views
2080 * under it. This is most useful to process touch events that happen
2081 * outside of your window bounds, where there is no view to receive it.
2082 *
2083 * @param event The touch screen event being processed.
2084 *
2085 * @return Return true if you have consumed the event, false if you haven't.
2086 * The default implementation always returns false.
2087 */
2088 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002089 if (mWindow.shouldCloseOnTouch(this, event)) {
2090 finish();
2091 return true;
2092 }
2093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 return false;
2095 }
2096
2097 /**
2098 * Called when the trackball was moved and not handled by any of the
2099 * views inside of the activity. So, for example, if the trackball moves
2100 * while focus is on a button, you will receive a call here because
2101 * buttons do not normally do anything with trackball events. The call
2102 * here happens <em>before</em> trackball movements are converted to
2103 * DPAD key events, which then get sent back to the view hierarchy, and
2104 * will be processed at the point for things like focus navigation.
2105 *
2106 * @param event The trackball event being processed.
2107 *
2108 * @return Return true if you have consumed the event, false if you haven't.
2109 * The default implementation always returns false.
2110 */
2111 public boolean onTrackballEvent(MotionEvent event) {
2112 return false;
2113 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002114
2115 /**
2116 * Called when a generic motion event was not handled by any of the
2117 * views inside of the activity.
2118 * <p>
2119 * Generic motion events are dispatched to the focused view to describe
2120 * the motions of input devices such as joysticks. The
2121 * {@link MotionEvent#getSource() source} of the motion event specifies
2122 * the class of input that was received. Implementations of this method
2123 * must examine the bits in the source before processing the event.
2124 * The following code example shows how this is done.
2125 * </p>
2126 * <code>
2127 * public boolean onGenericMotionEvent(MotionEvent event) {
2128 * if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
2129 * float x = event.getX();
2130 * float y = event.getY();
2131 * // process the joystick motion
2132 * return true;
2133 * }
2134 * return super.onGenericMotionEvent(event);
2135 * }
2136 * </code>
2137 *
2138 * @param event The generic motion event being processed.
2139 *
2140 * @return Return true if you have consumed the event, false if you haven't.
2141 * The default implementation always returns false.
2142 */
2143 public boolean onGenericMotionEvent(MotionEvent event) {
2144 return false;
2145 }
2146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 /**
2148 * Called whenever a key, touch, or trackball event is dispatched to the
2149 * activity. Implement this method if you wish to know that the user has
2150 * interacted with the device in some way while your activity is running.
2151 * This callback and {@link #onUserLeaveHint} are intended to help
2152 * activities manage status bar notifications intelligently; specifically,
2153 * for helping activities determine the proper time to cancel a notfication.
2154 *
2155 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2156 * be accompanied by calls to {@link #onUserInteraction}. This
2157 * ensures that your activity will be told of relevant user activity such
2158 * as pulling down the notification pane and touching an item there.
2159 *
2160 * <p>Note that this callback will be invoked for the touch down action
2161 * that begins a touch gesture, but may not be invoked for the touch-moved
2162 * and touch-up actions that follow.
2163 *
2164 * @see #onUserLeaveHint()
2165 */
2166 public void onUserInteraction() {
2167 }
2168
2169 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2170 // Update window manager if: we have a view, that view is
2171 // attached to its parent (which will be a RootView), and
2172 // this activity is not embedded.
2173 if (mParent == null) {
2174 View decor = mDecor;
2175 if (decor != null && decor.getParent() != null) {
2176 getWindowManager().updateViewLayout(decor, params);
2177 }
2178 }
2179 }
2180
2181 public void onContentChanged() {
2182 }
2183
2184 /**
2185 * Called when the current {@link Window} of the activity gains or loses
2186 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002187 * to the user. The default implementation clears the key tracking
2188 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002190 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 * is managed independently of activity lifecycles. As such, while focus
2192 * changes will generally have some relation to lifecycle changes (an
2193 * activity that is stopped will not generally get window focus), you
2194 * should not rely on any particular order between the callbacks here and
2195 * those in the other lifecycle methods such as {@link #onResume}.
2196 *
2197 * <p>As a general rule, however, a resumed activity will have window
2198 * focus... unless it has displayed other dialogs or popups that take
2199 * input focus, in which case the activity itself will not have focus
2200 * when the other windows have it. Likewise, the system may display
2201 * system-level windows (such as the status bar notification panel or
2202 * a system alert) which will temporarily take window input focus without
2203 * pausing the foreground activity.
2204 *
2205 * @param hasFocus Whether the window of this activity has focus.
2206 *
2207 * @see #hasWindowFocus()
2208 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002209 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 */
2211 public void onWindowFocusChanged(boolean hasFocus) {
2212 }
2213
2214 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002215 * Called when the main window associated with the activity has been
2216 * attached to the window manager.
2217 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2218 * for more information.
2219 * @see View#onAttachedToWindow
2220 */
2221 public void onAttachedToWindow() {
2222 }
2223
2224 /**
2225 * Called when the main window associated with the activity has been
2226 * detached from the window manager.
2227 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2228 * for more information.
2229 * @see View#onDetachedFromWindow
2230 */
2231 public void onDetachedFromWindow() {
2232 }
2233
2234 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 * Returns true if this activity's <em>main</em> window currently has window focus.
2236 * Note that this is not the same as the view itself having focus.
2237 *
2238 * @return True if this activity's main window currently has window focus.
2239 *
2240 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2241 */
2242 public boolean hasWindowFocus() {
2243 Window w = getWindow();
2244 if (w != null) {
2245 View d = w.getDecorView();
2246 if (d != null) {
2247 return d.hasWindowFocus();
2248 }
2249 }
2250 return false;
2251 }
2252
2253 /**
2254 * Called to process key events. You can override this to intercept all
2255 * key events before they are dispatched to the window. Be sure to call
2256 * this implementation for key events that should be handled normally.
2257 *
2258 * @param event The key event.
2259 *
2260 * @return boolean Return true if this event was consumed.
2261 */
2262 public boolean dispatchKeyEvent(KeyEvent event) {
2263 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002264 Window win = getWindow();
2265 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 return true;
2267 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002268 View decor = mDecor;
2269 if (decor == null) decor = win.getDecorView();
2270 return event.dispatch(this, decor != null
2271 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 }
2273
2274 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002275 * Called to process a key shortcut event.
2276 * You can override this to intercept all key shortcut events before they are
2277 * dispatched to the window. Be sure to call this implementation for key shortcut
2278 * events that should be handled normally.
2279 *
2280 * @param event The key shortcut event.
2281 * @return True if this event was consumed.
2282 */
2283 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2284 onUserInteraction();
2285 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2286 return true;
2287 }
2288 return onKeyShortcut(event.getKeyCode(), event);
2289 }
2290
2291 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 * Called to process touch screen events. You can override this to
2293 * intercept all touch screen events before they are dispatched to the
2294 * window. Be sure to call this implementation for touch screen events
2295 * that should be handled normally.
2296 *
2297 * @param ev The touch screen event.
2298 *
2299 * @return boolean Return true if this event was consumed.
2300 */
2301 public boolean dispatchTouchEvent(MotionEvent ev) {
2302 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2303 onUserInteraction();
2304 }
2305 if (getWindow().superDispatchTouchEvent(ev)) {
2306 return true;
2307 }
2308 return onTouchEvent(ev);
2309 }
2310
2311 /**
2312 * Called to process trackball events. You can override this to
2313 * intercept all trackball events before they are dispatched to the
2314 * window. Be sure to call this implementation for trackball events
2315 * that should be handled normally.
2316 *
2317 * @param ev The trackball event.
2318 *
2319 * @return boolean Return true if this event was consumed.
2320 */
2321 public boolean dispatchTrackballEvent(MotionEvent ev) {
2322 onUserInteraction();
2323 if (getWindow().superDispatchTrackballEvent(ev)) {
2324 return true;
2325 }
2326 return onTrackballEvent(ev);
2327 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002328
Jeff Browncb1404e2011-01-15 18:14:15 -08002329 /**
2330 * Called to process generic motion events. You can override this to
2331 * intercept all generic motion events before they are dispatched to the
2332 * window. Be sure to call this implementation for generic motion events
2333 * that should be handled normally.
2334 *
2335 * @param ev The generic motion event.
2336 *
2337 * @return boolean Return true if this event was consumed.
2338 */
2339 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2340 onUserInteraction();
2341 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2342 return true;
2343 }
2344 return onGenericMotionEvent(ev);
2345 }
2346
svetoslavganov75986cf2009-05-14 22:28:01 -07002347 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2348 event.setClassName(getClass().getName());
2349 event.setPackageName(getPackageName());
2350
2351 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002352 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2353 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002354 event.setFullScreen(isFullScreen);
2355
2356 CharSequence title = getTitle();
2357 if (!TextUtils.isEmpty(title)) {
2358 event.getText().add(title);
2359 }
2360
2361 return true;
2362 }
2363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 /**
2365 * Default implementation of
2366 * {@link android.view.Window.Callback#onCreatePanelView}
2367 * for activities. This
2368 * simply returns null so that all panel sub-windows will have the default
2369 * menu behavior.
2370 */
2371 public View onCreatePanelView(int featureId) {
2372 return null;
2373 }
2374
2375 /**
2376 * Default implementation of
2377 * {@link android.view.Window.Callback#onCreatePanelMenu}
2378 * for activities. This calls through to the new
2379 * {@link #onCreateOptionsMenu} method for the
2380 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2381 * so that subclasses of Activity don't need to deal with feature codes.
2382 */
2383 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2384 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002385 boolean show = onCreateOptionsMenu(menu);
2386 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2387 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
2389 return false;
2390 }
2391
2392 /**
2393 * Default implementation of
2394 * {@link android.view.Window.Callback#onPreparePanel}
2395 * for activities. This
2396 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2397 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2398 * panel, so that subclasses of
2399 * Activity don't need to deal with feature codes.
2400 */
2401 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2402 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2403 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002404 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 return goforit && menu.hasVisibleItems();
2406 }
2407 return true;
2408 }
2409
2410 /**
2411 * {@inheritDoc}
2412 *
2413 * @return The default implementation returns true.
2414 */
2415 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002416 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell049dd3d2010-12-02 13:43:59 -08002417 if (mActionBar != null) {
2418 mActionBar.dispatchMenuVisibilityChanged(true);
2419 } else {
2420 Log.e(TAG, "Tried to open action bar menu with no action bar");
2421 }
Adam Powell8515ee82010-11-30 14:09:55 -08002422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 return true;
2424 }
2425
2426 /**
2427 * Default implementation of
2428 * {@link android.view.Window.Callback#onMenuItemSelected}
2429 * for activities. This calls through to the new
2430 * {@link #onOptionsItemSelected} method for the
2431 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2432 * panel, so that subclasses of
2433 * Activity don't need to deal with feature codes.
2434 */
2435 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2436 switch (featureId) {
2437 case Window.FEATURE_OPTIONS_PANEL:
2438 // Put event logging here so it gets called even if subclass
2439 // doesn't call through to superclass's implmeentation of each
2440 // of these methods below
2441 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002442 if (onOptionsItemSelected(item)) {
2443 return true;
2444 }
2445 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446
2447 case Window.FEATURE_CONTEXT_MENU:
2448 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002449 if (onContextItemSelected(item)) {
2450 return true;
2451 }
2452 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 default:
2455 return false;
2456 }
2457 }
2458
2459 /**
2460 * Default implementation of
2461 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2462 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2463 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2464 * so that subclasses of Activity don't need to deal with feature codes.
2465 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2466 * {@link #onContextMenuClosed(Menu)} will be called.
2467 */
2468 public void onPanelClosed(int featureId, Menu menu) {
2469 switch (featureId) {
2470 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002471 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 onOptionsMenuClosed(menu);
2473 break;
2474
2475 case Window.FEATURE_CONTEXT_MENU:
2476 onContextMenuClosed(menu);
2477 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002478
2479 case Window.FEATURE_ACTION_BAR:
2480 mActionBar.dispatchMenuVisibilityChanged(false);
2481 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483 }
2484
2485 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002486 * Declare that the options menu has changed, so should be recreated.
2487 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2488 * time it needs to be displayed.
2489 */
2490 public void invalidateOptionsMenu() {
2491 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2492 }
2493
2494 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 * Initialize the contents of the Activity's standard options menu. You
2496 * should place your menu items in to <var>menu</var>.
2497 *
2498 * <p>This is only called once, the first time the options menu is
2499 * displayed. To update the menu every time it is displayed, see
2500 * {@link #onPrepareOptionsMenu}.
2501 *
2502 * <p>The default implementation populates the menu with standard system
2503 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2504 * they will be correctly ordered with application-defined menu items.
2505 * Deriving classes should always call through to the base implementation.
2506 *
2507 * <p>You can safely hold on to <var>menu</var> (and any items created
2508 * from it), making modifications to it as desired, until the next
2509 * time onCreateOptionsMenu() is called.
2510 *
2511 * <p>When you add items to the menu, you can implement the Activity's
2512 * {@link #onOptionsItemSelected} method to handle them there.
2513 *
2514 * @param menu The options menu in which you place your items.
2515 *
2516 * @return You must return true for the menu to be displayed;
2517 * if you return false it will not be shown.
2518 *
2519 * @see #onPrepareOptionsMenu
2520 * @see #onOptionsItemSelected
2521 */
2522 public boolean onCreateOptionsMenu(Menu menu) {
2523 if (mParent != null) {
2524 return mParent.onCreateOptionsMenu(menu);
2525 }
2526 return true;
2527 }
2528
2529 /**
2530 * Prepare the Screen's standard options menu to be displayed. This is
2531 * called right before the menu is shown, every time it is shown. You can
2532 * use this method to efficiently enable/disable items or otherwise
2533 * dynamically modify the contents.
2534 *
2535 * <p>The default implementation updates the system menu items based on the
2536 * activity's state. Deriving classes should always call through to the
2537 * base class implementation.
2538 *
2539 * @param menu The options menu as last shown or first initialized by
2540 * onCreateOptionsMenu().
2541 *
2542 * @return You must return true for the menu to be displayed;
2543 * if you return false it will not be shown.
2544 *
2545 * @see #onCreateOptionsMenu
2546 */
2547 public boolean onPrepareOptionsMenu(Menu menu) {
2548 if (mParent != null) {
2549 return mParent.onPrepareOptionsMenu(menu);
2550 }
2551 return true;
2552 }
2553
2554 /**
2555 * This hook is called whenever an item in your options menu is selected.
2556 * The default implementation simply returns false to have the normal
2557 * processing happen (calling the item's Runnable or sending a message to
2558 * its Handler as appropriate). You can use this method for any items
2559 * for which you would like to do processing without those other
2560 * facilities.
2561 *
2562 * <p>Derived classes should call through to the base class for it to
2563 * perform the default menu handling.
2564 *
2565 * @param item The menu item that was selected.
2566 *
2567 * @return boolean Return false to allow normal menu processing to
2568 * proceed, true to consume it here.
2569 *
2570 * @see #onCreateOptionsMenu
2571 */
2572 public boolean onOptionsItemSelected(MenuItem item) {
2573 if (mParent != null) {
2574 return mParent.onOptionsItemSelected(item);
2575 }
2576 return false;
2577 }
2578
2579 /**
2580 * This hook is called whenever the options menu is being closed (either by the user canceling
2581 * the menu with the back/menu button, or when an item is selected).
2582 *
2583 * @param menu The options menu as last shown or first initialized by
2584 * onCreateOptionsMenu().
2585 */
2586 public void onOptionsMenuClosed(Menu menu) {
2587 if (mParent != null) {
2588 mParent.onOptionsMenuClosed(menu);
2589 }
2590 }
2591
2592 /**
2593 * Programmatically opens the options menu. If the options menu is already
2594 * open, this method does nothing.
2595 */
2596 public void openOptionsMenu() {
2597 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2598 }
2599
2600 /**
2601 * Progammatically closes the options menu. If the options menu is already
2602 * closed, this method does nothing.
2603 */
2604 public void closeOptionsMenu() {
2605 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2606 }
2607
2608 /**
2609 * Called when a context menu for the {@code view} is about to be shown.
2610 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2611 * time the context menu is about to be shown and should be populated for
2612 * the view (or item inside the view for {@link AdapterView} subclasses,
2613 * this can be found in the {@code menuInfo})).
2614 * <p>
2615 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2616 * item has been selected.
2617 * <p>
2618 * It is not safe to hold onto the context menu after this method returns.
2619 * {@inheritDoc}
2620 */
2621 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2622 }
2623
2624 /**
2625 * Registers a context menu to be shown for the given view (multiple views
2626 * can show the context menu). This method will set the
2627 * {@link OnCreateContextMenuListener} on the view to this activity, so
2628 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2629 * called when it is time to show the context menu.
2630 *
2631 * @see #unregisterForContextMenu(View)
2632 * @param view The view that should show a context menu.
2633 */
2634 public void registerForContextMenu(View view) {
2635 view.setOnCreateContextMenuListener(this);
2636 }
2637
2638 /**
2639 * Prevents a context menu to be shown for the given view. This method will remove the
2640 * {@link OnCreateContextMenuListener} on the view.
2641 *
2642 * @see #registerForContextMenu(View)
2643 * @param view The view that should stop showing a context menu.
2644 */
2645 public void unregisterForContextMenu(View view) {
2646 view.setOnCreateContextMenuListener(null);
2647 }
2648
2649 /**
2650 * Programmatically opens the context menu for a particular {@code view}.
2651 * The {@code view} should have been added via
2652 * {@link #registerForContextMenu(View)}.
2653 *
2654 * @param view The view to show the context menu for.
2655 */
2656 public void openContextMenu(View view) {
2657 view.showContextMenu();
2658 }
2659
2660 /**
2661 * Programmatically closes the most recently opened context menu, if showing.
2662 */
2663 public void closeContextMenu() {
2664 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2665 }
2666
2667 /**
2668 * This hook is called whenever an item in a context menu is selected. The
2669 * default implementation simply returns false to have the normal processing
2670 * happen (calling the item's Runnable or sending a message to its Handler
2671 * as appropriate). You can use this method for any items for which you
2672 * would like to do processing without those other facilities.
2673 * <p>
2674 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2675 * View that added this menu item.
2676 * <p>
2677 * Derived classes should call through to the base class for it to perform
2678 * the default menu handling.
2679 *
2680 * @param item The context menu item that was selected.
2681 * @return boolean Return false to allow normal context menu processing to
2682 * proceed, true to consume it here.
2683 */
2684 public boolean onContextItemSelected(MenuItem item) {
2685 if (mParent != null) {
2686 return mParent.onContextItemSelected(item);
2687 }
2688 return false;
2689 }
2690
2691 /**
2692 * This hook is called whenever the context menu is being closed (either by
2693 * the user canceling the menu with the back/menu button, or when an item is
2694 * selected).
2695 *
2696 * @param menu The context menu that is being closed.
2697 */
2698 public void onContextMenuClosed(Menu menu) {
2699 if (mParent != null) {
2700 mParent.onContextMenuClosed(menu);
2701 }
2702 }
2703
2704 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002705 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002707 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 protected Dialog onCreateDialog(int id) {
2709 return null;
2710 }
2711
2712 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002713 * Callback for creating dialogs that are managed (saved and restored) for you
2714 * by the activity. The default implementation calls through to
2715 * {@link #onCreateDialog(int)} for compatibility.
2716 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002717 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2718 * or later, consider instead using a {@link DialogFragment} instead.</em>
2719 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002720 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2721 * this method the first time, and hang onto it thereafter. Any dialog
2722 * that is created by this method will automatically be saved and restored
2723 * for you, including whether it is showing.
2724 *
2725 * <p>If you would like the activity to manage saving and restoring dialogs
2726 * for you, you should override this method and handle any ids that are
2727 * passed to {@link #showDialog}.
2728 *
2729 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2730 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2731 *
2732 * @param id The id of the dialog.
2733 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2734 * @return The dialog. If you return null, the dialog will not be created.
2735 *
2736 * @see #onPrepareDialog(int, Dialog, Bundle)
2737 * @see #showDialog(int, Bundle)
2738 * @see #dismissDialog(int)
2739 * @see #removeDialog(int)
2740 */
2741 protected Dialog onCreateDialog(int id, Bundle args) {
2742 return onCreateDialog(id);
2743 }
2744
2745 /**
2746 * @deprecated Old no-arguments version of
2747 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2748 */
2749 @Deprecated
2750 protected void onPrepareDialog(int id, Dialog dialog) {
2751 dialog.setOwnerActivity(this);
2752 }
2753
2754 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002756 * shown. The default implementation calls through to
2757 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2758 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 * <p>
2760 * Override this if you need to update a managed dialog based on the state
2761 * of the application each time it is shown. For example, a time picker
2762 * dialog might want to be updated with the current time. You should call
2763 * through to the superclass's implementation. The default implementation
2764 * will set this Activity as the owner activity on the Dialog.
2765 *
2766 * @param id The id of the managed dialog.
2767 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002768 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2769 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 * @see #showDialog(int)
2771 * @see #dismissDialog(int)
2772 * @see #removeDialog(int)
2773 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002774 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2775 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
2777
2778 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002779 * Simple version of {@link #showDialog(int, Bundle)} that does not
2780 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2781 * with null arguments.
2782 */
2783 public final void showDialog(int id) {
2784 showDialog(id, null);
2785 }
2786
2787 /**
2788 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 * will be made with the same id the first time this is called for a given
2790 * id. From thereafter, the dialog will be automatically saved and restored.
2791 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002792 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2793 * or later, consider instead using a {@link DialogFragment} instead.</em>
2794 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002795 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 * be made to provide an opportunity to do any timely preparation.
2797 *
2798 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002799 * @param args Arguments to pass through to the dialog. These will be saved
2800 * and restored for you. Note that if the dialog is already created,
2801 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2802 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002803 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002804 * @return Returns true if the Dialog was created; false is returned if
2805 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2806 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002807 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002808 * @see #onCreateDialog(int, Bundle)
2809 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 * @see #dismissDialog(int)
2811 * @see #removeDialog(int)
2812 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002813 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002815 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002817 ManagedDialog md = mManagedDialogs.get(id);
2818 if (md == null) {
2819 md = new ManagedDialog();
2820 md.mDialog = createDialog(id, null, args);
2821 if (md.mDialog == null) {
2822 return false;
2823 }
2824 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002827 md.mArgs = args;
2828 onPrepareDialog(id, md.mDialog, args);
2829 md.mDialog.show();
2830 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 }
2832
2833 /**
2834 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2835 *
2836 * @param id The id of the managed dialog.
2837 *
2838 * @throws IllegalArgumentException if the id was not previously shown via
2839 * {@link #showDialog(int)}.
2840 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002841 * @see #onCreateDialog(int, Bundle)
2842 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 * @see #showDialog(int)
2844 * @see #removeDialog(int)
2845 */
2846 public final void dismissDialog(int id) {
2847 if (mManagedDialogs == null) {
2848 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002850
2851 final ManagedDialog md = mManagedDialogs.get(id);
2852 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 throw missingDialog(id);
2854 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002855 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 }
2857
2858 /**
2859 * Creates an exception to throw if a user passed in a dialog id that is
2860 * unexpected.
2861 */
2862 private IllegalArgumentException missingDialog(int id) {
2863 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2864 + "shown via Activity#showDialog");
2865 }
2866
2867 /**
2868 * Removes any internal references to a dialog managed by this Activity.
2869 * If the dialog is showing, it will dismiss it as part of the clean up.
2870 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002871 * <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 -08002872 * want to avoid the overhead of saving and restoring it in the future.
2873 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002874 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2875 * will not throw an exception if you try to remove an ID that does not
2876 * currently have an associated dialog.</p>
2877 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 * @param id The id of the managed dialog.
2879 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002880 * @see #onCreateDialog(int, Bundle)
2881 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 * @see #showDialog(int)
2883 * @see #dismissDialog(int)
2884 */
2885 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002886 if (mManagedDialogs != null) {
2887 final ManagedDialog md = mManagedDialogs.get(id);
2888 if (md != null) {
2889 md.mDialog.dismiss();
2890 mManagedDialogs.remove(id);
2891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894
2895 /**
2896 * This hook is called when the user signals the desire to start a search.
2897 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002898 * <p>You can use this function as a simple way to launch the search UI, in response to a
2899 * menu item, search button, or other widgets within your activity. Unless overidden,
2900 * calling this function is the same as calling
2901 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2902 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 *
2904 * <p>You can override this function to force global search, e.g. in response to a dedicated
2905 * search key, or to block search entirely (by simply returning false).
2906 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002907 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2908 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 *
2910 * @see android.app.SearchManager
2911 */
2912 public boolean onSearchRequested() {
2913 startSearch(null, false, null, false);
2914 return true;
2915 }
2916
2917 /**
2918 * This hook is called to launch the search UI.
2919 *
2920 * <p>It is typically called from onSearchRequested(), either directly from
2921 * Activity.onSearchRequested() or from an overridden version in any given
2922 * Activity. If your goal is simply to activate search, it is preferred to call
2923 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2924 * is to inject specific data such as context data, it is preferred to <i>override</i>
2925 * onSearchRequested(), so that any callers to it will benefit from the override.
2926 *
2927 * @param initialQuery Any non-null non-empty string will be inserted as
2928 * pre-entered text in the search query box.
2929 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2930 * any further typing will replace it. This is useful for cases where an entire pre-formed
2931 * query is being inserted. If false, the selection point will be placed at the end of the
2932 * inserted query. This is useful when the inserted query is text that the user entered,
2933 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2934 * if initialQuery is a non-empty string.</i>
2935 * @param appSearchData An application can insert application-specific
2936 * context here, in order to improve quality or specificity of its own
2937 * searches. This data will be returned with SEARCH intent(s). Null if
2938 * no extra data is required.
2939 * @param globalSearch If false, this will only launch the search that has been specifically
2940 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002941 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2943 *
2944 * @see android.app.SearchManager
2945 * @see #onSearchRequested
2946 */
2947 public void startSearch(String initialQuery, boolean selectInitialQuery,
2948 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002949 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002950 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 appSearchData, globalSearch);
2952 }
2953
2954 /**
krosaend2d60142009-08-17 08:56:48 -07002955 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2956 * the search dialog. Made available for testing purposes.
2957 *
2958 * @param query The query to trigger. If empty, the request will be ignored.
2959 * @param appSearchData An application can insert application-specific
2960 * context here, in order to improve quality or specificity of its own
2961 * searches. This data will be returned with SEARCH intent(s). Null if
2962 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002963 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002964 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002965 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002966 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002967 }
2968
2969 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 * Request that key events come to this activity. Use this if your
2971 * activity has no views with focus, but the activity still wants
2972 * a chance to process key events.
2973 *
2974 * @see android.view.Window#takeKeyEvents
2975 */
2976 public void takeKeyEvents(boolean get) {
2977 getWindow().takeKeyEvents(get);
2978 }
2979
2980 /**
2981 * Enable extended window features. This is a convenience for calling
2982 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2983 *
2984 * @param featureId The desired feature as defined in
2985 * {@link android.view.Window}.
2986 * @return Returns true if the requested feature is supported and now
2987 * enabled.
2988 *
2989 * @see android.view.Window#requestFeature
2990 */
2991 public final boolean requestWindowFeature(int featureId) {
2992 return getWindow().requestFeature(featureId);
2993 }
2994
2995 /**
2996 * Convenience for calling
2997 * {@link android.view.Window#setFeatureDrawableResource}.
2998 */
2999 public final void setFeatureDrawableResource(int featureId, int resId) {
3000 getWindow().setFeatureDrawableResource(featureId, resId);
3001 }
3002
3003 /**
3004 * Convenience for calling
3005 * {@link android.view.Window#setFeatureDrawableUri}.
3006 */
3007 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3008 getWindow().setFeatureDrawableUri(featureId, uri);
3009 }
3010
3011 /**
3012 * Convenience for calling
3013 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3014 */
3015 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3016 getWindow().setFeatureDrawable(featureId, drawable);
3017 }
3018
3019 /**
3020 * Convenience for calling
3021 * {@link android.view.Window#setFeatureDrawableAlpha}.
3022 */
3023 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3024 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3025 }
3026
3027 /**
3028 * Convenience for calling
3029 * {@link android.view.Window#getLayoutInflater}.
3030 */
3031 public LayoutInflater getLayoutInflater() {
3032 return getWindow().getLayoutInflater();
3033 }
3034
3035 /**
3036 * Returns a {@link MenuInflater} with this context.
3037 */
3038 public MenuInflater getMenuInflater() {
3039 return new MenuInflater(this);
3040 }
3041
3042 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003043 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3044 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 if (mParent == null) {
3046 super.onApplyThemeResource(theme, resid, first);
3047 } else {
3048 try {
3049 theme.setTo(mParent.getTheme());
3050 } catch (Exception e) {
3051 // Empty
3052 }
3053 theme.applyStyle(resid, false);
3054 }
3055 }
3056
3057 /**
3058 * Launch an activity for which you would like a result when it finished.
3059 * When this activity exits, your
3060 * onActivityResult() method will be called with the given requestCode.
3061 * Using a negative requestCode is the same as calling
3062 * {@link #startActivity} (the activity is not launched as a sub-activity).
3063 *
3064 * <p>Note that this method should only be used with Intent protocols
3065 * that are defined to return a result. In other protocols (such as
3066 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3067 * not get the result when you expect. For example, if the activity you
3068 * are launching uses the singleTask launch mode, it will not run in your
3069 * task and thus you will immediately receive a cancel result.
3070 *
3071 * <p>As a special case, if you call startActivityForResult() with a requestCode
3072 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3073 * activity, then your window will not be displayed until a result is
3074 * returned back from the started activity. This is to avoid visible
3075 * flickering when redirecting to another activity.
3076 *
3077 * <p>This method throws {@link android.content.ActivityNotFoundException}
3078 * if there was no Activity found to run the given Intent.
3079 *
3080 * @param intent The intent to start.
3081 * @param requestCode If >= 0, this code will be returned in
3082 * onActivityResult() when the activity exits.
3083 *
3084 * @throws android.content.ActivityNotFoundException
3085 *
3086 * @see #startActivity
3087 */
3088 public void startActivityForResult(Intent intent, int requestCode) {
3089 if (mParent == null) {
3090 Instrumentation.ActivityResult ar =
3091 mInstrumentation.execStartActivity(
3092 this, mMainThread.getApplicationThread(), mToken, this,
3093 intent, requestCode);
3094 if (ar != null) {
3095 mMainThread.sendActivityResult(
3096 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3097 ar.getResultData());
3098 }
3099 if (requestCode >= 0) {
3100 // If this start is requesting a result, we can avoid making
3101 // the activity visible until the result is received. Setting
3102 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3103 // activity hidden during this time, to avoid flickering.
3104 // This can only be done when a result is requested because
3105 // that guarantees we will get information back when the
3106 // activity is finished, no matter what happens to it.
3107 mStartedActivity = true;
3108 }
3109 } else {
3110 mParent.startActivityFromChild(this, intent, requestCode);
3111 }
3112 }
3113
3114 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003115 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003116 * to use a IntentSender to describe the activity to be started. If
3117 * the IntentSender is for an activity, that activity will be started
3118 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3119 * here; otherwise, its associated action will be executed (such as
3120 * sending a broadcast) as if you had called
3121 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003122 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003123 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003124 * @param requestCode If >= 0, this code will be returned in
3125 * onActivityResult() when the activity exits.
3126 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003127 * intent parameter to {@link IntentSender#sendIntent}.
3128 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003129 * would like to change.
3130 * @param flagsValues Desired values for any bits set in
3131 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003132 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003133 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003134 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3135 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3136 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003137 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003138 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003139 flagsMask, flagsValues, this);
3140 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003141 mParent.startIntentSenderFromChild(this, intent, requestCode,
3142 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003143 }
3144 }
3145
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003146 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003147 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003148 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003149 try {
3150 String resolvedType = null;
3151 if (fillInIntent != null) {
3152 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3153 }
3154 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003155 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003156 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3157 requestCode, flagsMask, flagsValues);
3158 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003159 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003160 }
3161 Instrumentation.checkStartActivityResult(result, null);
3162 } catch (RemoteException e) {
3163 }
3164 if (requestCode >= 0) {
3165 // If this start is requesting a result, we can avoid making
3166 // the activity visible until the result is received. Setting
3167 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3168 // activity hidden during this time, to avoid flickering.
3169 // This can only be done when a result is requested because
3170 // that guarantees we will get information back when the
3171 // activity is finished, no matter what happens to it.
3172 mStartedActivity = true;
3173 }
3174 }
3175
3176 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 * Launch a new activity. You will not receive any information about when
3178 * the activity exits. This implementation overrides the base version,
3179 * providing information about
3180 * the activity performing the launch. Because of this additional
3181 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3182 * required; if not specified, the new activity will be added to the
3183 * task of the caller.
3184 *
3185 * <p>This method throws {@link android.content.ActivityNotFoundException}
3186 * if there was no Activity found to run the given Intent.
3187 *
3188 * @param intent The intent to start.
3189 *
3190 * @throws android.content.ActivityNotFoundException
3191 *
3192 * @see #startActivityForResult
3193 */
3194 @Override
3195 public void startActivity(Intent intent) {
3196 startActivityForResult(intent, -1);
3197 }
3198
3199 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003200 * Launch a new activity. You will not receive any information about when
3201 * the activity exits. This implementation overrides the base version,
3202 * providing information about
3203 * the activity performing the launch. Because of this additional
3204 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3205 * required; if not specified, the new activity will be added to the
3206 * task of the caller.
3207 *
3208 * <p>This method throws {@link android.content.ActivityNotFoundException}
3209 * if there was no Activity found to run the given Intent.
3210 *
3211 * @param intents The intents to start.
3212 *
3213 * @throws android.content.ActivityNotFoundException
3214 *
3215 * @see #startActivityForResult
3216 */
3217 @Override
3218 public void startActivities(Intent[] intents) {
3219 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3220 mToken, this, intents);
3221 }
3222
3223 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003224 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003225 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003226 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003227 * for more information.
3228 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003229 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003230 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003231 * intent parameter to {@link IntentSender#sendIntent}.
3232 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003233 * would like to change.
3234 * @param flagsValues Desired values for any bits set in
3235 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003236 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003237 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003238 public void startIntentSender(IntentSender intent,
3239 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3240 throws IntentSender.SendIntentException {
3241 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3242 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003243 }
3244
3245 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 * A special variation to launch an activity only if a new activity
3247 * instance is needed to handle the given Intent. In other words, this is
3248 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3249 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3250 * singleTask or singleTop
3251 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3252 * and the activity
3253 * that handles <var>intent</var> is the same as your currently running
3254 * activity, then a new instance is not needed. In this case, instead of
3255 * the normal behavior of calling {@link #onNewIntent} this function will
3256 * return and you can handle the Intent yourself.
3257 *
3258 * <p>This function can only be called from a top-level activity; if it is
3259 * called from a child activity, a runtime exception will be thrown.
3260 *
3261 * @param intent The intent to start.
3262 * @param requestCode If >= 0, this code will be returned in
3263 * onActivityResult() when the activity exits, as described in
3264 * {@link #startActivityForResult}.
3265 *
3266 * @return If a new activity was launched then true is returned; otherwise
3267 * false is returned and you must handle the Intent yourself.
3268 *
3269 * @see #startActivity
3270 * @see #startActivityForResult
3271 */
3272 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3273 if (mParent == null) {
3274 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3275 try {
3276 result = ActivityManagerNative.getDefault()
3277 .startActivity(mMainThread.getApplicationThread(),
3278 intent, intent.resolveTypeIfNeeded(
3279 getContentResolver()),
3280 null, 0,
3281 mToken, mEmbeddedID, requestCode, true, false);
3282 } catch (RemoteException e) {
3283 // Empty
3284 }
3285
3286 Instrumentation.checkStartActivityResult(result, intent);
3287
3288 if (requestCode >= 0) {
3289 // If this start is requesting a result, we can avoid making
3290 // the activity visible until the result is received. Setting
3291 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3292 // activity hidden during this time, to avoid flickering.
3293 // This can only be done when a result is requested because
3294 // that guarantees we will get information back when the
3295 // activity is finished, no matter what happens to it.
3296 mStartedActivity = true;
3297 }
3298 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3299 }
3300
3301 throw new UnsupportedOperationException(
3302 "startActivityIfNeeded can only be called from a top-level activity");
3303 }
3304
3305 /**
3306 * Special version of starting an activity, for use when you are replacing
3307 * other activity components. You can use this to hand the Intent off
3308 * to the next Activity that can handle it. You typically call this in
3309 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3310 *
3311 * @param intent The intent to dispatch to the next activity. For
3312 * correct behavior, this must be the same as the Intent that started
3313 * your own activity; the only changes you can make are to the extras
3314 * inside of it.
3315 *
3316 * @return Returns a boolean indicating whether there was another Activity
3317 * to start: true if there was a next activity to start, false if there
3318 * wasn't. In general, if true is returned you will then want to call
3319 * finish() on yourself.
3320 */
3321 public boolean startNextMatchingActivity(Intent intent) {
3322 if (mParent == null) {
3323 try {
3324 return ActivityManagerNative.getDefault()
3325 .startNextMatchingActivity(mToken, intent);
3326 } catch (RemoteException e) {
3327 // Empty
3328 }
3329 return false;
3330 }
3331
3332 throw new UnsupportedOperationException(
3333 "startNextMatchingActivity can only be called from a top-level activity");
3334 }
3335
3336 /**
3337 * This is called when a child activity of this one calls its
3338 * {@link #startActivity} or {@link #startActivityForResult} method.
3339 *
3340 * <p>This method throws {@link android.content.ActivityNotFoundException}
3341 * if there was no Activity found to run the given Intent.
3342 *
3343 * @param child The activity making the call.
3344 * @param intent The intent to start.
3345 * @param requestCode Reply request code. < 0 if reply is not requested.
3346 *
3347 * @throws android.content.ActivityNotFoundException
3348 *
3349 * @see #startActivity
3350 * @see #startActivityForResult
3351 */
3352 public void startActivityFromChild(Activity child, Intent intent,
3353 int requestCode) {
3354 Instrumentation.ActivityResult ar =
3355 mInstrumentation.execStartActivity(
3356 this, mMainThread.getApplicationThread(), mToken, child,
3357 intent, requestCode);
3358 if (ar != null) {
3359 mMainThread.sendActivityResult(
3360 mToken, child.mEmbeddedID, requestCode,
3361 ar.getResultCode(), ar.getResultData());
3362 }
3363 }
3364
3365 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003366 * This is called when a Fragment in this activity calls its
3367 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3368 * method.
3369 *
3370 * <p>This method throws {@link android.content.ActivityNotFoundException}
3371 * if there was no Activity found to run the given Intent.
3372 *
3373 * @param fragment The fragment making the call.
3374 * @param intent The intent to start.
3375 * @param requestCode Reply request code. < 0 if reply is not requested.
3376 *
3377 * @throws android.content.ActivityNotFoundException
3378 *
3379 * @see Fragment#startActivity
3380 * @see Fragment#startActivityForResult
3381 */
3382 public void startActivityFromFragment(Fragment fragment, Intent intent,
3383 int requestCode) {
3384 Instrumentation.ActivityResult ar =
3385 mInstrumentation.execStartActivity(
3386 this, mMainThread.getApplicationThread(), mToken, fragment,
3387 intent, requestCode);
3388 if (ar != null) {
3389 mMainThread.sendActivityResult(
3390 mToken, fragment.mWho, requestCode,
3391 ar.getResultCode(), ar.getResultData());
3392 }
3393 }
3394
3395 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003396 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003397 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003398 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003399 * for more information.
3400 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003401 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3402 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3403 int extraFlags)
3404 throws IntentSender.SendIntentException {
3405 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003406 flagsMask, flagsValues, child);
3407 }
3408
3409 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003410 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3411 * or {@link #finish} to specify an explicit transition animation to
3412 * perform next.
3413 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003414 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003415 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003416 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003417 */
3418 public void overridePendingTransition(int enterAnim, int exitAnim) {
3419 try {
3420 ActivityManagerNative.getDefault().overridePendingTransition(
3421 mToken, getPackageName(), enterAnim, exitAnim);
3422 } catch (RemoteException e) {
3423 }
3424 }
3425
3426 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 * Call this to set the result that your activity will return to its
3428 * caller.
3429 *
3430 * @param resultCode The result code to propagate back to the originating
3431 * activity, often RESULT_CANCELED or RESULT_OK
3432 *
3433 * @see #RESULT_CANCELED
3434 * @see #RESULT_OK
3435 * @see #RESULT_FIRST_USER
3436 * @see #setResult(int, Intent)
3437 */
3438 public final void setResult(int resultCode) {
3439 synchronized (this) {
3440 mResultCode = resultCode;
3441 mResultData = null;
3442 }
3443 }
3444
3445 /**
3446 * Call this to set the result that your activity will return to its
3447 * caller.
3448 *
3449 * @param resultCode The result code to propagate back to the originating
3450 * activity, often RESULT_CANCELED or RESULT_OK
3451 * @param data The data to propagate back to the originating activity.
3452 *
3453 * @see #RESULT_CANCELED
3454 * @see #RESULT_OK
3455 * @see #RESULT_FIRST_USER
3456 * @see #setResult(int)
3457 */
3458 public final void setResult(int resultCode, Intent data) {
3459 synchronized (this) {
3460 mResultCode = resultCode;
3461 mResultData = data;
3462 }
3463 }
3464
3465 /**
3466 * Return the name of the package that invoked this activity. This is who
3467 * the data in {@link #setResult setResult()} will be sent to. You can
3468 * use this information to validate that the recipient is allowed to
3469 * receive the data.
3470 *
3471 * <p>Note: if the calling activity is not expecting a result (that is it
3472 * did not use the {@link #startActivityForResult}
3473 * form that includes a request code), then the calling package will be
3474 * null.
3475 *
3476 * @return The package of the activity that will receive your
3477 * reply, or null if none.
3478 */
3479 public String getCallingPackage() {
3480 try {
3481 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3482 } catch (RemoteException e) {
3483 return null;
3484 }
3485 }
3486
3487 /**
3488 * Return the name of the activity that invoked this activity. This is
3489 * who the data in {@link #setResult setResult()} will be sent to. You
3490 * can use this information to validate that the recipient is allowed to
3491 * receive the data.
3492 *
3493 * <p>Note: if the calling activity is not expecting a result (that is it
3494 * did not use the {@link #startActivityForResult}
3495 * form that includes a request code), then the calling package will be
3496 * null.
3497 *
3498 * @return String The full name of the activity that will receive your
3499 * reply, or null if none.
3500 */
3501 public ComponentName getCallingActivity() {
3502 try {
3503 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3504 } catch (RemoteException e) {
3505 return null;
3506 }
3507 }
3508
3509 /**
3510 * Control whether this activity's main window is visible. This is intended
3511 * only for the special case of an activity that is not going to show a
3512 * UI itself, but can't just finish prior to onResume() because it needs
3513 * to wait for a service binding or such. Setting this to false allows
3514 * you to prevent your UI from being shown during that time.
3515 *
3516 * <p>The default value for this is taken from the
3517 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3518 */
3519 public void setVisible(boolean visible) {
3520 if (mVisibleFromClient != visible) {
3521 mVisibleFromClient = visible;
3522 if (mVisibleFromServer) {
3523 if (visible) makeVisible();
3524 else mDecor.setVisibility(View.INVISIBLE);
3525 }
3526 }
3527 }
3528
3529 void makeVisible() {
3530 if (!mWindowAdded) {
3531 ViewManager wm = getWindowManager();
3532 wm.addView(mDecor, getWindow().getAttributes());
3533 mWindowAdded = true;
3534 }
3535 mDecor.setVisibility(View.VISIBLE);
3536 }
3537
3538 /**
3539 * Check to see whether this activity is in the process of finishing,
3540 * either because you called {@link #finish} on it or someone else
3541 * has requested that it finished. This is often used in
3542 * {@link #onPause} to determine whether the activity is simply pausing or
3543 * completely finishing.
3544 *
3545 * @return If the activity is finishing, returns true; else returns false.
3546 *
3547 * @see #finish
3548 */
3549 public boolean isFinishing() {
3550 return mFinished;
3551 }
3552
3553 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003554 * Check to see whether this activity is in the process of being destroyed in order to be
3555 * recreated with a new configuration. This is often used in
3556 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3557 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3558 *
3559 * @return If the activity is being torn down in order to be recreated with a new configuration,
3560 * returns true; else returns false.
3561 */
3562 public boolean isChangingConfigurations() {
3563 return mChangingConfigurations;
3564 }
3565
3566 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003567 * Cause this Activity to be recreated with a new instance. This results
3568 * in essentially the same flow as when the Activity is created due to
3569 * a configuration change -- the current instance will go through its
3570 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3571 */
3572 public void recreate() {
3573 if (mParent != null) {
3574 throw new IllegalStateException("Can only be called on top-level activity");
3575 }
3576 if (Looper.myLooper() != mMainThread.getLooper()) {
3577 throw new IllegalStateException("Must be called from main thread");
3578 }
3579 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3580 }
3581
3582 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 * Call this when your activity is done and should be closed. The
3584 * ActivityResult is propagated back to whoever launched you via
3585 * onActivityResult().
3586 */
3587 public void finish() {
3588 if (mParent == null) {
3589 int resultCode;
3590 Intent resultData;
3591 synchronized (this) {
3592 resultCode = mResultCode;
3593 resultData = mResultData;
3594 }
3595 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3596 try {
3597 if (ActivityManagerNative.getDefault()
3598 .finishActivity(mToken, resultCode, resultData)) {
3599 mFinished = true;
3600 }
3601 } catch (RemoteException e) {
3602 // Empty
3603 }
3604 } else {
3605 mParent.finishFromChild(this);
3606 }
3607 }
3608
3609 /**
3610 * This is called when a child activity of this one calls its
3611 * {@link #finish} method. The default implementation simply calls
3612 * finish() on this activity (the parent), finishing the entire group.
3613 *
3614 * @param child The activity making the call.
3615 *
3616 * @see #finish
3617 */
3618 public void finishFromChild(Activity child) {
3619 finish();
3620 }
3621
3622 /**
3623 * Force finish another activity that you had previously started with
3624 * {@link #startActivityForResult}.
3625 *
3626 * @param requestCode The request code of the activity that you had
3627 * given to startActivityForResult(). If there are multiple
3628 * activities started with this request code, they
3629 * will all be finished.
3630 */
3631 public void finishActivity(int requestCode) {
3632 if (mParent == null) {
3633 try {
3634 ActivityManagerNative.getDefault()
3635 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3636 } catch (RemoteException e) {
3637 // Empty
3638 }
3639 } else {
3640 mParent.finishActivityFromChild(this, requestCode);
3641 }
3642 }
3643
3644 /**
3645 * This is called when a child activity of this one calls its
3646 * finishActivity().
3647 *
3648 * @param child The activity making the call.
3649 * @param requestCode Request code that had been used to start the
3650 * activity.
3651 */
3652 public void finishActivityFromChild(Activity child, int requestCode) {
3653 try {
3654 ActivityManagerNative.getDefault()
3655 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3656 } catch (RemoteException e) {
3657 // Empty
3658 }
3659 }
3660
3661 /**
3662 * Called when an activity you launched exits, giving you the requestCode
3663 * you started it with, the resultCode it returned, and any additional
3664 * data from it. The <var>resultCode</var> will be
3665 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3666 * didn't return any result, or crashed during its operation.
3667 *
3668 * <p>You will receive this call immediately before onResume() when your
3669 * activity is re-starting.
3670 *
3671 * @param requestCode The integer request code originally supplied to
3672 * startActivityForResult(), allowing you to identify who this
3673 * result came from.
3674 * @param resultCode The integer result code returned by the child activity
3675 * through its setResult().
3676 * @param data An Intent, which can return result data to the caller
3677 * (various data can be attached to Intent "extras").
3678 *
3679 * @see #startActivityForResult
3680 * @see #createPendingResult
3681 * @see #setResult(int)
3682 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003683 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 }
3685
3686 /**
3687 * Create a new PendingIntent object which you can hand to others
3688 * for them to use to send result data back to your
3689 * {@link #onActivityResult} callback. The created object will be either
3690 * one-shot (becoming invalid after a result is sent back) or multiple
3691 * (allowing any number of results to be sent through it).
3692 *
3693 * @param requestCode Private request code for the sender that will be
3694 * associated with the result data when it is returned. The sender can not
3695 * modify this value, allowing you to identify incoming results.
3696 * @param data Default data to supply in the result, which may be modified
3697 * by the sender.
3698 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3699 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3700 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3701 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3702 * or any of the flags as supported by
3703 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3704 * of the intent that can be supplied when the actual send happens.
3705 *
3706 * @return Returns an existing or new PendingIntent matching the given
3707 * parameters. May return null only if
3708 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3709 * supplied.
3710 *
3711 * @see PendingIntent
3712 */
3713 public PendingIntent createPendingResult(int requestCode, Intent data,
3714 int flags) {
3715 String packageName = getPackageName();
3716 try {
3717 IIntentSender target =
3718 ActivityManagerNative.getDefault().getIntentSender(
3719 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3720 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003721 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 return target != null ? new PendingIntent(target) : null;
3723 } catch (RemoteException e) {
3724 // Empty
3725 }
3726 return null;
3727 }
3728
3729 /**
3730 * Change the desired orientation of this activity. If the activity
3731 * is currently in the foreground or otherwise impacting the screen
3732 * orientation, the screen will immediately be changed (possibly causing
3733 * the activity to be restarted). Otherwise, this will be used the next
3734 * time the activity is visible.
3735 *
3736 * @param requestedOrientation An orientation constant as used in
3737 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3738 */
3739 public void setRequestedOrientation(int requestedOrientation) {
3740 if (mParent == null) {
3741 try {
3742 ActivityManagerNative.getDefault().setRequestedOrientation(
3743 mToken, requestedOrientation);
3744 } catch (RemoteException e) {
3745 // Empty
3746 }
3747 } else {
3748 mParent.setRequestedOrientation(requestedOrientation);
3749 }
3750 }
3751
3752 /**
3753 * Return the current requested orientation of the activity. This will
3754 * either be the orientation requested in its component's manifest, or
3755 * the last requested orientation given to
3756 * {@link #setRequestedOrientation(int)}.
3757 *
3758 * @return Returns an orientation constant as used in
3759 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3760 */
3761 public int getRequestedOrientation() {
3762 if (mParent == null) {
3763 try {
3764 return ActivityManagerNative.getDefault()
3765 .getRequestedOrientation(mToken);
3766 } catch (RemoteException e) {
3767 // Empty
3768 }
3769 } else {
3770 return mParent.getRequestedOrientation();
3771 }
3772 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3773 }
3774
3775 /**
3776 * Return the identifier of the task this activity is in. This identifier
3777 * will remain the same for the lifetime of the activity.
3778 *
3779 * @return Task identifier, an opaque integer.
3780 */
3781 public int getTaskId() {
3782 try {
3783 return ActivityManagerNative.getDefault()
3784 .getTaskForActivity(mToken, false);
3785 } catch (RemoteException e) {
3786 return -1;
3787 }
3788 }
3789
3790 /**
3791 * Return whether this activity is the root of a task. The root is the
3792 * first activity in a task.
3793 *
3794 * @return True if this is the root activity, else false.
3795 */
3796 public boolean isTaskRoot() {
3797 try {
3798 return ActivityManagerNative.getDefault()
3799 .getTaskForActivity(mToken, true) >= 0;
3800 } catch (RemoteException e) {
3801 return false;
3802 }
3803 }
3804
3805 /**
3806 * Move the task containing this activity to the back of the activity
3807 * stack. The activity's order within the task is unchanged.
3808 *
3809 * @param nonRoot If false then this only works if the activity is the root
3810 * of a task; if true it will work for any activity in
3811 * a task.
3812 *
3813 * @return If the task was moved (or it was already at the
3814 * back) true is returned, else false.
3815 */
3816 public boolean moveTaskToBack(boolean nonRoot) {
3817 try {
3818 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3819 mToken, nonRoot);
3820 } catch (RemoteException e) {
3821 // Empty
3822 }
3823 return false;
3824 }
3825
3826 /**
3827 * Returns class name for this activity with the package prefix removed.
3828 * This is the default name used to read and write settings.
3829 *
3830 * @return The local class name.
3831 */
3832 public String getLocalClassName() {
3833 final String pkg = getPackageName();
3834 final String cls = mComponent.getClassName();
3835 int packageLen = pkg.length();
3836 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3837 || cls.charAt(packageLen) != '.') {
3838 return cls;
3839 }
3840 return cls.substring(packageLen+1);
3841 }
3842
3843 /**
3844 * Returns complete component name of this activity.
3845 *
3846 * @return Returns the complete component name for this activity
3847 */
3848 public ComponentName getComponentName()
3849 {
3850 return mComponent;
3851 }
3852
3853 /**
3854 * Retrieve a {@link SharedPreferences} object for accessing preferences
3855 * that are private to this activity. This simply calls the underlying
3856 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3857 * class name as the preferences name.
3858 *
3859 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3860 * operation, {@link #MODE_WORLD_READABLE} and
3861 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3862 *
3863 * @return Returns the single SharedPreferences instance that can be used
3864 * to retrieve and modify the preference values.
3865 */
3866 public SharedPreferences getPreferences(int mode) {
3867 return getSharedPreferences(getLocalClassName(), mode);
3868 }
3869
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003870 private void ensureSearchManager() {
3871 if (mSearchManager != null) {
3872 return;
3873 }
3874
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003875 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003876 }
3877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 @Override
3879 public Object getSystemService(String name) {
3880 if (getBaseContext() == null) {
3881 throw new IllegalStateException(
3882 "System services not available to Activities before onCreate()");
3883 }
3884
3885 if (WINDOW_SERVICE.equals(name)) {
3886 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003887 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003888 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003889 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 }
3891 return super.getSystemService(name);
3892 }
3893
3894 /**
3895 * Change the title associated with this activity. If this is a
3896 * top-level activity, the title for its window will change. If it
3897 * is an embedded activity, the parent can do whatever it wants
3898 * with it.
3899 */
3900 public void setTitle(CharSequence title) {
3901 mTitle = title;
3902 onTitleChanged(title, mTitleColor);
3903
3904 if (mParent != null) {
3905 mParent.onChildTitleChanged(this, title);
3906 }
3907 }
3908
3909 /**
3910 * Change the title associated with this activity. If this is a
3911 * top-level activity, the title for its window will change. If it
3912 * is an embedded activity, the parent can do whatever it wants
3913 * with it.
3914 */
3915 public void setTitle(int titleId) {
3916 setTitle(getText(titleId));
3917 }
3918
3919 public void setTitleColor(int textColor) {
3920 mTitleColor = textColor;
3921 onTitleChanged(mTitle, textColor);
3922 }
3923
3924 public final CharSequence getTitle() {
3925 return mTitle;
3926 }
3927
3928 public final int getTitleColor() {
3929 return mTitleColor;
3930 }
3931
3932 protected void onTitleChanged(CharSequence title, int color) {
3933 if (mTitleReady) {
3934 final Window win = getWindow();
3935 if (win != null) {
3936 win.setTitle(title);
3937 if (color != 0) {
3938 win.setTitleColor(color);
3939 }
3940 }
3941 }
3942 }
3943
3944 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3945 }
3946
3947 /**
3948 * Sets the visibility of the progress bar in the title.
3949 * <p>
3950 * In order for the progress bar to be shown, the feature must be requested
3951 * via {@link #requestWindowFeature(int)}.
3952 *
3953 * @param visible Whether to show the progress bars in the title.
3954 */
3955 public final void setProgressBarVisibility(boolean visible) {
3956 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3957 Window.PROGRESS_VISIBILITY_OFF);
3958 }
3959
3960 /**
3961 * Sets the visibility of the indeterminate progress bar in the title.
3962 * <p>
3963 * In order for the progress bar to be shown, the feature must be requested
3964 * via {@link #requestWindowFeature(int)}.
3965 *
3966 * @param visible Whether to show the progress bars in the title.
3967 */
3968 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3969 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3970 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3971 }
3972
3973 /**
3974 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3975 * is always indeterminate).
3976 * <p>
3977 * In order for the progress bar to be shown, the feature must be requested
3978 * via {@link #requestWindowFeature(int)}.
3979 *
3980 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3981 */
3982 public final void setProgressBarIndeterminate(boolean indeterminate) {
3983 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3984 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3985 }
3986
3987 /**
3988 * Sets the progress for the progress bars in the title.
3989 * <p>
3990 * In order for the progress bar to be shown, the feature must be requested
3991 * via {@link #requestWindowFeature(int)}.
3992 *
3993 * @param progress The progress for the progress bar. Valid ranges are from
3994 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3995 * bar will be completely filled and will fade out.
3996 */
3997 public final void setProgress(int progress) {
3998 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3999 }
4000
4001 /**
4002 * Sets the secondary progress for the progress bar in the title. This
4003 * progress is drawn between the primary progress (set via
4004 * {@link #setProgress(int)} and the background. It can be ideal for media
4005 * scenarios such as showing the buffering progress while the default
4006 * progress shows the play progress.
4007 * <p>
4008 * In order for the progress bar to be shown, the feature must be requested
4009 * via {@link #requestWindowFeature(int)}.
4010 *
4011 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
4012 * 0 to 10000 (both inclusive).
4013 */
4014 public final void setSecondaryProgress(int secondaryProgress) {
4015 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4016 secondaryProgress + Window.PROGRESS_SECONDARY_START);
4017 }
4018
4019 /**
4020 * Suggests an audio stream whose volume should be changed by the hardware
4021 * volume controls.
4022 * <p>
4023 * The suggested audio stream will be tied to the window of this Activity.
4024 * If the Activity is switched, the stream set here is no longer the
4025 * suggested stream. The client does not need to save and restore the old
4026 * suggested stream value in onPause and onResume.
4027 *
4028 * @param streamType The type of the audio stream whose volume should be
4029 * changed by the hardware volume controls. It is not guaranteed that
4030 * the hardware volume controls will always change this stream's
4031 * volume (for example, if a call is in progress, its stream's volume
4032 * may be changed instead). To reset back to the default, use
4033 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4034 */
4035 public final void setVolumeControlStream(int streamType) {
4036 getWindow().setVolumeControlStream(streamType);
4037 }
4038
4039 /**
4040 * Gets the suggested audio stream whose volume should be changed by the
4041 * harwdare volume controls.
4042 *
4043 * @return The suggested audio stream type whose volume should be changed by
4044 * the hardware volume controls.
4045 * @see #setVolumeControlStream(int)
4046 */
4047 public final int getVolumeControlStream() {
4048 return getWindow().getVolumeControlStream();
4049 }
4050
4051 /**
4052 * Runs the specified action on the UI thread. If the current thread is the UI
4053 * thread, then the action is executed immediately. If the current thread is
4054 * not the UI thread, the action is posted to the event queue of the UI thread.
4055 *
4056 * @param action the action to run on the UI thread
4057 */
4058 public final void runOnUiThread(Runnable action) {
4059 if (Thread.currentThread() != mUiThread) {
4060 mHandler.post(action);
4061 } else {
4062 action.run();
4063 }
4064 }
4065
4066 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004067 * Standard implementation of
4068 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4069 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004070 * This implementation does nothing and is for
4071 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4072 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4073 *
4074 * @see android.view.LayoutInflater#createView
4075 * @see android.view.Window#getLayoutInflater
4076 */
4077 public View onCreateView(String name, Context context, AttributeSet attrs) {
4078 return null;
4079 }
4080
4081 /**
4082 * Standard implementation of
4083 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4084 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004085 * This implementation handles <fragment> tags to embed fragments inside
4086 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 *
4088 * @see android.view.LayoutInflater#createView
4089 * @see android.view.Window#getLayoutInflater
4090 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004091 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004092 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004093 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004094 }
4095
Dianne Hackborndef15372010-08-15 12:43:52 -07004096 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004097 TypedArray a =
4098 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004099 if (fname == null) {
4100 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4101 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004102 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004103 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4104 a.recycle();
4105
Dianne Hackborn625ac272010-09-17 18:29:22 -07004106 int containerId = parent != null ? parent.getId() : 0;
4107 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004108 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004109 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004110 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004111
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004112 // If we restored from a previous state, we may already have
4113 // instantiated this fragment from the state and should use
4114 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004115 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4116 if (fragment == null && tag != null) {
4117 fragment = mFragments.findFragmentByTag(tag);
4118 }
4119 if (fragment == null && containerId != View.NO_ID) {
4120 fragment = mFragments.findFragmentById(containerId);
4121 }
4122
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004123 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4124 + Integer.toHexString(id) + " fname=" + fname
4125 + " existing=" + fragment);
4126 if (fragment == null) {
4127 fragment = Fragment.instantiate(this, fname);
4128 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004129 fragment.mFragmentId = id != 0 ? id : containerId;
4130 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004131 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004132 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004133 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004134 fragment.mFragmentManager = mFragments;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004135 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4136 mFragments.addFragment(fragment, true);
4137
4138 } else if (fragment.mInLayout) {
4139 // A fragment already exists and it is not one we restored from
4140 // previous state.
4141 throw new IllegalArgumentException(attrs.getPositionDescription()
4142 + ": Duplicate id 0x" + Integer.toHexString(id)
4143 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4144 + " with another fragment for " + fname);
4145 } else {
4146 // This fragment was retained from a previous instance; get it
4147 // going now.
4148 fragment.mInLayout = true;
4149 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004150 // If this fragment is newly instantiated (either right now, or
4151 // from last saved state), then give it the attributes to
4152 // initialize itself.
4153 if (!fragment.mRetaining) {
4154 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4155 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004156 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004157 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004158
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004159 if (fragment.mView == null) {
4160 throw new IllegalStateException("Fragment " + fname
4161 + " did not create a view.");
4162 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004163 if (id != 0) {
4164 fragment.mView.setId(id);
4165 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004166 if (fragment.mView.getTag() == null) {
4167 fragment.mView.setTag(tag);
4168 }
4169 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 }
4171
Daniel Sandler69a48172010-06-23 16:29:36 -04004172 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004173 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004174 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004175 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004176 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004177 * @param fd The raw file descriptor that the dump is being sent to.
4178 * @param writer The PrintWriter to which you should dump your state. This will be
4179 * closed for you after you return.
4180 * @param args additional arguments to the dump request.
4181 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004182 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4183 writer.print(prefix); writer.print("Local Activity ");
4184 writer.print(Integer.toHexString(System.identityHashCode(this)));
4185 writer.println(" State:");
4186 String innerPrefix = prefix + " ";
4187 writer.print(innerPrefix); writer.print("mResumed=");
4188 writer.print(mResumed); writer.print(" mStopped=");
4189 writer.print(mStopped); writer.print(" mFinished=");
4190 writer.println(mFinished);
4191 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4192 writer.println(mLoadersStarted);
4193 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4194 writer.println(mChangingConfigurations);
4195 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4196 writer.println(mCurrentConfig);
4197 if (mLoaderManager != null) {
4198 writer.print(prefix); writer.print("Loader Manager ");
4199 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4200 writer.println(":");
4201 mLoaderManager.dump(prefix + " ", fd, writer, args);
4202 }
4203 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004204 }
4205
4206 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004207 * Bit indicating that this activity is "immersive" and should not be
4208 * interrupted by notifications if possible.
4209 *
4210 * This value is initially set by the manifest property
4211 * <code>android:immersive</code> but may be changed at runtime by
4212 * {@link #setImmersive}.
4213 *
4214 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004215 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004216 */
4217 public boolean isImmersive() {
4218 try {
4219 return ActivityManagerNative.getDefault().isImmersive(mToken);
4220 } catch (RemoteException e) {
4221 return false;
4222 }
4223 }
4224
4225 /**
4226 * Adjust the current immersive mode setting.
4227 *
4228 * Note that changing this value will have no effect on the activity's
4229 * {@link android.content.pm.ActivityInfo} structure; that is, if
4230 * <code>android:immersive</code> is set to <code>true</code>
4231 * in the application's manifest entry for this activity, the {@link
4232 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4233 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4234 * FLAG_IMMERSIVE} bit set.
4235 *
4236 * @see #isImmersive
4237 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004238 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004239 */
4240 public void setImmersive(boolean i) {
4241 try {
4242 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4243 } catch (RemoteException e) {
4244 // pass
4245 }
4246 }
4247
Adam Powell6e346362010-07-23 10:18:23 -07004248 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004249 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004250 *
4251 * @param callback Callback that will manage lifecycle events for this context mode
4252 * @return The ContextMode that was started, or null if it was canceled
4253 *
4254 * @see ActionMode
4255 */
Adam Powell5d279772010-07-27 16:34:07 -07004256 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004257 return mWindow.getDecorView().startActionMode(callback);
4258 }
4259
Adam Powelldebf3be2010-11-15 18:58:48 -08004260 /**
4261 * Give the Activity a chance to control the UI for an action mode requested
4262 * by the system.
4263 *
4264 * <p>Note: If you are looking for a notification callback that an action mode
4265 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4266 *
4267 * @param callback The callback that should control the new action mode
4268 * @return The new action mode, or <code>null</code> if the activity does not want to
4269 * provide special handling for this action mode. (It will be handled by the system.)
4270 */
4271 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004272 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004273 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004274 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004275 }
4276 return null;
4277 }
4278
Adam Powelldebf3be2010-11-15 18:58:48 -08004279 /**
4280 * Notifies the Activity that an action mode has been started.
4281 * Activity subclasses overriding this method should call the superclass implementation.
4282 *
4283 * @param mode The new action mode.
4284 */
4285 public void onActionModeStarted(ActionMode mode) {
4286 }
4287
4288 /**
4289 * Notifies the activity that an action mode has finished.
4290 * Activity subclasses overriding this method should call the superclass implementation.
4291 *
4292 * @param mode The action mode that just finished.
4293 */
4294 public void onActionModeFinished(ActionMode mode) {
4295 }
4296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 // ------------------ Internal API ------------------
4298
4299 final void setParent(Activity parent) {
4300 mParent = parent;
4301 }
4302
4303 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4304 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004305 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004307 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004308 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 }
4310
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004311 final void attach(Context context, ActivityThread aThread,
4312 Instrumentation instr, IBinder token, int ident,
4313 Application application, Intent intent, ActivityInfo info,
4314 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004315 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004316 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 attachBaseContext(context);
4318
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004319 mFragments.attachActivity(this);
4320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 mWindow = PolicyManager.makeNewWindow(this);
4322 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08004323 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4325 mWindow.setSoftInputMode(info.softInputMode);
4326 }
4327 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 mMainThread = aThread;
4330 mInstrumentation = instr;
4331 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004332 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 mApplication = application;
4334 mIntent = intent;
4335 mComponent = intent.getComponent();
4336 mActivityInfo = info;
4337 mTitle = title;
4338 mParent = parent;
4339 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004340 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341
Romain Guy529b60a2010-08-03 18:05:47 -07004342 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4343 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 if (mParent != null) {
4345 mWindow.setContainer(mParent.getWindow());
4346 }
4347 mWindowManager = mWindow.getWindowManager();
4348 mCurrentConfig = config;
4349 }
4350
4351 final IBinder getActivityToken() {
4352 return mParent != null ? mParent.getActivityToken() : mToken;
4353 }
4354
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004355 final void performCreate(Bundle icicle) {
4356 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004357 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4358 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004359 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004360 }
4361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004363 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004365 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 mInstrumentation.callActivityOnStart(this);
4367 if (!mCalled) {
4368 throw new SuperNotCalledException(
4369 "Activity " + mComponent.toShortString() +
4370 " did not call through to super.onStart()");
4371 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004372 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004373 if (mAllLoaderManagers != null) {
4374 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4375 mAllLoaderManagers.valueAt(i).finishRetain();
4376 }
4377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379
4380 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004381 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004382
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004383 synchronized (mManagedCursors) {
4384 final int N = mManagedCursors.size();
4385 for (int i=0; i<N; i++) {
4386 ManagedCursor mc = mManagedCursors.get(i);
4387 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004388 if (!mc.mCursor.requery()) {
4389 throw new IllegalStateException(
4390 "trying to requery an already closed cursor");
4391 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004392 mc.mReleased = false;
4393 mc.mUpdated = false;
4394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 }
4396 }
4397
4398 if (mStopped) {
4399 mStopped = false;
4400 mCalled = false;
4401 mInstrumentation.callActivityOnRestart(this);
4402 if (!mCalled) {
4403 throw new SuperNotCalledException(
4404 "Activity " + mComponent.toShortString() +
4405 " did not call through to super.onRestart()");
4406 }
4407 performStart();
4408 }
4409 }
4410
4411 final void performResume() {
4412 performRestart();
4413
Dianne Hackborn445646c2010-06-25 15:52:59 -07004414 mFragments.execPendingActions();
4415
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004416 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06004419 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 mInstrumentation.callActivityOnResume(this);
4421 if (!mCalled) {
4422 throw new SuperNotCalledException(
4423 "Activity " + mComponent.toShortString() +
4424 " did not call through to super.onResume()");
4425 }
4426
4427 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004429
4430 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004431 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 onPostResume();
4434 if (!mCalled) {
4435 throw new SuperNotCalledException(
4436 "Activity " + mComponent.toShortString() +
4437 " did not call through to super.onPostResume()");
4438 }
4439 }
4440
4441 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004442 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004443 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004445 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004446 if (!mCalled && getApplicationInfo().targetSdkVersion
4447 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4448 throw new SuperNotCalledException(
4449 "Activity " + mComponent.toShortString() +
4450 " did not call through to super.onPause()");
4451 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06004452 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454
4455 final void performUserLeaving() {
4456 onUserInteraction();
4457 onUserLeaveHint();
4458 }
4459
4460 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004461 if (mLoadersStarted) {
4462 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004463 if (mLoaderManager != null) {
4464 if (!mChangingConfigurations) {
4465 mLoaderManager.doStop();
4466 } else {
4467 mLoaderManager.doRetain();
4468 }
4469 }
4470 }
4471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 if (!mStopped) {
4473 if (mWindow != null) {
4474 mWindow.closeAllPanels();
4475 }
4476
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004477 mFragments.dispatchStop();
4478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 mCalled = false;
4480 mInstrumentation.callActivityOnStop(this);
4481 if (!mCalled) {
4482 throw new SuperNotCalledException(
4483 "Activity " + mComponent.toShortString() +
4484 " did not call through to super.onStop()");
4485 }
4486
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004487 synchronized (mManagedCursors) {
4488 final int N = mManagedCursors.size();
4489 for (int i=0; i<N; i++) {
4490 ManagedCursor mc = mManagedCursors.get(i);
4491 if (!mc.mReleased) {
4492 mc.mCursor.deactivate();
4493 mc.mReleased = true;
4494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 }
4496 }
4497
4498 mStopped = true;
4499 }
4500 mResumed = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08004501
4502 // Check for Activity leaks, if enabled.
4503 StrictMode.conditionallyCheckInstanceCounts();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
4505
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004506 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004507 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004508 mFragments.dispatchDestroy();
4509 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004510 if (mLoaderManager != null) {
4511 mLoaderManager.doDestroy();
4512 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004513 }
4514
Jeff Hamilton52d32032011-01-08 15:31:26 -06004515 /**
4516 * @hide
4517 */
4518 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 return mResumed;
4520 }
4521
4522 void dispatchActivityResult(String who, int requestCode,
4523 int resultCode, Intent data) {
4524 if (Config.LOGV) Log.v(
4525 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4526 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004527 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 if (who == null) {
4529 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004530 } else {
4531 Fragment frag = mFragments.findFragmentByWho(who);
4532 if (frag != null) {
4533 frag.onActivityResult(requestCode, resultCode, data);
4534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 }
4536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537}