blob: 3c45080531ea5b5210218ca64b2aaec2dd21d380 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 private boolean mResumed;
659 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();
1070 mCalled = true;
1071 }
1072
1073 /**
1074 * This is called for activities that set launchMode to "singleTop" in
1075 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1076 * flag when calling {@link #startActivity}. In either case, when the
1077 * activity is re-launched while at the top of the activity stack instead
1078 * of a new instance of the activity being started, onNewIntent() will be
1079 * called on the existing instance with the Intent that was used to
1080 * re-launch it.
1081 *
1082 * <p>An activity will always be paused before receiving a new intent, so
1083 * you can count on {@link #onResume} being called after this method.
1084 *
1085 * <p>Note that {@link #getIntent} still returns the original Intent. You
1086 * can use {@link #setIntent} to update it to this new Intent.
1087 *
1088 * @param intent The new intent that was started for the activity.
1089 *
1090 * @see #getIntent
1091 * @see #setIntent
1092 * @see #onResume
1093 */
1094 protected void onNewIntent(Intent intent) {
1095 }
1096
1097 /**
1098 * The hook for {@link ActivityThread} to save the state of this activity.
1099 *
1100 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1101 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1102 *
1103 * @param outState The bundle to save the state to.
1104 */
1105 final void performSaveInstanceState(Bundle outState) {
1106 onSaveInstanceState(outState);
1107 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
1110 /**
1111 * Called to retrieve per-instance state from an activity before being killed
1112 * so that the state can be restored in {@link #onCreate} or
1113 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1114 * will be passed to both).
1115 *
1116 * <p>This method is called before an activity may be killed so that when it
1117 * comes back some time in the future it can restore its state. For example,
1118 * if activity B is launched in front of activity A, and at some point activity
1119 * A is killed to reclaim resources, activity A will have a chance to save the
1120 * current state of its user interface via this method so that when the user
1121 * returns to activity A, the state of the user interface can be restored
1122 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1123 *
1124 * <p>Do not confuse this method with activity lifecycle callbacks such as
1125 * {@link #onPause}, which is always called when an activity is being placed
1126 * in the background or on its way to destruction, or {@link #onStop} which
1127 * is called before destruction. One example of when {@link #onPause} and
1128 * {@link #onStop} is called and not this method is when a user navigates back
1129 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1130 * on B because that particular instance will never be restored, so the
1131 * system avoids calling it. An example when {@link #onPause} is called and
1132 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1133 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1134 * killed during the lifetime of B since the state of the user interface of
1135 * A will stay intact.
1136 *
1137 * <p>The default implementation takes care of most of the UI per-instance
1138 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1139 * view in the hierarchy that has an id, and by saving the id of the currently
1140 * focused view (all of which is restored by the default implementation of
1141 * {@link #onRestoreInstanceState}). If you override this method to save additional
1142 * information not captured by each individual view, you will likely want to
1143 * call through to the default implementation, otherwise be prepared to save
1144 * all of the state of each view yourself.
1145 *
1146 * <p>If called, this method will occur before {@link #onStop}. There are
1147 * no guarantees about whether it will occur before or after {@link #onPause}.
1148 *
1149 * @param outState Bundle in which to place your saved state.
1150 *
1151 * @see #onCreate
1152 * @see #onRestoreInstanceState
1153 * @see #onPause
1154 */
1155 protected void onSaveInstanceState(Bundle outState) {
1156 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001157 Parcelable p = mFragments.saveAllState();
1158 if (p != null) {
1159 outState.putParcelable(FRAGMENTS_TAG, p);
1160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
1162
1163 /**
1164 * Save the state of any managed dialogs.
1165 *
1166 * @param outState place to store the saved state.
1167 */
1168 private void saveManagedDialogs(Bundle outState) {
1169 if (mManagedDialogs == null) {
1170 return;
1171 }
1172
1173 final int numDialogs = mManagedDialogs.size();
1174 if (numDialogs == 0) {
1175 return;
1176 }
1177
1178 Bundle dialogState = new Bundle();
1179
1180 int[] ids = new int[mManagedDialogs.size()];
1181
1182 // save each dialog's bundle, gather the ids
1183 for (int i = 0; i < numDialogs; i++) {
1184 final int key = mManagedDialogs.keyAt(i);
1185 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001186 final ManagedDialog md = mManagedDialogs.valueAt(i);
1187 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1188 if (md.mArgs != null) {
1189 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
1192
1193 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1194 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1195 }
1196
1197
1198 /**
1199 * Called as part of the activity lifecycle when an activity is going into
1200 * the background, but has not (yet) been killed. The counterpart to
1201 * {@link #onResume}.
1202 *
1203 * <p>When activity B is launched in front of activity A, this callback will
1204 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1205 * so be sure to not do anything lengthy here.
1206 *
1207 * <p>This callback is mostly used for saving any persistent state the
1208 * activity is editing, to present a "edit in place" model to the user and
1209 * making sure nothing is lost if there are not enough resources to start
1210 * the new activity without first killing this one. This is also a good
1211 * place to do things like stop animations and other things that consume a
1212 * noticeable mount of CPU in order to make the switch to the next activity
1213 * as fast as possible, or to close resources that are exclusive access
1214 * such as the camera.
1215 *
1216 * <p>In situations where the system needs more memory it may kill paused
1217 * processes to reclaim resources. Because of this, you should be sure
1218 * that all of your state is saved by the time you return from
1219 * this function. In general {@link #onSaveInstanceState} is used to save
1220 * per-instance state in the activity and this method is used to store
1221 * global persistent data (in content providers, files, etc.)
1222 *
1223 * <p>After receiving this call you will usually receive a following call
1224 * to {@link #onStop} (after the next activity has been resumed and
1225 * displayed), however in some cases there will be a direct call back to
1226 * {@link #onResume} without going through the stopped state.
1227 *
1228 * <p><em>Derived classes must call through to the super class's
1229 * implementation of this method. If they do not, an exception will be
1230 * thrown.</em></p>
1231 *
1232 * @see #onResume
1233 * @see #onSaveInstanceState
1234 * @see #onStop
1235 */
1236 protected void onPause() {
1237 mCalled = true;
1238 }
1239
1240 /**
1241 * Called as part of the activity lifecycle when an activity is about to go
1242 * into the background as the result of user choice. For example, when the
1243 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1244 * when an incoming phone call causes the in-call Activity to be automatically
1245 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1246 * the activity being interrupted. In cases when it is invoked, this method
1247 * is called right before the activity's {@link #onPause} callback.
1248 *
1249 * <p>This callback and {@link #onUserInteraction} are intended to help
1250 * activities manage status bar notifications intelligently; specifically,
1251 * for helping activities determine the proper time to cancel a notfication.
1252 *
1253 * @see #onUserInteraction()
1254 */
1255 protected void onUserLeaveHint() {
1256 }
1257
1258 /**
1259 * Generate a new thumbnail for this activity. This method is called before
1260 * pausing the activity, and should draw into <var>outBitmap</var> the
1261 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1262 * can use the given <var>canvas</var>, which is configured to draw into the
1263 * bitmap, for rendering if desired.
1264 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001265 * <p>The default implementation returns fails and does not draw a thumbnail;
1266 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 *
1268 * @param outBitmap The bitmap to contain the thumbnail.
1269 * @param canvas Can be used to render into the bitmap.
1270 *
1271 * @return Return true if you have drawn into the bitmap; otherwise after
1272 * you return it will be filled with a default thumbnail.
1273 *
1274 * @see #onCreateDescription
1275 * @see #onSaveInstanceState
1276 * @see #onPause
1277 */
1278 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001279 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281
1282 /**
1283 * Generate a new description for this activity. This method is called
1284 * before pausing the activity and can, if desired, return some textual
1285 * description of its current state to be displayed to the user.
1286 *
1287 * <p>The default implementation returns null, which will cause you to
1288 * inherit the description from the previous activity. If all activities
1289 * return null, generally the label of the top activity will be used as the
1290 * description.
1291 *
1292 * @return A description of what the user is doing. It should be short and
1293 * sweet (only a few words).
1294 *
1295 * @see #onCreateThumbnail
1296 * @see #onSaveInstanceState
1297 * @see #onPause
1298 */
1299 public CharSequence onCreateDescription() {
1300 return null;
1301 }
1302
1303 /**
1304 * Called when you are no longer visible to the user. You will next
1305 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1306 * depending on later user activity.
1307 *
1308 * <p>Note that this method may never be called, in low memory situations
1309 * where the system does not have enough memory to keep your activity's
1310 * process running after its {@link #onPause} method is called.
1311 *
1312 * <p><em>Derived classes must call through to the super class's
1313 * implementation of this method. If they do not, an exception will be
1314 * thrown.</em></p>
1315 *
1316 * @see #onRestart
1317 * @see #onResume
1318 * @see #onSaveInstanceState
1319 * @see #onDestroy
1320 */
1321 protected void onStop() {
1322 mCalled = true;
1323 }
1324
1325 /**
1326 * Perform any final cleanup before an activity is destroyed. This can
1327 * happen either because the activity is finishing (someone called
1328 * {@link #finish} on it, or because the system is temporarily destroying
1329 * this instance of the activity to save space. You can distinguish
1330 * between these two scenarios with the {@link #isFinishing} method.
1331 *
1332 * <p><em>Note: do not count on this method being called as a place for
1333 * saving data! For example, if an activity is editing data in a content
1334 * provider, those edits should be committed in either {@link #onPause} or
1335 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1336 * free resources like threads that are associated with an activity, so
1337 * that a destroyed activity does not leave such things around while the
1338 * rest of its application is still running. There are situations where
1339 * the system will simply kill the activity's hosting process without
1340 * calling this method (or any others) in it, so it should not be used to
1341 * do things that are intended to remain around after the process goes
1342 * away.
1343 *
1344 * <p><em>Derived classes must call through to the super class's
1345 * implementation of this method. If they do not, an exception will be
1346 * thrown.</em></p>
1347 *
1348 * @see #onPause
1349 * @see #onStop
1350 * @see #finish
1351 * @see #isFinishing
1352 */
1353 protected void onDestroy() {
1354 mCalled = true;
1355
1356 // dismiss any dialogs we are managing.
1357 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 final int numDialogs = mManagedDialogs.size();
1359 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001360 final ManagedDialog md = mManagedDialogs.valueAt(i);
1361 if (md.mDialog.isShowing()) {
1362 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001365 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
1368 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001369 synchronized (mManagedCursors) {
1370 int numCursors = mManagedCursors.size();
1371 for (int i = 0; i < numCursors; i++) {
1372 ManagedCursor c = mManagedCursors.get(i);
1373 if (c != null) {
1374 c.mCursor.close();
1375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001377 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
Amith Yamasani49860442010-03-17 20:54:10 -07001379
1380 // Close any open search dialog
1381 if (mSearchManager != null) {
1382 mSearchManager.stopSearch();
1383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
1386 /**
1387 * Called by the system when the device configuration changes while your
1388 * activity is running. Note that this will <em>only</em> be called if
1389 * you have selected configurations you would like to handle with the
1390 * {@link android.R.attr#configChanges} attribute in your manifest. If
1391 * any configuration change occurs that is not selected to be reported
1392 * by that attribute, then instead of reporting it the system will stop
1393 * and restart the activity (to have it launched with the new
1394 * configuration).
1395 *
1396 * <p>At the time that this function has been called, your Resources
1397 * object will have been updated to return resource values matching the
1398 * new configuration.
1399 *
1400 * @param newConfig The new device configuration.
1401 */
1402 public void onConfigurationChanged(Configuration newConfig) {
1403 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001404
Dianne Hackborn9d071802010-12-08 14:49:15 -08001405 mFragments.dispatchConfigurationChanged(newConfig);
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 if (mWindow != null) {
1408 // Pass the configuration changed event to the window
1409 mWindow.onConfigurationChanged(newConfig);
1410 }
1411 }
1412
1413 /**
1414 * If this activity is being destroyed because it can not handle a
1415 * configuration parameter being changed (and thus its
1416 * {@link #onConfigurationChanged(Configuration)} method is
1417 * <em>not</em> being called), then you can use this method to discover
1418 * the set of changes that have occurred while in the process of being
1419 * destroyed. Note that there is no guarantee that these will be
1420 * accurate (other changes could have happened at any time), so you should
1421 * only use this as an optimization hint.
1422 *
1423 * @return Returns a bit field of the configuration parameters that are
1424 * changing, as defined by the {@link android.content.res.Configuration}
1425 * class.
1426 */
1427 public int getChangingConfigurations() {
1428 return mConfigChangeFlags;
1429 }
1430
1431 /**
1432 * Retrieve the non-configuration instance data that was previously
1433 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1434 * be available from the initial {@link #onCreate} and
1435 * {@link #onStart} calls to the new instance, allowing you to extract
1436 * any useful dynamic state from the previous instance.
1437 *
1438 * <p>Note that the data you retrieve here should <em>only</em> be used
1439 * as an optimization for handling configuration changes. You should always
1440 * be able to handle getting a null pointer back, and an activity must
1441 * still be able to restore itself to its previous state (through the
1442 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1443 * function returns null.
1444 *
1445 * @return Returns the object previously returned by
1446 * {@link #onRetainNonConfigurationInstance()}.
1447 */
1448 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001449 return mLastNonConfigurationInstances != null
1450 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452
1453 /**
1454 * Called by the system, as part of destroying an
1455 * activity due to a configuration change, when it is known that a new
1456 * instance will immediately be created for the new configuration. You
1457 * can return any object you like here, including the activity instance
1458 * itself, which can later be retrieved by calling
1459 * {@link #getLastNonConfigurationInstance()} in the new activity
1460 * instance.
1461 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001462 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1463 * or later, consider instead using a {@link Fragment} with
1464 * {@link Fragment#setRetainInstance(boolean)
1465 * Fragment.setRetainInstance(boolean}.</em>
1466 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 * <p>This function is called purely as an optimization, and you must
1468 * not rely on it being called. When it is called, a number of guarantees
1469 * will be made to help optimize configuration switching:
1470 * <ul>
1471 * <li> The function will be called between {@link #onStop} and
1472 * {@link #onDestroy}.
1473 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001474 * created after this one's {@link #onDestroy()} is called. In particular,
1475 * <em>no</em> messages will be dispatched during this time (when the returned
1476 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * <li> The object you return here will <em>always</em> be available from
1478 * the {@link #getLastNonConfigurationInstance()} method of the following
1479 * activity instance as described there.
1480 * </ul>
1481 *
1482 * <p>These guarantees are designed so that an activity can use this API
1483 * to propagate extensive state from the old to new activity instance, from
1484 * loaded bitmaps, to network connections, to evenly actively running
1485 * threads. Note that you should <em>not</em> propagate any data that
1486 * may change based on the configuration, including any data loaded from
1487 * resources such as strings, layouts, or drawables.
1488 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001489 * <p>The guarantee of no message handling during the switch to the next
1490 * activity simplifies use with active objects. For example if your retained
1491 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1492 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1493 * not be called from the call here until you execute the next instance's
1494 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1495 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1496 * running in a separate thread.)
1497 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 * @return Return any Object holding the desired state to propagate to the
1499 * next activity instance.
1500 */
1501 public Object onRetainNonConfigurationInstance() {
1502 return null;
1503 }
1504
1505 /**
1506 * Retrieve the non-configuration instance data that was previously
1507 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1508 * be available from the initial {@link #onCreate} and
1509 * {@link #onStart} calls to the new instance, allowing you to extract
1510 * any useful dynamic state from the previous instance.
1511 *
1512 * <p>Note that the data you retrieve here should <em>only</em> be used
1513 * as an optimization for handling configuration changes. You should always
1514 * be able to handle getting a null pointer back, and an activity must
1515 * still be able to restore itself to its previous state (through the
1516 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1517 * function returns null.
1518 *
1519 * @return Returns the object previously returned by
1520 * {@link #onRetainNonConfigurationChildInstances()}
1521 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001522 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1523 return mLastNonConfigurationInstances != null
1524 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526
1527 /**
1528 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1529 * it should return either a mapping from child activity id strings to arbitrary objects,
1530 * or null. This method is intended to be used by Activity framework subclasses that control a
1531 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1532 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1533 */
1534 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1535 return null;
1536 }
1537
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001538 NonConfigurationInstances retainNonConfigurationInstances() {
1539 Object activity = onRetainNonConfigurationInstance();
1540 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1541 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001542 boolean retainLoaders = false;
1543 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001544 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001545 // have nothing useful to retain.
1546 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001547 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001548 if (lm.mRetaining) {
1549 retainLoaders = true;
1550 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001551 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001552 mAllLoaderManagers.removeAt(i);
1553 }
1554 }
1555 }
1556 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001557 return null;
1558 }
1559
1560 NonConfigurationInstances nci = new NonConfigurationInstances();
1561 nci.activity = activity;
1562 nci.children = children;
1563 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001564 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001565 return nci;
1566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 public void onLowMemory() {
1569 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001570 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572
1573 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001574 * Return the FragmentManager for interacting with fragments associated
1575 * with this activity.
1576 */
1577 public FragmentManager getFragmentManager() {
1578 return mFragments;
1579 }
1580
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001581 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001582 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001583 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001584 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1585 if (lm != null) {
1586 lm.doDestroy();
1587 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001588 mAllLoaderManagers.remove(index);
1589 }
1590 }
1591
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001592 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001593 * Called when a Fragment is being attached to this activity, immediately
1594 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1595 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1596 */
1597 public void onAttachFragment(Fragment fragment) {
1598 }
1599
1600 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 * Wrapper around
1602 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1603 * that gives the resulting {@link Cursor} to call
1604 * {@link #startManagingCursor} so that the activity will manage its
1605 * lifecycle for you.
1606 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001607 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1608 * or later, consider instead using {@link LoaderManager} instead, available
1609 * via {@link #getLoaderManager()}.</em>
1610 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 * @param uri The URI of the content provider to query.
1612 * @param projection List of columns to return.
1613 * @param selection SQL WHERE clause.
1614 * @param sortOrder SQL ORDER BY clause.
1615 *
1616 * @return The Cursor that was returned by query().
1617 *
1618 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1619 * @see #startManagingCursor
1620 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001621 *
1622 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 */
Jason parks6ed50de2010-08-25 10:18:50 -05001624 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001625 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1626 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1628 if (c != null) {
1629 startManagingCursor(c);
1630 }
1631 return c;
1632 }
1633
1634 /**
1635 * Wrapper around
1636 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1637 * that gives the resulting {@link Cursor} to call
1638 * {@link #startManagingCursor} so that the activity will manage its
1639 * lifecycle for you.
1640 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001641 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1642 * or later, consider instead using {@link LoaderManager} instead, available
1643 * via {@link #getLoaderManager()}.</em>
1644 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 * @param uri The URI of the content provider to query.
1646 * @param projection List of columns to return.
1647 * @param selection SQL WHERE clause.
1648 * @param selectionArgs The arguments to selection, if any ?s are pesent
1649 * @param sortOrder SQL ORDER BY clause.
1650 *
1651 * @return The Cursor that was returned by query().
1652 *
1653 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1654 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001655 *
1656 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 */
Jason parks6ed50de2010-08-25 10:18:50 -05001658 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001659 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1660 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1662 if (c != null) {
1663 startManagingCursor(c);
1664 }
1665 return c;
1666 }
1667
1668 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 * This method allows the activity to take care of managing the given
1670 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1671 * That is, when the activity is stopped it will automatically call
1672 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1673 * it will call {@link Cursor#requery} for you. When the activity is
1674 * destroyed, all managed Cursors will be closed automatically.
1675 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001676 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1677 * or later, consider instead using {@link LoaderManager} instead, available
1678 * via {@link #getLoaderManager()}.</em>
1679 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 * @param c The Cursor to be managed.
1681 *
1682 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1683 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001684 *
1685 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 */
Jason parks6ed50de2010-08-25 10:18:50 -05001687 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 public void startManagingCursor(Cursor c) {
1689 synchronized (mManagedCursors) {
1690 mManagedCursors.add(new ManagedCursor(c));
1691 }
1692 }
1693
1694 /**
1695 * Given a Cursor that was previously given to
1696 * {@link #startManagingCursor}, stop the activity's management of that
1697 * cursor.
1698 *
1699 * @param c The Cursor that was being managed.
1700 *
1701 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001702 *
1703 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 */
Jason parks6ed50de2010-08-25 10:18:50 -05001705 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 public void stopManagingCursor(Cursor c) {
1707 synchronized (mManagedCursors) {
1708 final int N = mManagedCursors.size();
1709 for (int i=0; i<N; i++) {
1710 ManagedCursor mc = mManagedCursors.get(i);
1711 if (mc.mCursor == c) {
1712 mManagedCursors.remove(i);
1713 break;
1714 }
1715 }
1716 }
1717 }
1718
1719 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001720 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1721 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001722 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001724 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727
1728 /**
1729 * Finds a view that was identified by the id attribute from the XML that
1730 * was processed in {@link #onCreate}.
1731 *
1732 * @return The view if found or null otherwise.
1733 */
1734 public View findViewById(int id) {
1735 return getWindow().findViewById(id);
1736 }
Adam Powell33b97432010-04-20 10:01:14 -07001737
1738 /**
1739 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001740 *
Adam Powell33b97432010-04-20 10:01:14 -07001741 * @return The Activity's ActionBar, or null if it does not have one.
1742 */
1743 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001744 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001745 return mActionBar;
1746 }
1747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 /**
Adam Powell33b97432010-04-20 10:01:14 -07001749 * Creates a new ActionBar, locates the inflated ActionBarView,
1750 * initializes the ActionBar with the view, and sets mActionBar.
1751 */
1752 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001753 Window window = getWindow();
Adam Powell9b4c8042010-08-10 15:36:44 -07001754 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001755 return;
1756 }
1757
Adam Powell661c9082010-07-02 10:09:44 -07001758 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001759 }
1760
1761 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 * Set the activity content from a layout resource. The resource will be
1763 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08001764 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 * @param layoutResID Resource ID to be inflated.
Romain Guy482b34a62011-01-20 10:59:28 -08001766 *
1767 * @see #setContentView(android.view.View)
1768 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 */
1770 public void setContentView(int layoutResID) {
1771 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001772 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774
1775 /**
1776 * Set the activity content to an explicit view. This view is placed
1777 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001778 * view hierarchy. When calling this method, the layout parameters of the
1779 * specified view are ignored. Both the width and the height of the view are
1780 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
1781 * your own layout parameters, invoke
1782 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
1783 * instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 *
1785 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08001786 *
1787 * @see #setContentView(int)
1788 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 */
1790 public void setContentView(View view) {
1791 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001792 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794
1795 /**
1796 * Set the activity content to an explicit view. This view is placed
1797 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08001798 * view hierarchy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 *
1800 * @param view The desired content to display.
1801 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08001802 *
1803 * @see #setContentView(android.view.View)
1804 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 */
1806 public void setContentView(View view, ViewGroup.LayoutParams params) {
1807 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001808 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810
1811 /**
1812 * Add an additional content view to the activity. Added after any existing
1813 * ones in the activity -- existing views are NOT removed.
1814 *
1815 * @param view The desired content to display.
1816 * @param params Layout parameters for the view.
1817 */
1818 public void addContentView(View view, ViewGroup.LayoutParams params) {
1819 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001820 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822
1823 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08001824 * Sets whether this activity is finished when touched outside its window's
1825 * bounds.
1826 */
1827 public void setFinishOnTouchOutside(boolean finish) {
1828 mWindow.setCloseOnTouchOutside(finish);
1829 }
1830
1831 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1833 * keys.
1834 *
1835 * @see #setDefaultKeyMode
1836 */
1837 static public final int DEFAULT_KEYS_DISABLE = 0;
1838 /**
1839 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1840 * key handling.
1841 *
1842 * @see #setDefaultKeyMode
1843 */
1844 static public final int DEFAULT_KEYS_DIALER = 1;
1845 /**
1846 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1847 * default key handling.
1848 *
1849 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1850 *
1851 * @see #setDefaultKeyMode
1852 */
1853 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1854 /**
1855 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1856 * will start an application-defined search. (If the application or activity does not
1857 * actually define a search, the the keys will be ignored.)
1858 *
1859 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1860 *
1861 * @see #setDefaultKeyMode
1862 */
1863 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1864
1865 /**
1866 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1867 * will start a global search (typically web search, but some platforms may define alternate
1868 * methods for global search)
1869 *
1870 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1871 *
1872 * @see #setDefaultKeyMode
1873 */
1874 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1875
1876 /**
1877 * Select the default key handling for this activity. This controls what
1878 * will happen to key events that are not otherwise handled. The default
1879 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1880 * floor. Other modes allow you to launch the dialer
1881 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1882 * menu without requiring the menu key be held down
1883 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1884 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1885 *
1886 * <p>Note that the mode selected here does not impact the default
1887 * handling of system keys, such as the "back" and "menu" keys, and your
1888 * activity and its views always get a first chance to receive and handle
1889 * all application keys.
1890 *
1891 * @param mode The desired default key mode constant.
1892 *
1893 * @see #DEFAULT_KEYS_DISABLE
1894 * @see #DEFAULT_KEYS_DIALER
1895 * @see #DEFAULT_KEYS_SHORTCUT
1896 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1897 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1898 * @see #onKeyDown
1899 */
1900 public final void setDefaultKeyMode(int mode) {
1901 mDefaultKeyMode = mode;
1902
1903 // Some modes use a SpannableStringBuilder to track & dispatch input events
1904 // This list must remain in sync with the switch in onKeyDown()
1905 switch (mode) {
1906 case DEFAULT_KEYS_DISABLE:
1907 case DEFAULT_KEYS_SHORTCUT:
1908 mDefaultKeySsb = null; // not used in these modes
1909 break;
1910 case DEFAULT_KEYS_DIALER:
1911 case DEFAULT_KEYS_SEARCH_LOCAL:
1912 case DEFAULT_KEYS_SEARCH_GLOBAL:
1913 mDefaultKeySsb = new SpannableStringBuilder();
1914 Selection.setSelection(mDefaultKeySsb,0);
1915 break;
1916 default:
1917 throw new IllegalArgumentException();
1918 }
1919 }
1920
1921 /**
1922 * Called when a key was pressed down and not handled by any of the views
1923 * inside of the activity. So, for example, key presses while the cursor
1924 * is inside a TextView will not trigger the event (unless it is a navigation
1925 * to another object) because TextView handles its own key presses.
1926 *
1927 * <p>If the focused view didn't want this event, this method is called.
1928 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001929 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1930 * by calling {@link #onBackPressed()}, though the behavior varies based
1931 * on the application compatibility mode: for
1932 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1933 * it will set up the dispatch to call {@link #onKeyUp} where the action
1934 * will be performed; for earlier applications, it will perform the
1935 * action immediately in on-down, as those versions of the platform
1936 * behaved.
1937 *
1938 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001939 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 *
1941 * @return Return <code>true</code> to prevent this event from being propagated
1942 * further, or <code>false</code> to indicate that you have not handled
1943 * this event and it should continue to be propagated.
1944 * @see #onKeyUp
1945 * @see android.view.KeyEvent
1946 */
1947 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001948 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001949 if (getApplicationInfo().targetSdkVersion
1950 >= Build.VERSION_CODES.ECLAIR) {
1951 event.startTracking();
1952 } else {
1953 onBackPressed();
1954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 return true;
1956 }
1957
1958 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1959 return false;
1960 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001961 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1962 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1963 return true;
1964 }
1965 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 } else {
1967 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1968 boolean clearSpannable = false;
1969 boolean handled;
1970 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1971 clearSpannable = true;
1972 handled = false;
1973 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001974 handled = TextKeyListener.getInstance().onKeyDown(
1975 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 if (handled && mDefaultKeySsb.length() > 0) {
1977 // something useable has been typed - dispatch it now.
1978
1979 final String str = mDefaultKeySsb.toString();
1980 clearSpannable = true;
1981
1982 switch (mDefaultKeyMode) {
1983 case DEFAULT_KEYS_DIALER:
1984 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1985 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1986 startActivity(intent);
1987 break;
1988 case DEFAULT_KEYS_SEARCH_LOCAL:
1989 startSearch(str, false, null, false);
1990 break;
1991 case DEFAULT_KEYS_SEARCH_GLOBAL:
1992 startSearch(str, false, null, true);
1993 break;
1994 }
1995 }
1996 }
1997 if (clearSpannable) {
1998 mDefaultKeySsb.clear();
1999 mDefaultKeySsb.clearSpans();
2000 Selection.setSelection(mDefaultKeySsb,0);
2001 }
2002 return handled;
2003 }
2004 }
2005
2006 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002007 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2008 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2009 * the event).
2010 */
2011 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2012 return false;
2013 }
2014
2015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 * Called when a key was released and not handled by any of the views
2017 * inside of the activity. So, for example, key presses while the cursor
2018 * is inside a TextView will not trigger the event (unless it is a navigation
2019 * to another object) because TextView handles its own key presses.
2020 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002021 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2022 * and go back.
2023 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 * @return Return <code>true</code> to prevent this event from being propagated
2025 * further, or <code>false</code> to indicate that you have not handled
2026 * this event and it should continue to be propagated.
2027 * @see #onKeyDown
2028 * @see KeyEvent
2029 */
2030 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002031 if (getApplicationInfo().targetSdkVersion
2032 >= Build.VERSION_CODES.ECLAIR) {
2033 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2034 && !event.isCanceled()) {
2035 onBackPressed();
2036 return true;
2037 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 return false;
2040 }
2041
2042 /**
2043 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2044 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2045 * the event).
2046 */
2047 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2048 return false;
2049 }
2050
2051 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002052 * Called when the activity has detected the user's press of the back
2053 * key. The default implementation simply finishes the current activity,
2054 * but you can override this to do whatever you want.
2055 */
2056 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002057 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002058 finish();
2059 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002060 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002061
2062 /**
2063 * Called when a key shortcut event is not handled by any of the views in the Activity.
2064 * Override this method to implement global key shortcuts for the Activity.
2065 * Key shortcuts can also be implemented by setting the
2066 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2067 *
2068 * @param keyCode The value in event.getKeyCode().
2069 * @param event Description of the key event.
2070 * @return True if the key shortcut was handled.
2071 */
2072 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2073 return false;
2074 }
2075
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002076 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 * Called when a touch screen event was not handled by any of the views
2078 * under it. This is most useful to process touch events that happen
2079 * outside of your window bounds, where there is no view to receive it.
2080 *
2081 * @param event The touch screen event being processed.
2082 *
2083 * @return Return true if you have consumed the event, false if you haven't.
2084 * The default implementation always returns false.
2085 */
2086 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08002087 if (mWindow.shouldCloseOnTouch(this, event)) {
2088 finish();
2089 return true;
2090 }
2091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 return false;
2093 }
2094
2095 /**
2096 * Called when the trackball was moved and not handled by any of the
2097 * views inside of the activity. So, for example, if the trackball moves
2098 * while focus is on a button, you will receive a call here because
2099 * buttons do not normally do anything with trackball events. The call
2100 * here happens <em>before</em> trackball movements are converted to
2101 * DPAD key events, which then get sent back to the view hierarchy, and
2102 * will be processed at the point for things like focus navigation.
2103 *
2104 * @param event The trackball event being processed.
2105 *
2106 * @return Return true if you have consumed the event, false if you haven't.
2107 * The default implementation always returns false.
2108 */
2109 public boolean onTrackballEvent(MotionEvent event) {
2110 return false;
2111 }
2112
2113 /**
2114 * Called whenever a key, touch, or trackball event is dispatched to the
2115 * activity. Implement this method if you wish to know that the user has
2116 * interacted with the device in some way while your activity is running.
2117 * This callback and {@link #onUserLeaveHint} are intended to help
2118 * activities manage status bar notifications intelligently; specifically,
2119 * for helping activities determine the proper time to cancel a notfication.
2120 *
2121 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2122 * be accompanied by calls to {@link #onUserInteraction}. This
2123 * ensures that your activity will be told of relevant user activity such
2124 * as pulling down the notification pane and touching an item there.
2125 *
2126 * <p>Note that this callback will be invoked for the touch down action
2127 * that begins a touch gesture, but may not be invoked for the touch-moved
2128 * and touch-up actions that follow.
2129 *
2130 * @see #onUserLeaveHint()
2131 */
2132 public void onUserInteraction() {
2133 }
2134
2135 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2136 // Update window manager if: we have a view, that view is
2137 // attached to its parent (which will be a RootView), and
2138 // this activity is not embedded.
2139 if (mParent == null) {
2140 View decor = mDecor;
2141 if (decor != null && decor.getParent() != null) {
2142 getWindowManager().updateViewLayout(decor, params);
2143 }
2144 }
2145 }
2146
2147 public void onContentChanged() {
2148 }
2149
2150 /**
2151 * Called when the current {@link Window} of the activity gains or loses
2152 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002153 * to the user. The default implementation clears the key tracking
2154 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002156 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 * is managed independently of activity lifecycles. As such, while focus
2158 * changes will generally have some relation to lifecycle changes (an
2159 * activity that is stopped will not generally get window focus), you
2160 * should not rely on any particular order between the callbacks here and
2161 * those in the other lifecycle methods such as {@link #onResume}.
2162 *
2163 * <p>As a general rule, however, a resumed activity will have window
2164 * focus... unless it has displayed other dialogs or popups that take
2165 * input focus, in which case the activity itself will not have focus
2166 * when the other windows have it. Likewise, the system may display
2167 * system-level windows (such as the status bar notification panel or
2168 * a system alert) which will temporarily take window input focus without
2169 * pausing the foreground activity.
2170 *
2171 * @param hasFocus Whether the window of this activity has focus.
2172 *
2173 * @see #hasWindowFocus()
2174 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002175 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 */
2177 public void onWindowFocusChanged(boolean hasFocus) {
2178 }
2179
2180 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002181 * Called when the main window associated with the activity has been
2182 * attached to the window manager.
2183 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2184 * for more information.
2185 * @see View#onAttachedToWindow
2186 */
2187 public void onAttachedToWindow() {
2188 }
2189
2190 /**
2191 * Called when the main window associated with the activity has been
2192 * detached from the window manager.
2193 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2194 * for more information.
2195 * @see View#onDetachedFromWindow
2196 */
2197 public void onDetachedFromWindow() {
2198 }
2199
2200 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 * Returns true if this activity's <em>main</em> window currently has window focus.
2202 * Note that this is not the same as the view itself having focus.
2203 *
2204 * @return True if this activity's main window currently has window focus.
2205 *
2206 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2207 */
2208 public boolean hasWindowFocus() {
2209 Window w = getWindow();
2210 if (w != null) {
2211 View d = w.getDecorView();
2212 if (d != null) {
2213 return d.hasWindowFocus();
2214 }
2215 }
2216 return false;
2217 }
2218
2219 /**
2220 * Called to process key events. You can override this to intercept all
2221 * key events before they are dispatched to the window. Be sure to call
2222 * this implementation for key events that should be handled normally.
2223 *
2224 * @param event The key event.
2225 *
2226 * @return boolean Return true if this event was consumed.
2227 */
2228 public boolean dispatchKeyEvent(KeyEvent event) {
2229 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002230 Window win = getWindow();
2231 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 return true;
2233 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002234 View decor = mDecor;
2235 if (decor == null) decor = win.getDecorView();
2236 return event.dispatch(this, decor != null
2237 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
2239
2240 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002241 * Called to process a key shortcut event.
2242 * You can override this to intercept all key shortcut events before they are
2243 * dispatched to the window. Be sure to call this implementation for key shortcut
2244 * events that should be handled normally.
2245 *
2246 * @param event The key shortcut event.
2247 * @return True if this event was consumed.
2248 */
2249 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2250 onUserInteraction();
2251 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2252 return true;
2253 }
2254 return onKeyShortcut(event.getKeyCode(), event);
2255 }
2256
2257 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 * Called to process touch screen events. You can override this to
2259 * intercept all touch screen events before they are dispatched to the
2260 * window. Be sure to call this implementation for touch screen events
2261 * that should be handled normally.
2262 *
2263 * @param ev The touch screen event.
2264 *
2265 * @return boolean Return true if this event was consumed.
2266 */
2267 public boolean dispatchTouchEvent(MotionEvent ev) {
2268 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2269 onUserInteraction();
2270 }
2271 if (getWindow().superDispatchTouchEvent(ev)) {
2272 return true;
2273 }
2274 return onTouchEvent(ev);
2275 }
2276
2277 /**
2278 * Called to process trackball events. You can override this to
2279 * intercept all trackball events before they are dispatched to the
2280 * window. Be sure to call this implementation for trackball events
2281 * that should be handled normally.
2282 *
2283 * @param ev The trackball event.
2284 *
2285 * @return boolean Return true if this event was consumed.
2286 */
2287 public boolean dispatchTrackballEvent(MotionEvent ev) {
2288 onUserInteraction();
2289 if (getWindow().superDispatchTrackballEvent(ev)) {
2290 return true;
2291 }
2292 return onTrackballEvent(ev);
2293 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002294
2295 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2296 event.setClassName(getClass().getName());
2297 event.setPackageName(getPackageName());
2298
2299 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002300 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2301 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002302 event.setFullScreen(isFullScreen);
2303
2304 CharSequence title = getTitle();
2305 if (!TextUtils.isEmpty(title)) {
2306 event.getText().add(title);
2307 }
2308
2309 return true;
2310 }
2311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 /**
2313 * Default implementation of
2314 * {@link android.view.Window.Callback#onCreatePanelView}
2315 * for activities. This
2316 * simply returns null so that all panel sub-windows will have the default
2317 * menu behavior.
2318 */
2319 public View onCreatePanelView(int featureId) {
2320 return null;
2321 }
2322
2323 /**
2324 * Default implementation of
2325 * {@link android.view.Window.Callback#onCreatePanelMenu}
2326 * for activities. This calls through to the new
2327 * {@link #onCreateOptionsMenu} method for the
2328 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2329 * so that subclasses of Activity don't need to deal with feature codes.
2330 */
2331 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2332 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002333 boolean show = onCreateOptionsMenu(menu);
2334 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2335 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337 return false;
2338 }
2339
2340 /**
2341 * Default implementation of
2342 * {@link android.view.Window.Callback#onPreparePanel}
2343 * for activities. This
2344 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2345 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2346 * panel, so that subclasses of
2347 * Activity don't need to deal with feature codes.
2348 */
2349 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2350 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2351 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002352 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 return goforit && menu.hasVisibleItems();
2354 }
2355 return true;
2356 }
2357
2358 /**
2359 * {@inheritDoc}
2360 *
2361 * @return The default implementation returns true.
2362 */
2363 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002364 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell049dd3d2010-12-02 13:43:59 -08002365 if (mActionBar != null) {
2366 mActionBar.dispatchMenuVisibilityChanged(true);
2367 } else {
2368 Log.e(TAG, "Tried to open action bar menu with no action bar");
2369 }
Adam Powell8515ee82010-11-30 14:09:55 -08002370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 return true;
2372 }
2373
2374 /**
2375 * Default implementation of
2376 * {@link android.view.Window.Callback#onMenuItemSelected}
2377 * for activities. This calls through to the new
2378 * {@link #onOptionsItemSelected} method for the
2379 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2380 * panel, so that subclasses of
2381 * Activity don't need to deal with feature codes.
2382 */
2383 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2384 switch (featureId) {
2385 case Window.FEATURE_OPTIONS_PANEL:
2386 // Put event logging here so it gets called even if subclass
2387 // doesn't call through to superclass's implmeentation of each
2388 // of these methods below
2389 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002390 if (onOptionsItemSelected(item)) {
2391 return true;
2392 }
2393 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394
2395 case Window.FEATURE_CONTEXT_MENU:
2396 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002397 if (onContextItemSelected(item)) {
2398 return true;
2399 }
2400 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 default:
2403 return false;
2404 }
2405 }
2406
2407 /**
2408 * Default implementation of
2409 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2410 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2411 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2412 * so that subclasses of Activity don't need to deal with feature codes.
2413 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2414 * {@link #onContextMenuClosed(Menu)} will be called.
2415 */
2416 public void onPanelClosed(int featureId, Menu menu) {
2417 switch (featureId) {
2418 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002419 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 onOptionsMenuClosed(menu);
2421 break;
2422
2423 case Window.FEATURE_CONTEXT_MENU:
2424 onContextMenuClosed(menu);
2425 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002426
2427 case Window.FEATURE_ACTION_BAR:
2428 mActionBar.dispatchMenuVisibilityChanged(false);
2429 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 }
2431 }
2432
2433 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002434 * Declare that the options menu has changed, so should be recreated.
2435 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2436 * time it needs to be displayed.
2437 */
2438 public void invalidateOptionsMenu() {
2439 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2440 }
2441
2442 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 * Initialize the contents of the Activity's standard options menu. You
2444 * should place your menu items in to <var>menu</var>.
2445 *
2446 * <p>This is only called once, the first time the options menu is
2447 * displayed. To update the menu every time it is displayed, see
2448 * {@link #onPrepareOptionsMenu}.
2449 *
2450 * <p>The default implementation populates the menu with standard system
2451 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2452 * they will be correctly ordered with application-defined menu items.
2453 * Deriving classes should always call through to the base implementation.
2454 *
2455 * <p>You can safely hold on to <var>menu</var> (and any items created
2456 * from it), making modifications to it as desired, until the next
2457 * time onCreateOptionsMenu() is called.
2458 *
2459 * <p>When you add items to the menu, you can implement the Activity's
2460 * {@link #onOptionsItemSelected} method to handle them there.
2461 *
2462 * @param menu The options menu in which you place your items.
2463 *
2464 * @return You must return true for the menu to be displayed;
2465 * if you return false it will not be shown.
2466 *
2467 * @see #onPrepareOptionsMenu
2468 * @see #onOptionsItemSelected
2469 */
2470 public boolean onCreateOptionsMenu(Menu menu) {
2471 if (mParent != null) {
2472 return mParent.onCreateOptionsMenu(menu);
2473 }
2474 return true;
2475 }
2476
2477 /**
2478 * Prepare the Screen's standard options menu to be displayed. This is
2479 * called right before the menu is shown, every time it is shown. You can
2480 * use this method to efficiently enable/disable items or otherwise
2481 * dynamically modify the contents.
2482 *
2483 * <p>The default implementation updates the system menu items based on the
2484 * activity's state. Deriving classes should always call through to the
2485 * base class implementation.
2486 *
2487 * @param menu The options menu as last shown or first initialized by
2488 * onCreateOptionsMenu().
2489 *
2490 * @return You must return true for the menu to be displayed;
2491 * if you return false it will not be shown.
2492 *
2493 * @see #onCreateOptionsMenu
2494 */
2495 public boolean onPrepareOptionsMenu(Menu menu) {
2496 if (mParent != null) {
2497 return mParent.onPrepareOptionsMenu(menu);
2498 }
2499 return true;
2500 }
2501
2502 /**
2503 * This hook is called whenever an item in your options menu is selected.
2504 * The default implementation simply returns false to have the normal
2505 * processing happen (calling the item's Runnable or sending a message to
2506 * its Handler as appropriate). You can use this method for any items
2507 * for which you would like to do processing without those other
2508 * facilities.
2509 *
2510 * <p>Derived classes should call through to the base class for it to
2511 * perform the default menu handling.
2512 *
2513 * @param item The menu item that was selected.
2514 *
2515 * @return boolean Return false to allow normal menu processing to
2516 * proceed, true to consume it here.
2517 *
2518 * @see #onCreateOptionsMenu
2519 */
2520 public boolean onOptionsItemSelected(MenuItem item) {
2521 if (mParent != null) {
2522 return mParent.onOptionsItemSelected(item);
2523 }
2524 return false;
2525 }
2526
2527 /**
2528 * This hook is called whenever the options menu is being closed (either by the user canceling
2529 * the menu with the back/menu button, or when an item is selected).
2530 *
2531 * @param menu The options menu as last shown or first initialized by
2532 * onCreateOptionsMenu().
2533 */
2534 public void onOptionsMenuClosed(Menu menu) {
2535 if (mParent != null) {
2536 mParent.onOptionsMenuClosed(menu);
2537 }
2538 }
2539
2540 /**
2541 * Programmatically opens the options menu. If the options menu is already
2542 * open, this method does nothing.
2543 */
2544 public void openOptionsMenu() {
2545 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2546 }
2547
2548 /**
2549 * Progammatically closes the options menu. If the options menu is already
2550 * closed, this method does nothing.
2551 */
2552 public void closeOptionsMenu() {
2553 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2554 }
2555
2556 /**
2557 * Called when a context menu for the {@code view} is about to be shown.
2558 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2559 * time the context menu is about to be shown and should be populated for
2560 * the view (or item inside the view for {@link AdapterView} subclasses,
2561 * this can be found in the {@code menuInfo})).
2562 * <p>
2563 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2564 * item has been selected.
2565 * <p>
2566 * It is not safe to hold onto the context menu after this method returns.
2567 * {@inheritDoc}
2568 */
2569 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2570 }
2571
2572 /**
2573 * Registers a context menu to be shown for the given view (multiple views
2574 * can show the context menu). This method will set the
2575 * {@link OnCreateContextMenuListener} on the view to this activity, so
2576 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2577 * called when it is time to show the context menu.
2578 *
2579 * @see #unregisterForContextMenu(View)
2580 * @param view The view that should show a context menu.
2581 */
2582 public void registerForContextMenu(View view) {
2583 view.setOnCreateContextMenuListener(this);
2584 }
2585
2586 /**
2587 * Prevents a context menu to be shown for the given view. This method will remove the
2588 * {@link OnCreateContextMenuListener} on the view.
2589 *
2590 * @see #registerForContextMenu(View)
2591 * @param view The view that should stop showing a context menu.
2592 */
2593 public void unregisterForContextMenu(View view) {
2594 view.setOnCreateContextMenuListener(null);
2595 }
2596
2597 /**
2598 * Programmatically opens the context menu for a particular {@code view}.
2599 * The {@code view} should have been added via
2600 * {@link #registerForContextMenu(View)}.
2601 *
2602 * @param view The view to show the context menu for.
2603 */
2604 public void openContextMenu(View view) {
2605 view.showContextMenu();
2606 }
2607
2608 /**
2609 * Programmatically closes the most recently opened context menu, if showing.
2610 */
2611 public void closeContextMenu() {
2612 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2613 }
2614
2615 /**
2616 * This hook is called whenever an item in a context menu is selected. The
2617 * default implementation simply returns false to have the normal processing
2618 * happen (calling the item's Runnable or sending a message to its Handler
2619 * as appropriate). You can use this method for any items for which you
2620 * would like to do processing without those other facilities.
2621 * <p>
2622 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2623 * View that added this menu item.
2624 * <p>
2625 * Derived classes should call through to the base class for it to perform
2626 * the default menu handling.
2627 *
2628 * @param item The context menu item that was selected.
2629 * @return boolean Return false to allow normal context menu processing to
2630 * proceed, true to consume it here.
2631 */
2632 public boolean onContextItemSelected(MenuItem item) {
2633 if (mParent != null) {
2634 return mParent.onContextItemSelected(item);
2635 }
2636 return false;
2637 }
2638
2639 /**
2640 * This hook is called whenever the context menu is being closed (either by
2641 * the user canceling the menu with the back/menu button, or when an item is
2642 * selected).
2643 *
2644 * @param menu The context menu that is being closed.
2645 */
2646 public void onContextMenuClosed(Menu menu) {
2647 if (mParent != null) {
2648 mParent.onContextMenuClosed(menu);
2649 }
2650 }
2651
2652 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002653 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002655 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 protected Dialog onCreateDialog(int id) {
2657 return null;
2658 }
2659
2660 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002661 * Callback for creating dialogs that are managed (saved and restored) for you
2662 * by the activity. The default implementation calls through to
2663 * {@link #onCreateDialog(int)} for compatibility.
2664 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002665 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2666 * or later, consider instead using a {@link DialogFragment} instead.</em>
2667 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002668 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2669 * this method the first time, and hang onto it thereafter. Any dialog
2670 * that is created by this method will automatically be saved and restored
2671 * for you, including whether it is showing.
2672 *
2673 * <p>If you would like the activity to manage saving and restoring dialogs
2674 * for you, you should override this method and handle any ids that are
2675 * passed to {@link #showDialog}.
2676 *
2677 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2678 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2679 *
2680 * @param id The id of the dialog.
2681 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2682 * @return The dialog. If you return null, the dialog will not be created.
2683 *
2684 * @see #onPrepareDialog(int, Dialog, Bundle)
2685 * @see #showDialog(int, Bundle)
2686 * @see #dismissDialog(int)
2687 * @see #removeDialog(int)
2688 */
2689 protected Dialog onCreateDialog(int id, Bundle args) {
2690 return onCreateDialog(id);
2691 }
2692
2693 /**
2694 * @deprecated Old no-arguments version of
2695 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2696 */
2697 @Deprecated
2698 protected void onPrepareDialog(int id, Dialog dialog) {
2699 dialog.setOwnerActivity(this);
2700 }
2701
2702 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002704 * shown. The default implementation calls through to
2705 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2706 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 * <p>
2708 * Override this if you need to update a managed dialog based on the state
2709 * of the application each time it is shown. For example, a time picker
2710 * dialog might want to be updated with the current time. You should call
2711 * through to the superclass's implementation. The default implementation
2712 * will set this Activity as the owner activity on the Dialog.
2713 *
2714 * @param id The id of the managed dialog.
2715 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002716 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2717 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 * @see #showDialog(int)
2719 * @see #dismissDialog(int)
2720 * @see #removeDialog(int)
2721 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002722 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2723 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725
2726 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002727 * Simple version of {@link #showDialog(int, Bundle)} that does not
2728 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2729 * with null arguments.
2730 */
2731 public final void showDialog(int id) {
2732 showDialog(id, null);
2733 }
2734
2735 /**
2736 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 * will be made with the same id the first time this is called for a given
2738 * id. From thereafter, the dialog will be automatically saved and restored.
2739 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002740 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2741 * or later, consider instead using a {@link DialogFragment} instead.</em>
2742 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002743 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 * be made to provide an opportunity to do any timely preparation.
2745 *
2746 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002747 * @param args Arguments to pass through to the dialog. These will be saved
2748 * and restored for you. Note that if the dialog is already created,
2749 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2750 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002751 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002752 * @return Returns true if the Dialog was created; false is returned if
2753 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2754 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002755 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002756 * @see #onCreateDialog(int, Bundle)
2757 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 * @see #dismissDialog(int)
2759 * @see #removeDialog(int)
2760 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002761 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002763 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002765 ManagedDialog md = mManagedDialogs.get(id);
2766 if (md == null) {
2767 md = new ManagedDialog();
2768 md.mDialog = createDialog(id, null, args);
2769 if (md.mDialog == null) {
2770 return false;
2771 }
2772 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 }
2774
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002775 md.mArgs = args;
2776 onPrepareDialog(id, md.mDialog, args);
2777 md.mDialog.show();
2778 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780
2781 /**
2782 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2783 *
2784 * @param id The id of the managed dialog.
2785 *
2786 * @throws IllegalArgumentException if the id was not previously shown via
2787 * {@link #showDialog(int)}.
2788 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002789 * @see #onCreateDialog(int, Bundle)
2790 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 * @see #showDialog(int)
2792 * @see #removeDialog(int)
2793 */
2794 public final void dismissDialog(int id) {
2795 if (mManagedDialogs == null) {
2796 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002798
2799 final ManagedDialog md = mManagedDialogs.get(id);
2800 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 throw missingDialog(id);
2802 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002803 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 }
2805
2806 /**
2807 * Creates an exception to throw if a user passed in a dialog id that is
2808 * unexpected.
2809 */
2810 private IllegalArgumentException missingDialog(int id) {
2811 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2812 + "shown via Activity#showDialog");
2813 }
2814
2815 /**
2816 * Removes any internal references to a dialog managed by this Activity.
2817 * If the dialog is showing, it will dismiss it as part of the clean up.
2818 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002819 * <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 -08002820 * want to avoid the overhead of saving and restoring it in the future.
2821 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002822 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2823 * will not throw an exception if you try to remove an ID that does not
2824 * currently have an associated dialog.</p>
2825 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 * @param id The id of the managed dialog.
2827 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002828 * @see #onCreateDialog(int, Bundle)
2829 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 * @see #showDialog(int)
2831 * @see #dismissDialog(int)
2832 */
2833 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002834 if (mManagedDialogs != null) {
2835 final ManagedDialog md = mManagedDialogs.get(id);
2836 if (md != null) {
2837 md.mDialog.dismiss();
2838 mManagedDialogs.remove(id);
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842
2843 /**
2844 * This hook is called when the user signals the desire to start a search.
2845 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002846 * <p>You can use this function as a simple way to launch the search UI, in response to a
2847 * menu item, search button, or other widgets within your activity. Unless overidden,
2848 * calling this function is the same as calling
2849 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2850 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 *
2852 * <p>You can override this function to force global search, e.g. in response to a dedicated
2853 * search key, or to block search entirely (by simply returning false).
2854 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002855 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2856 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 *
2858 * @see android.app.SearchManager
2859 */
2860 public boolean onSearchRequested() {
2861 startSearch(null, false, null, false);
2862 return true;
2863 }
2864
2865 /**
2866 * This hook is called to launch the search UI.
2867 *
2868 * <p>It is typically called from onSearchRequested(), either directly from
2869 * Activity.onSearchRequested() or from an overridden version in any given
2870 * Activity. If your goal is simply to activate search, it is preferred to call
2871 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2872 * is to inject specific data such as context data, it is preferred to <i>override</i>
2873 * onSearchRequested(), so that any callers to it will benefit from the override.
2874 *
2875 * @param initialQuery Any non-null non-empty string will be inserted as
2876 * pre-entered text in the search query box.
2877 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2878 * any further typing will replace it. This is useful for cases where an entire pre-formed
2879 * query is being inserted. If false, the selection point will be placed at the end of the
2880 * inserted query. This is useful when the inserted query is text that the user entered,
2881 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2882 * if initialQuery is a non-empty string.</i>
2883 * @param appSearchData An application can insert application-specific
2884 * context here, in order to improve quality or specificity of its own
2885 * searches. This data will be returned with SEARCH intent(s). Null if
2886 * no extra data is required.
2887 * @param globalSearch If false, this will only launch the search that has been specifically
2888 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002889 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2891 *
2892 * @see android.app.SearchManager
2893 * @see #onSearchRequested
2894 */
2895 public void startSearch(String initialQuery, boolean selectInitialQuery,
2896 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002897 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002898 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 appSearchData, globalSearch);
2900 }
2901
2902 /**
krosaend2d60142009-08-17 08:56:48 -07002903 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2904 * the search dialog. Made available for testing purposes.
2905 *
2906 * @param query The query to trigger. If empty, the request will be ignored.
2907 * @param appSearchData An application can insert application-specific
2908 * context here, in order to improve quality or specificity of its own
2909 * searches. This data will be returned with SEARCH intent(s). Null if
2910 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002911 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002912 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002913 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002914 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002915 }
2916
2917 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 * Request that key events come to this activity. Use this if your
2919 * activity has no views with focus, but the activity still wants
2920 * a chance to process key events.
2921 *
2922 * @see android.view.Window#takeKeyEvents
2923 */
2924 public void takeKeyEvents(boolean get) {
2925 getWindow().takeKeyEvents(get);
2926 }
2927
2928 /**
2929 * Enable extended window features. This is a convenience for calling
2930 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2931 *
2932 * @param featureId The desired feature as defined in
2933 * {@link android.view.Window}.
2934 * @return Returns true if the requested feature is supported and now
2935 * enabled.
2936 *
2937 * @see android.view.Window#requestFeature
2938 */
2939 public final boolean requestWindowFeature(int featureId) {
2940 return getWindow().requestFeature(featureId);
2941 }
2942
2943 /**
2944 * Convenience for calling
2945 * {@link android.view.Window#setFeatureDrawableResource}.
2946 */
2947 public final void setFeatureDrawableResource(int featureId, int resId) {
2948 getWindow().setFeatureDrawableResource(featureId, resId);
2949 }
2950
2951 /**
2952 * Convenience for calling
2953 * {@link android.view.Window#setFeatureDrawableUri}.
2954 */
2955 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2956 getWindow().setFeatureDrawableUri(featureId, uri);
2957 }
2958
2959 /**
2960 * Convenience for calling
2961 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2962 */
2963 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2964 getWindow().setFeatureDrawable(featureId, drawable);
2965 }
2966
2967 /**
2968 * Convenience for calling
2969 * {@link android.view.Window#setFeatureDrawableAlpha}.
2970 */
2971 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2972 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2973 }
2974
2975 /**
2976 * Convenience for calling
2977 * {@link android.view.Window#getLayoutInflater}.
2978 */
2979 public LayoutInflater getLayoutInflater() {
2980 return getWindow().getLayoutInflater();
2981 }
2982
2983 /**
2984 * Returns a {@link MenuInflater} with this context.
2985 */
2986 public MenuInflater getMenuInflater() {
2987 return new MenuInflater(this);
2988 }
2989
2990 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002991 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2992 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 if (mParent == null) {
2994 super.onApplyThemeResource(theme, resid, first);
2995 } else {
2996 try {
2997 theme.setTo(mParent.getTheme());
2998 } catch (Exception e) {
2999 // Empty
3000 }
3001 theme.applyStyle(resid, false);
3002 }
3003 }
3004
3005 /**
3006 * Launch an activity for which you would like a result when it finished.
3007 * When this activity exits, your
3008 * onActivityResult() method will be called with the given requestCode.
3009 * Using a negative requestCode is the same as calling
3010 * {@link #startActivity} (the activity is not launched as a sub-activity).
3011 *
3012 * <p>Note that this method should only be used with Intent protocols
3013 * that are defined to return a result. In other protocols (such as
3014 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3015 * not get the result when you expect. For example, if the activity you
3016 * are launching uses the singleTask launch mode, it will not run in your
3017 * task and thus you will immediately receive a cancel result.
3018 *
3019 * <p>As a special case, if you call startActivityForResult() with a requestCode
3020 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3021 * activity, then your window will not be displayed until a result is
3022 * returned back from the started activity. This is to avoid visible
3023 * flickering when redirecting to another activity.
3024 *
3025 * <p>This method throws {@link android.content.ActivityNotFoundException}
3026 * if there was no Activity found to run the given Intent.
3027 *
3028 * @param intent The intent to start.
3029 * @param requestCode If >= 0, this code will be returned in
3030 * onActivityResult() when the activity exits.
3031 *
3032 * @throws android.content.ActivityNotFoundException
3033 *
3034 * @see #startActivity
3035 */
3036 public void startActivityForResult(Intent intent, int requestCode) {
3037 if (mParent == null) {
3038 Instrumentation.ActivityResult ar =
3039 mInstrumentation.execStartActivity(
3040 this, mMainThread.getApplicationThread(), mToken, this,
3041 intent, requestCode);
3042 if (ar != null) {
3043 mMainThread.sendActivityResult(
3044 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3045 ar.getResultData());
3046 }
3047 if (requestCode >= 0) {
3048 // If this start is requesting a result, we can avoid making
3049 // the activity visible until the result is received. Setting
3050 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3051 // activity hidden during this time, to avoid flickering.
3052 // This can only be done when a result is requested because
3053 // that guarantees we will get information back when the
3054 // activity is finished, no matter what happens to it.
3055 mStartedActivity = true;
3056 }
3057 } else {
3058 mParent.startActivityFromChild(this, intent, requestCode);
3059 }
3060 }
3061
3062 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003063 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003064 * to use a IntentSender to describe the activity to be started. If
3065 * the IntentSender is for an activity, that activity will be started
3066 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3067 * here; otherwise, its associated action will be executed (such as
3068 * sending a broadcast) as if you had called
3069 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003070 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003071 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003072 * @param requestCode If >= 0, this code will be returned in
3073 * onActivityResult() when the activity exits.
3074 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003075 * intent parameter to {@link IntentSender#sendIntent}.
3076 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003077 * would like to change.
3078 * @param flagsValues Desired values for any bits set in
3079 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003080 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003081 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003082 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3083 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3084 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003085 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003086 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003087 flagsMask, flagsValues, this);
3088 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003089 mParent.startIntentSenderFromChild(this, intent, requestCode,
3090 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003091 }
3092 }
3093
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003094 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003095 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003096 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003097 try {
3098 String resolvedType = null;
3099 if (fillInIntent != null) {
3100 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3101 }
3102 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003103 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003104 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3105 requestCode, flagsMask, flagsValues);
3106 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003107 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003108 }
3109 Instrumentation.checkStartActivityResult(result, null);
3110 } catch (RemoteException e) {
3111 }
3112 if (requestCode >= 0) {
3113 // If this start is requesting a result, we can avoid making
3114 // the activity visible until the result is received. Setting
3115 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3116 // activity hidden during this time, to avoid flickering.
3117 // This can only be done when a result is requested because
3118 // that guarantees we will get information back when the
3119 // activity is finished, no matter what happens to it.
3120 mStartedActivity = true;
3121 }
3122 }
3123
3124 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 * Launch a new activity. You will not receive any information about when
3126 * the activity exits. This implementation overrides the base version,
3127 * providing information about
3128 * the activity performing the launch. Because of this additional
3129 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3130 * required; if not specified, the new activity will be added to the
3131 * task of the caller.
3132 *
3133 * <p>This method throws {@link android.content.ActivityNotFoundException}
3134 * if there was no Activity found to run the given Intent.
3135 *
3136 * @param intent The intent to start.
3137 *
3138 * @throws android.content.ActivityNotFoundException
3139 *
3140 * @see #startActivityForResult
3141 */
3142 @Override
3143 public void startActivity(Intent intent) {
3144 startActivityForResult(intent, -1);
3145 }
3146
3147 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003148 * Launch a new activity. You will not receive any information about when
3149 * the activity exits. This implementation overrides the base version,
3150 * providing information about
3151 * the activity performing the launch. Because of this additional
3152 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3153 * required; if not specified, the new activity will be added to the
3154 * task of the caller.
3155 *
3156 * <p>This method throws {@link android.content.ActivityNotFoundException}
3157 * if there was no Activity found to run the given Intent.
3158 *
3159 * @param intents The intents to start.
3160 *
3161 * @throws android.content.ActivityNotFoundException
3162 *
3163 * @see #startActivityForResult
3164 */
3165 @Override
3166 public void startActivities(Intent[] intents) {
3167 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3168 mToken, this, intents);
3169 }
3170
3171 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003172 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003173 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003174 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003175 * for more information.
3176 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003177 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003178 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003179 * intent parameter to {@link IntentSender#sendIntent}.
3180 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003181 * would like to change.
3182 * @param flagsValues Desired values for any bits set in
3183 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003184 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003185 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003186 public void startIntentSender(IntentSender intent,
3187 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3188 throws IntentSender.SendIntentException {
3189 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3190 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003191 }
3192
3193 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 * A special variation to launch an activity only if a new activity
3195 * instance is needed to handle the given Intent. In other words, this is
3196 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3197 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3198 * singleTask or singleTop
3199 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3200 * and the activity
3201 * that handles <var>intent</var> is the same as your currently running
3202 * activity, then a new instance is not needed. In this case, instead of
3203 * the normal behavior of calling {@link #onNewIntent} this function will
3204 * return and you can handle the Intent yourself.
3205 *
3206 * <p>This function can only be called from a top-level activity; if it is
3207 * called from a child activity, a runtime exception will be thrown.
3208 *
3209 * @param intent The intent to start.
3210 * @param requestCode If >= 0, this code will be returned in
3211 * onActivityResult() when the activity exits, as described in
3212 * {@link #startActivityForResult}.
3213 *
3214 * @return If a new activity was launched then true is returned; otherwise
3215 * false is returned and you must handle the Intent yourself.
3216 *
3217 * @see #startActivity
3218 * @see #startActivityForResult
3219 */
3220 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3221 if (mParent == null) {
3222 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3223 try {
3224 result = ActivityManagerNative.getDefault()
3225 .startActivity(mMainThread.getApplicationThread(),
3226 intent, intent.resolveTypeIfNeeded(
3227 getContentResolver()),
3228 null, 0,
3229 mToken, mEmbeddedID, requestCode, true, false);
3230 } catch (RemoteException e) {
3231 // Empty
3232 }
3233
3234 Instrumentation.checkStartActivityResult(result, intent);
3235
3236 if (requestCode >= 0) {
3237 // If this start is requesting a result, we can avoid making
3238 // the activity visible until the result is received. Setting
3239 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3240 // activity hidden during this time, to avoid flickering.
3241 // This can only be done when a result is requested because
3242 // that guarantees we will get information back when the
3243 // activity is finished, no matter what happens to it.
3244 mStartedActivity = true;
3245 }
3246 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3247 }
3248
3249 throw new UnsupportedOperationException(
3250 "startActivityIfNeeded can only be called from a top-level activity");
3251 }
3252
3253 /**
3254 * Special version of starting an activity, for use when you are replacing
3255 * other activity components. You can use this to hand the Intent off
3256 * to the next Activity that can handle it. You typically call this in
3257 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3258 *
3259 * @param intent The intent to dispatch to the next activity. For
3260 * correct behavior, this must be the same as the Intent that started
3261 * your own activity; the only changes you can make are to the extras
3262 * inside of it.
3263 *
3264 * @return Returns a boolean indicating whether there was another Activity
3265 * to start: true if there was a next activity to start, false if there
3266 * wasn't. In general, if true is returned you will then want to call
3267 * finish() on yourself.
3268 */
3269 public boolean startNextMatchingActivity(Intent intent) {
3270 if (mParent == null) {
3271 try {
3272 return ActivityManagerNative.getDefault()
3273 .startNextMatchingActivity(mToken, intent);
3274 } catch (RemoteException e) {
3275 // Empty
3276 }
3277 return false;
3278 }
3279
3280 throw new UnsupportedOperationException(
3281 "startNextMatchingActivity can only be called from a top-level activity");
3282 }
3283
3284 /**
3285 * This is called when a child activity of this one calls its
3286 * {@link #startActivity} or {@link #startActivityForResult} method.
3287 *
3288 * <p>This method throws {@link android.content.ActivityNotFoundException}
3289 * if there was no Activity found to run the given Intent.
3290 *
3291 * @param child The activity making the call.
3292 * @param intent The intent to start.
3293 * @param requestCode Reply request code. < 0 if reply is not requested.
3294 *
3295 * @throws android.content.ActivityNotFoundException
3296 *
3297 * @see #startActivity
3298 * @see #startActivityForResult
3299 */
3300 public void startActivityFromChild(Activity child, Intent intent,
3301 int requestCode) {
3302 Instrumentation.ActivityResult ar =
3303 mInstrumentation.execStartActivity(
3304 this, mMainThread.getApplicationThread(), mToken, child,
3305 intent, requestCode);
3306 if (ar != null) {
3307 mMainThread.sendActivityResult(
3308 mToken, child.mEmbeddedID, requestCode,
3309 ar.getResultCode(), ar.getResultData());
3310 }
3311 }
3312
3313 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003314 * This is called when a Fragment in this activity calls its
3315 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3316 * method.
3317 *
3318 * <p>This method throws {@link android.content.ActivityNotFoundException}
3319 * if there was no Activity found to run the given Intent.
3320 *
3321 * @param fragment The fragment making the call.
3322 * @param intent The intent to start.
3323 * @param requestCode Reply request code. < 0 if reply is not requested.
3324 *
3325 * @throws android.content.ActivityNotFoundException
3326 *
3327 * @see Fragment#startActivity
3328 * @see Fragment#startActivityForResult
3329 */
3330 public void startActivityFromFragment(Fragment fragment, Intent intent,
3331 int requestCode) {
3332 Instrumentation.ActivityResult ar =
3333 mInstrumentation.execStartActivity(
3334 this, mMainThread.getApplicationThread(), mToken, fragment,
3335 intent, requestCode);
3336 if (ar != null) {
3337 mMainThread.sendActivityResult(
3338 mToken, fragment.mWho, requestCode,
3339 ar.getResultCode(), ar.getResultData());
3340 }
3341 }
3342
3343 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003344 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003345 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003346 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003347 * for more information.
3348 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003349 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3350 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3351 int extraFlags)
3352 throws IntentSender.SendIntentException {
3353 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003354 flagsMask, flagsValues, child);
3355 }
3356
3357 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003358 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3359 * or {@link #finish} to specify an explicit transition animation to
3360 * perform next.
3361 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003362 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003363 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003364 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003365 */
3366 public void overridePendingTransition(int enterAnim, int exitAnim) {
3367 try {
3368 ActivityManagerNative.getDefault().overridePendingTransition(
3369 mToken, getPackageName(), enterAnim, exitAnim);
3370 } catch (RemoteException e) {
3371 }
3372 }
3373
3374 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 * Call this to set the result that your activity will return to its
3376 * caller.
3377 *
3378 * @param resultCode The result code to propagate back to the originating
3379 * activity, often RESULT_CANCELED or RESULT_OK
3380 *
3381 * @see #RESULT_CANCELED
3382 * @see #RESULT_OK
3383 * @see #RESULT_FIRST_USER
3384 * @see #setResult(int, Intent)
3385 */
3386 public final void setResult(int resultCode) {
3387 synchronized (this) {
3388 mResultCode = resultCode;
3389 mResultData = null;
3390 }
3391 }
3392
3393 /**
3394 * Call this to set the result that your activity will return to its
3395 * caller.
3396 *
3397 * @param resultCode The result code to propagate back to the originating
3398 * activity, often RESULT_CANCELED or RESULT_OK
3399 * @param data The data to propagate back to the originating activity.
3400 *
3401 * @see #RESULT_CANCELED
3402 * @see #RESULT_OK
3403 * @see #RESULT_FIRST_USER
3404 * @see #setResult(int)
3405 */
3406 public final void setResult(int resultCode, Intent data) {
3407 synchronized (this) {
3408 mResultCode = resultCode;
3409 mResultData = data;
3410 }
3411 }
3412
3413 /**
3414 * Return the name of the package that invoked this activity. This is who
3415 * the data in {@link #setResult setResult()} will be sent to. You can
3416 * use this information to validate that the recipient is allowed to
3417 * receive the data.
3418 *
3419 * <p>Note: if the calling activity is not expecting a result (that is it
3420 * did not use the {@link #startActivityForResult}
3421 * form that includes a request code), then the calling package will be
3422 * null.
3423 *
3424 * @return The package of the activity that will receive your
3425 * reply, or null if none.
3426 */
3427 public String getCallingPackage() {
3428 try {
3429 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3430 } catch (RemoteException e) {
3431 return null;
3432 }
3433 }
3434
3435 /**
3436 * Return the name of the activity that invoked this activity. This is
3437 * who the data in {@link #setResult setResult()} will be sent to. You
3438 * can use this information to validate that the recipient is allowed to
3439 * receive the data.
3440 *
3441 * <p>Note: if the calling activity is not expecting a result (that is it
3442 * did not use the {@link #startActivityForResult}
3443 * form that includes a request code), then the calling package will be
3444 * null.
3445 *
3446 * @return String The full name of the activity that will receive your
3447 * reply, or null if none.
3448 */
3449 public ComponentName getCallingActivity() {
3450 try {
3451 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3452 } catch (RemoteException e) {
3453 return null;
3454 }
3455 }
3456
3457 /**
3458 * Control whether this activity's main window is visible. This is intended
3459 * only for the special case of an activity that is not going to show a
3460 * UI itself, but can't just finish prior to onResume() because it needs
3461 * to wait for a service binding or such. Setting this to false allows
3462 * you to prevent your UI from being shown during that time.
3463 *
3464 * <p>The default value for this is taken from the
3465 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3466 */
3467 public void setVisible(boolean visible) {
3468 if (mVisibleFromClient != visible) {
3469 mVisibleFromClient = visible;
3470 if (mVisibleFromServer) {
3471 if (visible) makeVisible();
3472 else mDecor.setVisibility(View.INVISIBLE);
3473 }
3474 }
3475 }
3476
3477 void makeVisible() {
3478 if (!mWindowAdded) {
3479 ViewManager wm = getWindowManager();
3480 wm.addView(mDecor, getWindow().getAttributes());
3481 mWindowAdded = true;
3482 }
3483 mDecor.setVisibility(View.VISIBLE);
3484 }
3485
3486 /**
3487 * Check to see whether this activity is in the process of finishing,
3488 * either because you called {@link #finish} on it or someone else
3489 * has requested that it finished. This is often used in
3490 * {@link #onPause} to determine whether the activity is simply pausing or
3491 * completely finishing.
3492 *
3493 * @return If the activity is finishing, returns true; else returns false.
3494 *
3495 * @see #finish
3496 */
3497 public boolean isFinishing() {
3498 return mFinished;
3499 }
3500
3501 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003502 * Check to see whether this activity is in the process of being destroyed in order to be
3503 * recreated with a new configuration. This is often used in
3504 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3505 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3506 *
3507 * @return If the activity is being torn down in order to be recreated with a new configuration,
3508 * returns true; else returns false.
3509 */
3510 public boolean isChangingConfigurations() {
3511 return mChangingConfigurations;
3512 }
3513
3514 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003515 * Cause this Activity to be recreated with a new instance. This results
3516 * in essentially the same flow as when the Activity is created due to
3517 * a configuration change -- the current instance will go through its
3518 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3519 */
3520 public void recreate() {
3521 if (mParent != null) {
3522 throw new IllegalStateException("Can only be called on top-level activity");
3523 }
3524 if (Looper.myLooper() != mMainThread.getLooper()) {
3525 throw new IllegalStateException("Must be called from main thread");
3526 }
3527 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3528 }
3529
3530 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 * Call this when your activity is done and should be closed. The
3532 * ActivityResult is propagated back to whoever launched you via
3533 * onActivityResult().
3534 */
3535 public void finish() {
3536 if (mParent == null) {
3537 int resultCode;
3538 Intent resultData;
3539 synchronized (this) {
3540 resultCode = mResultCode;
3541 resultData = mResultData;
3542 }
3543 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3544 try {
3545 if (ActivityManagerNative.getDefault()
3546 .finishActivity(mToken, resultCode, resultData)) {
3547 mFinished = true;
3548 }
3549 } catch (RemoteException e) {
3550 // Empty
3551 }
3552 } else {
3553 mParent.finishFromChild(this);
3554 }
3555 }
3556
3557 /**
3558 * This is called when a child activity of this one calls its
3559 * {@link #finish} method. The default implementation simply calls
3560 * finish() on this activity (the parent), finishing the entire group.
3561 *
3562 * @param child The activity making the call.
3563 *
3564 * @see #finish
3565 */
3566 public void finishFromChild(Activity child) {
3567 finish();
3568 }
3569
3570 /**
3571 * Force finish another activity that you had previously started with
3572 * {@link #startActivityForResult}.
3573 *
3574 * @param requestCode The request code of the activity that you had
3575 * given to startActivityForResult(). If there are multiple
3576 * activities started with this request code, they
3577 * will all be finished.
3578 */
3579 public void finishActivity(int requestCode) {
3580 if (mParent == null) {
3581 try {
3582 ActivityManagerNative.getDefault()
3583 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3584 } catch (RemoteException e) {
3585 // Empty
3586 }
3587 } else {
3588 mParent.finishActivityFromChild(this, requestCode);
3589 }
3590 }
3591
3592 /**
3593 * This is called when a child activity of this one calls its
3594 * finishActivity().
3595 *
3596 * @param child The activity making the call.
3597 * @param requestCode Request code that had been used to start the
3598 * activity.
3599 */
3600 public void finishActivityFromChild(Activity child, int requestCode) {
3601 try {
3602 ActivityManagerNative.getDefault()
3603 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3604 } catch (RemoteException e) {
3605 // Empty
3606 }
3607 }
3608
3609 /**
3610 * Called when an activity you launched exits, giving you the requestCode
3611 * you started it with, the resultCode it returned, and any additional
3612 * data from it. The <var>resultCode</var> will be
3613 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3614 * didn't return any result, or crashed during its operation.
3615 *
3616 * <p>You will receive this call immediately before onResume() when your
3617 * activity is re-starting.
3618 *
3619 * @param requestCode The integer request code originally supplied to
3620 * startActivityForResult(), allowing you to identify who this
3621 * result came from.
3622 * @param resultCode The integer result code returned by the child activity
3623 * through its setResult().
3624 * @param data An Intent, which can return result data to the caller
3625 * (various data can be attached to Intent "extras").
3626 *
3627 * @see #startActivityForResult
3628 * @see #createPendingResult
3629 * @see #setResult(int)
3630 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003631 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 }
3633
3634 /**
3635 * Create a new PendingIntent object which you can hand to others
3636 * for them to use to send result data back to your
3637 * {@link #onActivityResult} callback. The created object will be either
3638 * one-shot (becoming invalid after a result is sent back) or multiple
3639 * (allowing any number of results to be sent through it).
3640 *
3641 * @param requestCode Private request code for the sender that will be
3642 * associated with the result data when it is returned. The sender can not
3643 * modify this value, allowing you to identify incoming results.
3644 * @param data Default data to supply in the result, which may be modified
3645 * by the sender.
3646 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3647 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3648 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3649 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3650 * or any of the flags as supported by
3651 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3652 * of the intent that can be supplied when the actual send happens.
3653 *
3654 * @return Returns an existing or new PendingIntent matching the given
3655 * parameters. May return null only if
3656 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3657 * supplied.
3658 *
3659 * @see PendingIntent
3660 */
3661 public PendingIntent createPendingResult(int requestCode, Intent data,
3662 int flags) {
3663 String packageName = getPackageName();
3664 try {
3665 IIntentSender target =
3666 ActivityManagerNative.getDefault().getIntentSender(
3667 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3668 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003669 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 return target != null ? new PendingIntent(target) : null;
3671 } catch (RemoteException e) {
3672 // Empty
3673 }
3674 return null;
3675 }
3676
3677 /**
3678 * Change the desired orientation of this activity. If the activity
3679 * is currently in the foreground or otherwise impacting the screen
3680 * orientation, the screen will immediately be changed (possibly causing
3681 * the activity to be restarted). Otherwise, this will be used the next
3682 * time the activity is visible.
3683 *
3684 * @param requestedOrientation An orientation constant as used in
3685 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3686 */
3687 public void setRequestedOrientation(int requestedOrientation) {
3688 if (mParent == null) {
3689 try {
3690 ActivityManagerNative.getDefault().setRequestedOrientation(
3691 mToken, requestedOrientation);
3692 } catch (RemoteException e) {
3693 // Empty
3694 }
3695 } else {
3696 mParent.setRequestedOrientation(requestedOrientation);
3697 }
3698 }
3699
3700 /**
3701 * Return the current requested orientation of the activity. This will
3702 * either be the orientation requested in its component's manifest, or
3703 * the last requested orientation given to
3704 * {@link #setRequestedOrientation(int)}.
3705 *
3706 * @return Returns an orientation constant as used in
3707 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3708 */
3709 public int getRequestedOrientation() {
3710 if (mParent == null) {
3711 try {
3712 return ActivityManagerNative.getDefault()
3713 .getRequestedOrientation(mToken);
3714 } catch (RemoteException e) {
3715 // Empty
3716 }
3717 } else {
3718 return mParent.getRequestedOrientation();
3719 }
3720 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3721 }
3722
3723 /**
3724 * Return the identifier of the task this activity is in. This identifier
3725 * will remain the same for the lifetime of the activity.
3726 *
3727 * @return Task identifier, an opaque integer.
3728 */
3729 public int getTaskId() {
3730 try {
3731 return ActivityManagerNative.getDefault()
3732 .getTaskForActivity(mToken, false);
3733 } catch (RemoteException e) {
3734 return -1;
3735 }
3736 }
3737
3738 /**
3739 * Return whether this activity is the root of a task. The root is the
3740 * first activity in a task.
3741 *
3742 * @return True if this is the root activity, else false.
3743 */
3744 public boolean isTaskRoot() {
3745 try {
3746 return ActivityManagerNative.getDefault()
3747 .getTaskForActivity(mToken, true) >= 0;
3748 } catch (RemoteException e) {
3749 return false;
3750 }
3751 }
3752
3753 /**
3754 * Move the task containing this activity to the back of the activity
3755 * stack. The activity's order within the task is unchanged.
3756 *
3757 * @param nonRoot If false then this only works if the activity is the root
3758 * of a task; if true it will work for any activity in
3759 * a task.
3760 *
3761 * @return If the task was moved (or it was already at the
3762 * back) true is returned, else false.
3763 */
3764 public boolean moveTaskToBack(boolean nonRoot) {
3765 try {
3766 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3767 mToken, nonRoot);
3768 } catch (RemoteException e) {
3769 // Empty
3770 }
3771 return false;
3772 }
3773
3774 /**
3775 * Returns class name for this activity with the package prefix removed.
3776 * This is the default name used to read and write settings.
3777 *
3778 * @return The local class name.
3779 */
3780 public String getLocalClassName() {
3781 final String pkg = getPackageName();
3782 final String cls = mComponent.getClassName();
3783 int packageLen = pkg.length();
3784 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3785 || cls.charAt(packageLen) != '.') {
3786 return cls;
3787 }
3788 return cls.substring(packageLen+1);
3789 }
3790
3791 /**
3792 * Returns complete component name of this activity.
3793 *
3794 * @return Returns the complete component name for this activity
3795 */
3796 public ComponentName getComponentName()
3797 {
3798 return mComponent;
3799 }
3800
3801 /**
3802 * Retrieve a {@link SharedPreferences} object for accessing preferences
3803 * that are private to this activity. This simply calls the underlying
3804 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3805 * class name as the preferences name.
3806 *
3807 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3808 * operation, {@link #MODE_WORLD_READABLE} and
3809 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3810 *
3811 * @return Returns the single SharedPreferences instance that can be used
3812 * to retrieve and modify the preference values.
3813 */
3814 public SharedPreferences getPreferences(int mode) {
3815 return getSharedPreferences(getLocalClassName(), mode);
3816 }
3817
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003818 private void ensureSearchManager() {
3819 if (mSearchManager != null) {
3820 return;
3821 }
3822
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003823 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003824 }
3825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 @Override
3827 public Object getSystemService(String name) {
3828 if (getBaseContext() == null) {
3829 throw new IllegalStateException(
3830 "System services not available to Activities before onCreate()");
3831 }
3832
3833 if (WINDOW_SERVICE.equals(name)) {
3834 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003835 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003836 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003837 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839 return super.getSystemService(name);
3840 }
3841
3842 /**
3843 * Change the title associated with this activity. If this is a
3844 * top-level activity, the title for its window will change. If it
3845 * is an embedded activity, the parent can do whatever it wants
3846 * with it.
3847 */
3848 public void setTitle(CharSequence title) {
3849 mTitle = title;
3850 onTitleChanged(title, mTitleColor);
3851
3852 if (mParent != null) {
3853 mParent.onChildTitleChanged(this, title);
3854 }
3855 }
3856
3857 /**
3858 * Change the title associated with this activity. If this is a
3859 * top-level activity, the title for its window will change. If it
3860 * is an embedded activity, the parent can do whatever it wants
3861 * with it.
3862 */
3863 public void setTitle(int titleId) {
3864 setTitle(getText(titleId));
3865 }
3866
3867 public void setTitleColor(int textColor) {
3868 mTitleColor = textColor;
3869 onTitleChanged(mTitle, textColor);
3870 }
3871
3872 public final CharSequence getTitle() {
3873 return mTitle;
3874 }
3875
3876 public final int getTitleColor() {
3877 return mTitleColor;
3878 }
3879
3880 protected void onTitleChanged(CharSequence title, int color) {
3881 if (mTitleReady) {
3882 final Window win = getWindow();
3883 if (win != null) {
3884 win.setTitle(title);
3885 if (color != 0) {
3886 win.setTitleColor(color);
3887 }
3888 }
3889 }
3890 }
3891
3892 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3893 }
3894
3895 /**
3896 * Sets the visibility of the progress bar in the title.
3897 * <p>
3898 * In order for the progress bar to be shown, the feature must be requested
3899 * via {@link #requestWindowFeature(int)}.
3900 *
3901 * @param visible Whether to show the progress bars in the title.
3902 */
3903 public final void setProgressBarVisibility(boolean visible) {
3904 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3905 Window.PROGRESS_VISIBILITY_OFF);
3906 }
3907
3908 /**
3909 * Sets the visibility of the indeterminate progress bar in the title.
3910 * <p>
3911 * In order for the progress bar to be shown, the feature must be requested
3912 * via {@link #requestWindowFeature(int)}.
3913 *
3914 * @param visible Whether to show the progress bars in the title.
3915 */
3916 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3917 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3918 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3919 }
3920
3921 /**
3922 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3923 * is always indeterminate).
3924 * <p>
3925 * In order for the progress bar to be shown, the feature must be requested
3926 * via {@link #requestWindowFeature(int)}.
3927 *
3928 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3929 */
3930 public final void setProgressBarIndeterminate(boolean indeterminate) {
3931 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3932 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3933 }
3934
3935 /**
3936 * Sets the progress for the progress bars in the title.
3937 * <p>
3938 * In order for the progress bar to be shown, the feature must be requested
3939 * via {@link #requestWindowFeature(int)}.
3940 *
3941 * @param progress The progress for the progress bar. Valid ranges are from
3942 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3943 * bar will be completely filled and will fade out.
3944 */
3945 public final void setProgress(int progress) {
3946 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3947 }
3948
3949 /**
3950 * Sets the secondary progress for the progress bar in the title. This
3951 * progress is drawn between the primary progress (set via
3952 * {@link #setProgress(int)} and the background. It can be ideal for media
3953 * scenarios such as showing the buffering progress while the default
3954 * progress shows the play progress.
3955 * <p>
3956 * In order for the progress bar to be shown, the feature must be requested
3957 * via {@link #requestWindowFeature(int)}.
3958 *
3959 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3960 * 0 to 10000 (both inclusive).
3961 */
3962 public final void setSecondaryProgress(int secondaryProgress) {
3963 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3964 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3965 }
3966
3967 /**
3968 * Suggests an audio stream whose volume should be changed by the hardware
3969 * volume controls.
3970 * <p>
3971 * The suggested audio stream will be tied to the window of this Activity.
3972 * If the Activity is switched, the stream set here is no longer the
3973 * suggested stream. The client does not need to save and restore the old
3974 * suggested stream value in onPause and onResume.
3975 *
3976 * @param streamType The type of the audio stream whose volume should be
3977 * changed by the hardware volume controls. It is not guaranteed that
3978 * the hardware volume controls will always change this stream's
3979 * volume (for example, if a call is in progress, its stream's volume
3980 * may be changed instead). To reset back to the default, use
3981 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3982 */
3983 public final void setVolumeControlStream(int streamType) {
3984 getWindow().setVolumeControlStream(streamType);
3985 }
3986
3987 /**
3988 * Gets the suggested audio stream whose volume should be changed by the
3989 * harwdare volume controls.
3990 *
3991 * @return The suggested audio stream type whose volume should be changed by
3992 * the hardware volume controls.
3993 * @see #setVolumeControlStream(int)
3994 */
3995 public final int getVolumeControlStream() {
3996 return getWindow().getVolumeControlStream();
3997 }
3998
3999 /**
4000 * Runs the specified action on the UI thread. If the current thread is the UI
4001 * thread, then the action is executed immediately. If the current thread is
4002 * not the UI thread, the action is posted to the event queue of the UI thread.
4003 *
4004 * @param action the action to run on the UI thread
4005 */
4006 public final void runOnUiThread(Runnable action) {
4007 if (Thread.currentThread() != mUiThread) {
4008 mHandler.post(action);
4009 } else {
4010 action.run();
4011 }
4012 }
4013
4014 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004015 * Standard implementation of
4016 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4017 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004018 * This implementation does nothing and is for
4019 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4020 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4021 *
4022 * @see android.view.LayoutInflater#createView
4023 * @see android.view.Window#getLayoutInflater
4024 */
4025 public View onCreateView(String name, Context context, AttributeSet attrs) {
4026 return null;
4027 }
4028
4029 /**
4030 * Standard implementation of
4031 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4032 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004033 * This implementation handles <fragment> tags to embed fragments inside
4034 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 *
4036 * @see android.view.LayoutInflater#createView
4037 * @see android.view.Window#getLayoutInflater
4038 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004039 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004040 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004041 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004042 }
4043
Dianne Hackborndef15372010-08-15 12:43:52 -07004044 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004045 TypedArray a =
4046 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004047 if (fname == null) {
4048 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4049 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004050 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004051 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4052 a.recycle();
4053
Dianne Hackborn625ac272010-09-17 18:29:22 -07004054 int containerId = parent != null ? parent.getId() : 0;
4055 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004056 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004057 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004058 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004059
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004060 // If we restored from a previous state, we may already have
4061 // instantiated this fragment from the state and should use
4062 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004063 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4064 if (fragment == null && tag != null) {
4065 fragment = mFragments.findFragmentByTag(tag);
4066 }
4067 if (fragment == null && containerId != View.NO_ID) {
4068 fragment = mFragments.findFragmentById(containerId);
4069 }
4070
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004071 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4072 + Integer.toHexString(id) + " fname=" + fname
4073 + " existing=" + fragment);
4074 if (fragment == null) {
4075 fragment = Fragment.instantiate(this, fname);
4076 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004077 fragment.mFragmentId = id != 0 ? id : containerId;
4078 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004079 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004080 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004081 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004082 fragment.mFragmentManager = mFragments;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004083 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4084 mFragments.addFragment(fragment, true);
4085
4086 } else if (fragment.mInLayout) {
4087 // A fragment already exists and it is not one we restored from
4088 // previous state.
4089 throw new IllegalArgumentException(attrs.getPositionDescription()
4090 + ": Duplicate id 0x" + Integer.toHexString(id)
4091 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4092 + " with another fragment for " + fname);
4093 } else {
4094 // This fragment was retained from a previous instance; get it
4095 // going now.
4096 fragment.mInLayout = true;
4097 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004098 // If this fragment is newly instantiated (either right now, or
4099 // from last saved state), then give it the attributes to
4100 // initialize itself.
4101 if (!fragment.mRetaining) {
4102 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4103 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004104 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004105 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004106
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004107 if (fragment.mView == null) {
4108 throw new IllegalStateException("Fragment " + fname
4109 + " did not create a view.");
4110 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004111 if (id != 0) {
4112 fragment.mView.setId(id);
4113 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004114 if (fragment.mView.getTag() == null) {
4115 fragment.mView.setTag(tag);
4116 }
4117 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 }
4119
Daniel Sandler69a48172010-06-23 16:29:36 -04004120 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004121 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004122 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004123 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004124 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004125 * @param fd The raw file descriptor that the dump is being sent to.
4126 * @param writer The PrintWriter to which you should dump your state. This will be
4127 * closed for you after you return.
4128 * @param args additional arguments to the dump request.
4129 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004130 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4131 writer.print(prefix); writer.print("Local Activity ");
4132 writer.print(Integer.toHexString(System.identityHashCode(this)));
4133 writer.println(" State:");
4134 String innerPrefix = prefix + " ";
4135 writer.print(innerPrefix); writer.print("mResumed=");
4136 writer.print(mResumed); writer.print(" mStopped=");
4137 writer.print(mStopped); writer.print(" mFinished=");
4138 writer.println(mFinished);
4139 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4140 writer.println(mLoadersStarted);
4141 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4142 writer.println(mChangingConfigurations);
4143 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4144 writer.println(mCurrentConfig);
4145 if (mLoaderManager != null) {
4146 writer.print(prefix); writer.print("Loader Manager ");
4147 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4148 writer.println(":");
4149 mLoaderManager.dump(prefix + " ", fd, writer, args);
4150 }
4151 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004152 }
4153
4154 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004155 * Bit indicating that this activity is "immersive" and should not be
4156 * interrupted by notifications if possible.
4157 *
4158 * This value is initially set by the manifest property
4159 * <code>android:immersive</code> but may be changed at runtime by
4160 * {@link #setImmersive}.
4161 *
4162 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004163 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004164 */
4165 public boolean isImmersive() {
4166 try {
4167 return ActivityManagerNative.getDefault().isImmersive(mToken);
4168 } catch (RemoteException e) {
4169 return false;
4170 }
4171 }
4172
4173 /**
4174 * Adjust the current immersive mode setting.
4175 *
4176 * Note that changing this value will have no effect on the activity's
4177 * {@link android.content.pm.ActivityInfo} structure; that is, if
4178 * <code>android:immersive</code> is set to <code>true</code>
4179 * in the application's manifest entry for this activity, the {@link
4180 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4181 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4182 * FLAG_IMMERSIVE} bit set.
4183 *
4184 * @see #isImmersive
4185 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004186 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004187 */
4188 public void setImmersive(boolean i) {
4189 try {
4190 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4191 } catch (RemoteException e) {
4192 // pass
4193 }
4194 }
4195
Adam Powell6e346362010-07-23 10:18:23 -07004196 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004197 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004198 *
4199 * @param callback Callback that will manage lifecycle events for this context mode
4200 * @return The ContextMode that was started, or null if it was canceled
4201 *
4202 * @see ActionMode
4203 */
Adam Powell5d279772010-07-27 16:34:07 -07004204 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004205 return mWindow.getDecorView().startActionMode(callback);
4206 }
4207
Adam Powelldebf3be2010-11-15 18:58:48 -08004208 /**
4209 * Give the Activity a chance to control the UI for an action mode requested
4210 * by the system.
4211 *
4212 * <p>Note: If you are looking for a notification callback that an action mode
4213 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4214 *
4215 * @param callback The callback that should control the new action mode
4216 * @return The new action mode, or <code>null</code> if the activity does not want to
4217 * provide special handling for this action mode. (It will be handled by the system.)
4218 */
4219 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004220 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004221 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004222 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004223 }
4224 return null;
4225 }
4226
Adam Powelldebf3be2010-11-15 18:58:48 -08004227 /**
4228 * Notifies the Activity that an action mode has been started.
4229 * Activity subclasses overriding this method should call the superclass implementation.
4230 *
4231 * @param mode The new action mode.
4232 */
4233 public void onActionModeStarted(ActionMode mode) {
4234 }
4235
4236 /**
4237 * Notifies the activity that an action mode has finished.
4238 * Activity subclasses overriding this method should call the superclass implementation.
4239 *
4240 * @param mode The action mode that just finished.
4241 */
4242 public void onActionModeFinished(ActionMode mode) {
4243 }
4244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 // ------------------ Internal API ------------------
4246
4247 final void setParent(Activity parent) {
4248 mParent = parent;
4249 }
4250
4251 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4252 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004253 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004255 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004256 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
4258
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004259 final void attach(Context context, ActivityThread aThread,
4260 Instrumentation instr, IBinder token, int ident,
4261 Application application, Intent intent, ActivityInfo info,
4262 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004263 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004264 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 attachBaseContext(context);
4266
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004267 mFragments.attachActivity(this);
4268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 mWindow = PolicyManager.makeNewWindow(this);
4270 mWindow.setCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08004271 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4273 mWindow.setSoftInputMode(info.softInputMode);
4274 }
4275 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 mMainThread = aThread;
4278 mInstrumentation = instr;
4279 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004280 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 mApplication = application;
4282 mIntent = intent;
4283 mComponent = intent.getComponent();
4284 mActivityInfo = info;
4285 mTitle = title;
4286 mParent = parent;
4287 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004288 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289
Romain Guy529b60a2010-08-03 18:05:47 -07004290 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4291 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 if (mParent != null) {
4293 mWindow.setContainer(mParent.getWindow());
4294 }
4295 mWindowManager = mWindow.getWindowManager();
4296 mCurrentConfig = config;
4297 }
4298
4299 final IBinder getActivityToken() {
4300 return mParent != null ? mParent.getActivityToken() : mToken;
4301 }
4302
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004303 final void performCreate(Bundle icicle) {
4304 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004305 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4306 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004307 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004308 }
4309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004311 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004313 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 mInstrumentation.callActivityOnStart(this);
4315 if (!mCalled) {
4316 throw new SuperNotCalledException(
4317 "Activity " + mComponent.toShortString() +
4318 " did not call through to super.onStart()");
4319 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004320 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004321 if (mAllLoaderManagers != null) {
4322 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4323 mAllLoaderManagers.valueAt(i).finishRetain();
4324 }
4325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 }
4327
4328 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004329 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004330
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004331 synchronized (mManagedCursors) {
4332 final int N = mManagedCursors.size();
4333 for (int i=0; i<N; i++) {
4334 ManagedCursor mc = mManagedCursors.get(i);
4335 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004336 if (!mc.mCursor.requery()) {
4337 throw new IllegalStateException(
4338 "trying to requery an already closed cursor");
4339 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004340 mc.mReleased = false;
4341 mc.mUpdated = false;
4342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 }
4344 }
4345
4346 if (mStopped) {
4347 mStopped = false;
4348 mCalled = false;
4349 mInstrumentation.callActivityOnRestart(this);
4350 if (!mCalled) {
4351 throw new SuperNotCalledException(
4352 "Activity " + mComponent.toShortString() +
4353 " did not call through to super.onRestart()");
4354 }
4355 performStart();
4356 }
4357 }
4358
4359 final void performResume() {
4360 performRestart();
4361
Dianne Hackborn445646c2010-06-25 15:52:59 -07004362 mFragments.execPendingActions();
4363
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004364 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365
4366 // First call onResume() -before- setting mResumed, so we don't
4367 // send out any status bar / menu notifications the client makes.
4368 mCalled = false;
4369 mInstrumentation.callActivityOnResume(this);
4370 if (!mCalled) {
4371 throw new SuperNotCalledException(
4372 "Activity " + mComponent.toShortString() +
4373 " did not call through to super.onResume()");
4374 }
4375
4376 // Now really resume, and install the current status bar and menu.
4377 mResumed = true;
4378 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004379
4380 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004381 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 onPostResume();
4384 if (!mCalled) {
4385 throw new SuperNotCalledException(
4386 "Activity " + mComponent.toShortString() +
4387 " did not call through to super.onPostResume()");
4388 }
4389 }
4390
4391 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004392 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004393 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 onPause();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004395 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004396 if (!mCalled && getApplicationInfo().targetSdkVersion
4397 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4398 throw new SuperNotCalledException(
4399 "Activity " + mComponent.toShortString() +
4400 " did not call through to super.onPause()");
4401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
4403
4404 final void performUserLeaving() {
4405 onUserInteraction();
4406 onUserLeaveHint();
4407 }
4408
4409 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004410 if (mLoadersStarted) {
4411 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004412 if (mLoaderManager != null) {
4413 if (!mChangingConfigurations) {
4414 mLoaderManager.doStop();
4415 } else {
4416 mLoaderManager.doRetain();
4417 }
4418 }
4419 }
4420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 if (!mStopped) {
4422 if (mWindow != null) {
4423 mWindow.closeAllPanels();
4424 }
4425
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004426 mFragments.dispatchStop();
4427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 mCalled = false;
4429 mInstrumentation.callActivityOnStop(this);
4430 if (!mCalled) {
4431 throw new SuperNotCalledException(
4432 "Activity " + mComponent.toShortString() +
4433 " did not call through to super.onStop()");
4434 }
4435
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004436 synchronized (mManagedCursors) {
4437 final int N = mManagedCursors.size();
4438 for (int i=0; i<N; i++) {
4439 ManagedCursor mc = mManagedCursors.get(i);
4440 if (!mc.mReleased) {
4441 mc.mCursor.deactivate();
4442 mc.mReleased = true;
4443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 }
4445 }
4446
4447 mStopped = true;
4448 }
4449 mResumed = false;
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08004450
4451 // Check for Activity leaks, if enabled.
4452 StrictMode.conditionallyCheckInstanceCounts();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004455 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004456 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004457 mFragments.dispatchDestroy();
4458 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004459 if (mLoaderManager != null) {
4460 mLoaderManager.doDestroy();
4461 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004462 }
4463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 final boolean isResumed() {
4465 return mResumed;
4466 }
4467
4468 void dispatchActivityResult(String who, int requestCode,
4469 int resultCode, Intent data) {
4470 if (Config.LOGV) Log.v(
4471 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4472 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004473 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 if (who == null) {
4475 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004476 } else {
4477 Fragment frag = mFragments.findFragmentByWho(who);
4478 if (frag != null) {
4479 frag.onActivityResult(requestCode, resultCode, data);
4480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 }
4482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483}