blob: 3eef7855e27a90d19588331afcf4bde0b5ef255a [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.text.Selection;
49import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070050import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.text.method.TextKeyListener;
52import android.util.AttributeSet;
53import android.util.Config;
54import android.util.EventLog;
55import android.util.Log;
56import android.util.SparseArray;
Adam Powell6e346362010-07-23 10:18:23 -070057import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -070059import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.ContextThemeWrapper;
61import android.view.KeyEvent;
62import android.view.LayoutInflater;
63import android.view.Menu;
64import android.view.MenuInflater;
65import android.view.MenuItem;
66import android.view.MotionEvent;
67import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -070068import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -070070import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.view.ViewManager;
72import android.view.Window;
73import android.view.WindowManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070074import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.widget.AdapterView;
76
Dianne Hackborn625ac272010-09-17 18:29:22 -070077import java.io.FileDescriptor;
78import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070079import java.util.ArrayList;
80import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82/**
83 * An activity is a single, focused thing that the user can do. Almost all
84 * activities interact with the user, so the Activity class takes care of
85 * creating a window for you in which you can place your UI with
86 * {@link #setContentView}. While activities are often presented to the user
87 * as full-screen windows, they can also be used in other ways: as floating
88 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
89 * or embedded inside of another activity (using {@link ActivityGroup}).
90 *
91 * There are two methods almost all subclasses of Activity will implement:
92 *
93 * <ul>
94 * <li> {@link #onCreate} is where you initialize your activity. Most
95 * importantly, here you will usually call {@link #setContentView(int)}
96 * with a layout resource defining your UI, and using {@link #findViewById}
97 * to retrieve the widgets in that UI that you need to interact with
98 * programmatically.
99 *
100 * <li> {@link #onPause} is where you deal with the user leaving your
101 * activity. Most importantly, any changes made by the user should at this
102 * point be committed (usually to the
103 * {@link android.content.ContentProvider} holding the data).
104 * </ul>
105 *
106 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
107 * activity classes must have a corresponding
108 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
109 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
110 *
111 * <p>The Activity class is an important part of an application's overall lifecycle,
112 * and the way activities are launched and put together is a fundamental
113 * part of the platform's application model. For a detailed perspective on the structure of
114 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
115 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
116 *
117 * <p>Topics covered here:
118 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700119 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
121 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
122 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
123 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
124 * <li><a href="#Permissions">Permissions</a>
125 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
126 * </ol>
127 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700128 * <a name="Fragments"></a>
129 * <h3>Fragments</h3>
130 *
131 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
132 * implementations can make use of the {@link Fragment} class to better
133 * modularize their code, build more sophisticated user interfaces for larger
134 * screens, and help scale their application between small and large screens.
135 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 * <a name="ActivityLifecycle"></a>
137 * <h3>Activity Lifecycle</h3>
138 *
139 * <p>Activities in the system are managed as an <em>activity stack</em>.
140 * When a new activity is started, it is placed on the top of the stack
141 * and becomes the running activity -- the previous activity always remains
142 * below it in the stack, and will not come to the foreground again until
143 * the new activity exits.</p>
144 *
145 * <p>An activity has essentially four states:</p>
146 * <ul>
147 * <li> If an activity in the foreground of the screen (at the top of
148 * the stack),
149 * it is <em>active</em> or <em>running</em>. </li>
150 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
151 * or transparent activity has focus on top of your activity), it
152 * is <em>paused</em>. A paused activity is completely alive (it
153 * maintains all state and member information and remains attached to
154 * the window manager), but can be killed by the system in extreme
155 * low memory situations.
156 * <li>If an activity is completely obscured by another activity,
157 * it is <em>stopped</em>. It still retains all state and member information,
158 * however, it is no longer visible to the user so its window is hidden
159 * and it will often be killed by the system when memory is needed
160 * elsewhere.</li>
161 * <li>If an activity is paused or stopped, the system can drop the activity
162 * from memory by either asking it to finish, or simply killing its
163 * process. When it is displayed again to the user, it must be
164 * completely restarted and restored to its previous state.</li>
165 * </ul>
166 *
167 * <p>The following diagram shows the important state paths of an Activity.
168 * The square rectangles represent callback methods you can implement to
169 * perform operations when the Activity moves between states. The colored
170 * ovals are major states the Activity can be in.</p>
171 *
172 * <p><img src="../../../images/activity_lifecycle.png"
173 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
174 *
175 * <p>There are three key loops you may be interested in monitoring within your
176 * activity:
177 *
178 * <ul>
179 * <li>The <b>entire lifetime</b> of an activity happens between the first call
180 * to {@link android.app.Activity#onCreate} through to a single final call
181 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
182 * of "global" state in onCreate(), and release all remaining resources in
183 * onDestroy(). For example, if it has a thread running in the background
184 * to download data from the network, it may create that thread in onCreate()
185 * and then stop the thread in onDestroy().
186 *
187 * <li>The <b>visible lifetime</b> of an activity happens between a call to
188 * {@link android.app.Activity#onStart} until a corresponding call to
189 * {@link android.app.Activity#onStop}. During this time the user can see the
190 * activity on-screen, though it may not be in the foreground and interacting
191 * with the user. Between these two methods you can maintain resources that
192 * are needed to show the activity to the user. For example, you can register
193 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
194 * that impact your UI, and unregister it in onStop() when the user an no
195 * longer see what you are displaying. The onStart() and onStop() methods
196 * can be called multiple times, as the activity becomes visible and hidden
197 * to the user.
198 *
199 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
200 * {@link android.app.Activity#onResume} until a corresponding call to
201 * {@link android.app.Activity#onPause}. During this time the activity is
202 * in front of all other activities and interacting with the user. An activity
203 * can frequently go between the resumed and paused states -- for example when
204 * the device goes to sleep, when an activity result is delivered, when a new
205 * intent is delivered -- so the code in these methods should be fairly
206 * lightweight.
207 * </ul>
208 *
209 * <p>The entire lifecycle of an activity is defined by the following
210 * Activity methods. All of these are hooks that you can override
211 * to do appropriate work when the activity changes state. All
212 * activities will implement {@link android.app.Activity#onCreate}
213 * to do their initial setup; many will also implement
214 * {@link android.app.Activity#onPause} to commit changes to data and
215 * otherwise prepare to stop interacting with the user. You should always
216 * call up to your superclass when implementing these methods.</p>
217 *
218 * </p>
219 * <pre class="prettyprint">
220 * public class Activity extends ApplicationContext {
221 * protected void onCreate(Bundle savedInstanceState);
222 *
223 * protected void onStart();
224 *
225 * protected void onRestart();
226 *
227 * protected void onResume();
228 *
229 * protected void onPause();
230 *
231 * protected void onStop();
232 *
233 * protected void onDestroy();
234 * }
235 * </pre>
236 *
237 * <p>In general the movement through an activity's lifecycle looks like
238 * this:</p>
239 *
240 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
241 * <colgroup align="left" span="3" />
242 * <colgroup align="left" />
243 * <colgroup align="center" />
244 * <colgroup align="center" />
245 *
246 * <thead>
247 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
248 * </thead>
249 *
250 * <tbody>
251 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
252 * <td>Called when the activity is first created.
253 * This is where you should do all of your normal static set up:
254 * create views, bind data to lists, etc. This method also
255 * provides you with a Bundle containing the activity's previously
256 * frozen state, if there was one.
257 * <p>Always followed by <code>onStart()</code>.</td>
258 * <td align="center">No</td>
259 * <td align="center"><code>onStart()</code></td>
260 * </tr>
261 *
262 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
263 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
264 * <td>Called after your activity has been stopped, prior to it being
265 * started again.
266 * <p>Always followed by <code>onStart()</code></td>
267 * <td align="center">No</td>
268 * <td align="center"><code>onStart()</code></td>
269 * </tr>
270 *
271 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
272 * <td>Called when the activity is becoming visible to the user.
273 * <p>Followed by <code>onResume()</code> if the activity comes
274 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
275 * <td align="center">No</td>
276 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
277 * </tr>
278 *
279 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
280 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
281 * <td>Called when the activity will start
282 * interacting with the user. At this point your activity is at
283 * the top of the activity stack, with user input going to it.
284 * <p>Always followed by <code>onPause()</code>.</td>
285 * <td align="center">No</td>
286 * <td align="center"><code>onPause()</code></td>
287 * </tr>
288 *
289 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
290 * <td>Called when the system is about to start resuming a previous
291 * activity. This is typically used to commit unsaved changes to
292 * persistent data, stop animations and other things that may be consuming
293 * CPU, etc. Implementations of this method must be very quick because
294 * the next activity will not be resumed until this method returns.
295 * <p>Followed by either <code>onResume()</code> if the activity
296 * returns back to the front, or <code>onStop()</code> if it becomes
297 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800298 * <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 -0800299 * <td align="center"><code>onResume()</code> or<br>
300 * <code>onStop()</code></td>
301 * </tr>
302 *
303 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
304 * <td>Called when the activity is no longer visible to the user, because
305 * another activity has been resumed and is covering this one. This
306 * may happen either because a new activity is being started, an existing
307 * one is being brought in front of this one, or this one is being
308 * destroyed.
309 * <p>Followed by either <code>onRestart()</code> if
310 * this activity is coming back to interact with the user, or
311 * <code>onDestroy()</code> if this activity is going away.</td>
312 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
313 * <td align="center"><code>onRestart()</code> or<br>
314 * <code>onDestroy()</code></td>
315 * </tr>
316 *
317 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
318 * <td>The final call you receive before your
319 * activity is destroyed. This can happen either because the
320 * activity is finishing (someone called {@link Activity#finish} on
321 * it, or because the system is temporarily destroying this
322 * instance of the activity to save space. You can distinguish
323 * between these two scenarios with the {@link
324 * Activity#isFinishing} method.</td>
325 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
326 * <td align="center"><em>nothing</em></td>
327 * </tr>
328 * </tbody>
329 * </table>
330 *
331 * <p>Note the "Killable" column in the above table -- for those methods that
332 * are marked as being killable, after that method returns the process hosting the
333 * activity may killed by the system <em>at any time</em> without another line
334 * of its code being executed. Because of this, you should use the
335 * {@link #onPause} method to write any persistent data (such as user edits)
336 * to storage. In addition, the method
337 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
338 * in such a background state, allowing you to save away any dynamic instance
339 * state in your activity into the given Bundle, to be later received in
340 * {@link #onCreate} if the activity needs to be re-created.
341 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
342 * section for more information on how the lifecycle of a process is tied
343 * to the activities it is hosting. Note that it is important to save
344 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
345 * because the later is not part of the lifecycle callbacks, so will not
346 * be called in every situation as described in its documentation.</p>
347 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800348 * <p class="note">Be aware that these semantics will change slightly between
349 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
350 * vs. those targeting prior platforms. Starting with Honeycomb, an application
351 * is not in the killable state until its {@link #onStop} has returned. This
352 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
353 * safely called after {@link #onPause()} and allows and application to safely
354 * wait until {@link #onStop()} to save persistent state.</p>
355 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 * <p>For those methods that are not marked as being killable, the activity's
357 * process will not be killed by the system starting from the time the method
358 * is called and continuing after it returns. Thus an activity is in the killable
359 * state, for example, between after <code>onPause()</code> to the start of
360 * <code>onResume()</code>.</p>
361 *
362 * <a name="ConfigurationChanges"></a>
363 * <h3>Configuration Changes</h3>
364 *
365 * <p>If the configuration of the device (as defined by the
366 * {@link Configuration Resources.Configuration} class) changes,
367 * then anything displaying a user interface will need to update to match that
368 * configuration. Because Activity is the primary mechanism for interacting
369 * with the user, it includes special support for handling configuration
370 * changes.</p>
371 *
372 * <p>Unless you specify otherwise, a configuration change (such as a change
373 * in screen orientation, language, input devices, etc) will cause your
374 * current activity to be <em>destroyed</em>, going through the normal activity
375 * lifecycle process of {@link #onPause},
376 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
377 * had been in the foreground or visible to the user, once {@link #onDestroy} is
378 * called in that instance then a new instance of the activity will be
379 * created, with whatever savedInstanceState the previous instance had generated
380 * from {@link #onSaveInstanceState}.</p>
381 *
382 * <p>This is done because any application resource,
383 * including layout files, can change based on any configuration value. Thus
384 * the only safe way to handle a configuration change is to re-retrieve all
385 * resources, including layouts, drawables, and strings. Because activities
386 * must already know how to save their state and re-create themselves from
387 * that state, this is a convenient way to have an activity restart itself
388 * with a new configuration.</p>
389 *
390 * <p>In some special cases, you may want to bypass restarting of your
391 * activity based on one or more types of configuration changes. This is
392 * done with the {@link android.R.attr#configChanges android:configChanges}
393 * attribute in its manifest. For any types of configuration changes you say
394 * that you handle there, you will receive a call to your current activity's
395 * {@link #onConfigurationChanged} method instead of being restarted. If
396 * a configuration change involves any that you do not handle, however, the
397 * activity will still be restarted and {@link #onConfigurationChanged}
398 * will not be called.</p>
399 *
400 * <a name="StartingActivities"></a>
401 * <h3>Starting Activities and Getting Results</h3>
402 *
403 * <p>The {@link android.app.Activity#startActivity}
404 * method is used to start a
405 * new activity, which will be placed at the top of the activity stack. It
406 * takes a single argument, an {@link android.content.Intent Intent},
407 * which describes the activity
408 * to be executed.</p>
409 *
410 * <p>Sometimes you want to get a result back from an activity when it
411 * ends. For example, you may start an activity that lets the user pick
412 * a person in a list of contacts; when it ends, it returns the person
413 * that was selected. To do this, you call the
414 * {@link android.app.Activity#startActivityForResult(Intent, int)}
415 * version with a second integer parameter identifying the call. The result
416 * will come back through your {@link android.app.Activity#onActivityResult}
417 * method.</p>
418 *
419 * <p>When an activity exits, it can call
420 * {@link android.app.Activity#setResult(int)}
421 * to return data back to its parent. It must always supply a result code,
422 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
423 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
424 * return back an Intent containing any additional data it wants. All of this
425 * information appears back on the
426 * parent's <code>Activity.onActivityResult()</code>, along with the integer
427 * identifier it originally supplied.</p>
428 *
429 * <p>If a child activity fails for any reason (such as crashing), the parent
430 * activity will receive a result with the code RESULT_CANCELED.</p>
431 *
432 * <pre class="prettyprint">
433 * public class MyActivity extends Activity {
434 * ...
435 *
436 * static final int PICK_CONTACT_REQUEST = 0;
437 *
438 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
439 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
440 * // When the user center presses, let them pick a contact.
441 * startActivityForResult(
442 * new Intent(Intent.ACTION_PICK,
443 * new Uri("content://contacts")),
444 * PICK_CONTACT_REQUEST);
445 * return true;
446 * }
447 * return false;
448 * }
449 *
450 * protected void onActivityResult(int requestCode, int resultCode,
451 * Intent data) {
452 * if (requestCode == PICK_CONTACT_REQUEST) {
453 * if (resultCode == RESULT_OK) {
454 * // A contact was picked. Here we will just display it
455 * // to the user.
456 * startActivity(new Intent(Intent.ACTION_VIEW, data));
457 * }
458 * }
459 * }
460 * }
461 * </pre>
462 *
463 * <a name="SavingPersistentState"></a>
464 * <h3>Saving Persistent State</h3>
465 *
466 * <p>There are generally two kinds of persistent state than an activity
467 * will deal with: shared document-like data (typically stored in a SQLite
468 * database using a {@linkplain android.content.ContentProvider content provider})
469 * and internal state such as user preferences.</p>
470 *
471 * <p>For content provider data, we suggest that activities use a
472 * "edit in place" user model. That is, any edits a user makes are effectively
473 * made immediately without requiring an additional confirmation step.
474 * Supporting this model is generally a simple matter of following two rules:</p>
475 *
476 * <ul>
477 * <li> <p>When creating a new document, the backing database entry or file for
478 * it is created immediately. For example, if the user chooses to write
479 * a new e-mail, a new entry for that e-mail is created as soon as they
480 * start entering data, so that if they go to any other activity after
481 * that point this e-mail will now appear in the list of drafts.</p>
482 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
483 * commit to the backing content provider or file any changes the user
484 * has made. This ensures that those changes will be seen by any other
485 * activity that is about to run. You will probably want to commit
486 * your data even more aggressively at key times during your
487 * activity's lifecycle: for example before starting a new
488 * activity, before finishing your own activity, when the user
489 * switches between input fields, etc.</p>
490 * </ul>
491 *
492 * <p>This model is designed to prevent data loss when a user is navigating
493 * between activities, and allows the system to safely kill an activity (because
494 * system resources are needed somewhere else) at any time after it has been
495 * paused. Note this implies
496 * that the user pressing BACK from your activity does <em>not</em>
497 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800498 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
500 *
501 * <p>See the {@linkplain android.content.ContentProvider content package} for
502 * more information about content providers. These are a key aspect of how
503 * different activities invoke and propagate data between themselves.</p>
504 *
505 * <p>The Activity class also provides an API for managing internal persistent state
506 * associated with an activity. This can be used, for example, to remember
507 * the user's preferred initial display in a calendar (day view or week view)
508 * or the user's default home page in a web browser.</p>
509 *
510 * <p>Activity persistent state is managed
511 * with the method {@link #getPreferences},
512 * allowing you to retrieve and
513 * modify a set of name/value pairs associated with the activity. To use
514 * preferences that are shared across multiple application components
515 * (activities, receivers, services, providers), you can use the underlying
516 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
517 * to retrieve a preferences
518 * object stored under a specific name.
519 * (Note that it is not possible to share settings data across application
520 * packages -- for that you will need a content provider.)</p>
521 *
522 * <p>Here is an excerpt from a calendar activity that stores the user's
523 * preferred view mode in its persistent settings:</p>
524 *
525 * <pre class="prettyprint">
526 * public class CalendarActivity extends Activity {
527 * ...
528 *
529 * static final int DAY_VIEW_MODE = 0;
530 * static final int WEEK_VIEW_MODE = 1;
531 *
532 * private SharedPreferences mPrefs;
533 * private int mCurViewMode;
534 *
535 * protected void onCreate(Bundle savedInstanceState) {
536 * super.onCreate(savedInstanceState);
537 *
538 * SharedPreferences mPrefs = getSharedPreferences();
539 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
540 * }
541 *
542 * protected void onPause() {
543 * super.onPause();
544 *
545 * SharedPreferences.Editor ed = mPrefs.edit();
546 * ed.putInt("view_mode", mCurViewMode);
547 * ed.commit();
548 * }
549 * }
550 * </pre>
551 *
552 * <a name="Permissions"></a>
553 * <h3>Permissions</h3>
554 *
555 * <p>The ability to start a particular Activity can be enforced when it is
556 * declared in its
557 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
558 * tag. By doing so, other applications will need to declare a corresponding
559 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
560 * element in their own manifest to be able to start that activity.
561 *
562 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
563 * document for more information on permissions and security in general.
564 *
565 * <a name="ProcessLifecycle"></a>
566 * <h3>Process Lifecycle</h3>
567 *
568 * <p>The Android system attempts to keep application process around for as
569 * long as possible, but eventually will need to remove old processes when
570 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
571 * Lifecycle</a>, the decision about which process to remove is intimately
572 * tied to the state of the user's interaction with it. In general, there
573 * are four states a process can be in based on the activities running in it,
574 * listed here in order of importance. The system will kill less important
575 * processes (the last ones) before it resorts to killing more important
576 * processes (the first ones).
577 *
578 * <ol>
579 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
580 * that the user is currently interacting with) is considered the most important.
581 * Its process will only be killed as a last resort, if it uses more memory
582 * than is available on the device. Generally at this point the device has
583 * reached a memory paging state, so this is required in order to keep the user
584 * interface responsive.
585 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
586 * but not in the foreground, such as one sitting behind a foreground dialog)
587 * is considered extremely important and will not be killed unless that is
588 * required to keep the foreground activity running.
589 * <li> <p>A <b>background activity</b> (an activity that is not visible to
590 * the user and has been paused) is no longer critical, so the system may
591 * safely kill its process to reclaim memory for other foreground or
592 * visible processes. If its process needs to be killed, when the user navigates
593 * back to the activity (making it visible on the screen again), its
594 * {@link #onCreate} method will be called with the savedInstanceState it had previously
595 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
596 * state as the user last left it.
597 * <li> <p>An <b>empty process</b> is one hosting no activities or other
598 * application components (such as {@link Service} or
599 * {@link android.content.BroadcastReceiver} classes). These are killed very
600 * quickly by the system as memory becomes low. For this reason, any
601 * background operation you do outside of an activity must be executed in the
602 * context of an activity BroadcastReceiver or Service to ensure that the system
603 * knows it needs to keep your process around.
604 * </ol>
605 *
606 * <p>Sometimes an Activity may need to do a long-running operation that exists
607 * independently of the activity lifecycle itself. An example may be a camera
608 * application that allows you to upload a picture to a web site. The upload
609 * may take a long time, and the application should allow the user to leave
610 * the application will it is executing. To accomplish this, your Activity
611 * should start a {@link Service} in which the upload takes place. This allows
612 * the system to properly prioritize your process (considering it to be more
613 * important than other non-visible applications) for the duration of the
614 * upload, independent of whether the original activity is paused, stopped,
615 * or finished.
616 */
617public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700618 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 Window.Callback, KeyEvent.Callback,
620 OnCreateContextMenuListener, ComponentCallbacks {
621 private static final String TAG = "Activity";
622
623 /** Standard activity result: operation canceled. */
624 public static final int RESULT_CANCELED = 0;
625 /** Standard activity result: operation succeeded. */
626 public static final int RESULT_OK = -1;
627 /** Start of user-defined activity results. */
628 public static final int RESULT_FIRST_USER = 1;
629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700631 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
633 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
634 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800635 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800637 private static class ManagedDialog {
638 Dialog mDialog;
639 Bundle mArgs;
640 }
641 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642
643 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
644 private Instrumentation mInstrumentation;
645 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700646 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 /*package*/ String mEmbeddedID;
648 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700649 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 private ComponentName mComponent;
651 /*package*/ ActivityInfo mActivityInfo;
652 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 Activity mParent;
654 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700655 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700656 boolean mLoadersStarted;
Jeff Hamilton52d32032011-01-08 15:31:26 -0600657 /*package*/ boolean mResumed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 private boolean mStopped;
659 boolean mFinished;
660 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700661 /** true if the activity is going through a transient pause */
662 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500663 /** true if the activity is being destroyed in order to recreate it with a new configuration */
664 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 /*package*/ int mConfigChangeFlags;
666 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100667 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700669 static final class NonConfigurationInstances {
670 Object activity;
671 HashMap<String, Object> children;
672 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700673 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700674 }
675 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 private Window mWindow;
678
679 private WindowManager mWindowManager;
680 /*package*/ View mDecor = null;
681 /*package*/ boolean mWindowAdded = false;
682 /*package*/ boolean mVisibleFromServer = false;
683 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700684 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
686 private CharSequence mTitle;
687 private int mTitleColor = 0;
688
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700689 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700690
Dianne Hackborn4911b782010-07-15 12:54:39 -0700691 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
692 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 private static final class ManagedCursor {
695 ManagedCursor(Cursor cursor) {
696 mCursor = cursor;
697 mReleased = false;
698 mUpdated = false;
699 }
700
701 private final Cursor mCursor;
702 private boolean mReleased;
703 private boolean mUpdated;
704 }
705 private final ArrayList<ManagedCursor> mManagedCursors =
706 new ArrayList<ManagedCursor>();
707
708 // protected by synchronized (this)
709 int mResultCode = RESULT_CANCELED;
710 Intent mResultData = null;
711
712 private boolean mTitleReady = false;
713
714 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
715 private SpannableStringBuilder mDefaultKeySsb = null;
716
717 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
718
719 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700720 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 /** Return the intent that started this activity. */
723 public Intent getIntent() {
724 return mIntent;
725 }
726
727 /**
728 * Change the intent returned by {@link #getIntent}. This holds a
729 * reference to the given intent; it does not copy it. Often used in
730 * conjunction with {@link #onNewIntent}.
731 *
732 * @param newIntent The new Intent object to return from getIntent
733 *
734 * @see #getIntent
735 * @see #onNewIntent
736 */
737 public void setIntent(Intent newIntent) {
738 mIntent = newIntent;
739 }
740
741 /** Return the application that owns this activity. */
742 public final Application getApplication() {
743 return mApplication;
744 }
745
746 /** Is this activity embedded inside of another activity? */
747 public final boolean isChild() {
748 return mParent != null;
749 }
750
751 /** Return the parent activity if this view is an embedded child. */
752 public final Activity getParent() {
753 return mParent;
754 }
755
756 /** Retrieve the window manager for showing custom windows. */
757 public WindowManager getWindowManager() {
758 return mWindowManager;
759 }
760
761 /**
762 * Retrieve the current {@link android.view.Window} for the activity.
763 * This can be used to directly access parts of the Window API that
764 * are not available through Activity/Screen.
765 *
766 * @return Window The current window, or null if the activity is not
767 * visual.
768 */
769 public Window getWindow() {
770 return mWindow;
771 }
772
773 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700774 * Return the LoaderManager for this fragment, creating it if needed.
775 */
776 public LoaderManager getLoaderManager() {
777 if (mLoaderManager != null) {
778 return mLoaderManager;
779 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700780 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700781 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700782 return mLoaderManager;
783 }
784
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700785 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700786 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700787 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700788 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700789 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700790 if (lm == null) {
791 if (create) {
792 lm = new LoaderManagerImpl(this, started);
793 mAllLoaderManagers.put(index, lm);
794 }
795 } else {
796 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700797 }
798 return lm;
799 }
800
801 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 * Calls {@link android.view.Window#getCurrentFocus} on the
803 * Window of this Activity to return the currently focused view.
804 *
805 * @return View The current View with focus or null.
806 *
807 * @see #getWindow
808 * @see android.view.Window#getCurrentFocus
809 */
810 public View getCurrentFocus() {
811 return mWindow != null ? mWindow.getCurrentFocus() : null;
812 }
813
814 @Override
815 public int getWallpaperDesiredMinimumWidth() {
816 int width = super.getWallpaperDesiredMinimumWidth();
817 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
818 }
819
820 @Override
821 public int getWallpaperDesiredMinimumHeight() {
822 int height = super.getWallpaperDesiredMinimumHeight();
823 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
824 }
825
826 /**
827 * Called when the activity is starting. This is where most initialization
828 * should go: calling {@link #setContentView(int)} to inflate the
829 * activity's UI, using {@link #findViewById} to programmatically interact
830 * with widgets in the UI, calling
831 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
832 * cursors for data being displayed, etc.
833 *
834 * <p>You can call {@link #finish} from within this function, in
835 * which case onDestroy() will be immediately called without any of the rest
836 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
837 * {@link #onPause}, etc) executing.
838 *
839 * <p><em>Derived classes must call through to the super class's
840 * implementation of this method. If they do not, an exception will be
841 * thrown.</em></p>
842 *
843 * @param savedInstanceState If the activity is being re-initialized after
844 * previously being shut down then this Bundle contains the data it most
845 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
846 *
847 * @see #onStart
848 * @see #onSaveInstanceState
849 * @see #onRestoreInstanceState
850 * @see #onPostCreate
851 */
852 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700853 if (mLastNonConfigurationInstances != null) {
854 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
855 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700856 if (savedInstanceState != null) {
857 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
858 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
859 ? mLastNonConfigurationInstances.fragments : null);
860 }
861 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 mCalled = true;
863 }
864
865 /**
866 * The hook for {@link ActivityThread} to restore the state of this activity.
867 *
868 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
869 * {@link #restoreManagedDialogs(android.os.Bundle)}.
870 *
871 * @param savedInstanceState contains the saved state
872 */
873 final void performRestoreInstanceState(Bundle savedInstanceState) {
874 onRestoreInstanceState(savedInstanceState);
875 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877
878 /**
879 * This method is called after {@link #onStart} when the activity is
880 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800881 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 * to restore their state, but it is sometimes convenient to do it here
883 * after all of the initialization has been done or to allow subclasses to
884 * decide whether to use your default implementation. The default
885 * implementation of this method performs a restore of any view state that
886 * had previously been frozen by {@link #onSaveInstanceState}.
887 *
888 * <p>This method is called between {@link #onStart} and
889 * {@link #onPostCreate}.
890 *
891 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
892 *
893 * @see #onCreate
894 * @see #onPostCreate
895 * @see #onResume
896 * @see #onSaveInstanceState
897 */
898 protected void onRestoreInstanceState(Bundle savedInstanceState) {
899 if (mWindow != null) {
900 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
901 if (windowState != null) {
902 mWindow.restoreHierarchyState(windowState);
903 }
904 }
905 }
906
907 /**
908 * Restore the state of any saved managed dialogs.
909 *
910 * @param savedInstanceState The bundle to restore from.
911 */
912 private void restoreManagedDialogs(Bundle savedInstanceState) {
913 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
914 if (b == null) {
915 return;
916 }
917
918 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
919 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800920 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 for (int i = 0; i < numDialogs; i++) {
922 final Integer dialogId = ids[i];
923 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
924 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700925 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
926 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800927 final ManagedDialog md = new ManagedDialog();
928 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
929 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
930 if (md.mDialog != null) {
931 mManagedDialogs.put(dialogId, md);
932 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
933 md.mDialog.onRestoreInstanceState(dialogState);
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 }
937 }
938
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800939 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
940 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700941 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800942 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700943 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700944 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700945 return dialog;
946 }
947
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800948 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 return SAVED_DIALOG_KEY_PREFIX + key;
950 }
951
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800952 private static String savedDialogArgsKeyFor(int key) {
953 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955
956 /**
957 * Called when activity start-up is complete (after {@link #onStart}
958 * and {@link #onRestoreInstanceState} have been called). Applications will
959 * generally not implement this method; it is intended for system
960 * classes to do final initialization after application code has run.
961 *
962 * <p><em>Derived classes must call through to the super class's
963 * implementation of this method. If they do not, an exception will be
964 * thrown.</em></p>
965 *
966 * @param savedInstanceState If the activity is being re-initialized after
967 * previously being shut down then this Bundle contains the data it most
968 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
969 * @see #onCreate
970 */
971 protected void onPostCreate(Bundle savedInstanceState) {
972 if (!isChild()) {
973 mTitleReady = true;
974 onTitleChanged(getTitle(), getTitleColor());
975 }
976 mCalled = true;
977 }
978
979 /**
980 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
981 * the activity had been stopped, but is now again being displayed to the
982 * user. It will be followed by {@link #onResume}.
983 *
984 * <p><em>Derived classes must call through to the super class's
985 * implementation of this method. If they do not, an exception will be
986 * thrown.</em></p>
987 *
988 * @see #onCreate
989 * @see #onStop
990 * @see #onResume
991 */
992 protected void onStart() {
993 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700994
995 if (!mLoadersStarted) {
996 mLoadersStarted = true;
997 if (mLoaderManager != null) {
998 mLoaderManager.doStart();
999 } else if (!mCheckedForLoaderManager) {
1000 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
1001 }
1002 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
1005
1006 /**
1007 * Called after {@link #onStop} when the current activity is being
1008 * re-displayed to the user (the user has navigated back to it). It will
1009 * be followed by {@link #onStart} and then {@link #onResume}.
1010 *
1011 * <p>For activities that are using raw {@link Cursor} objects (instead of
1012 * creating them through
1013 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1014 * this is usually the place
1015 * where the cursor should be requeried (because you had deactivated it in
1016 * {@link #onStop}.
1017 *
1018 * <p><em>Derived classes must call through to the super class's
1019 * implementation of this method. If they do not, an exception will be
1020 * thrown.</em></p>
1021 *
1022 * @see #onStop
1023 * @see #onStart
1024 * @see #onResume
1025 */
1026 protected void onRestart() {
1027 mCalled = true;
1028 }
1029
1030 /**
1031 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1032 * {@link #onPause}, for your activity to start interacting with the user.
1033 * This is a good place to begin animations, open exclusive-access devices
1034 * (such as the camera), etc.
1035 *
1036 * <p>Keep in mind that onResume is not the best indicator that your activity
1037 * is visible to the user; a system window such as the keyguard may be in
1038 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1039 * activity is visible to the user (for example, to resume a game).
1040 *
1041 * <p><em>Derived classes must call through to the super class's
1042 * implementation of this method. If they do not, an exception will be
1043 * thrown.</em></p>
1044 *
1045 * @see #onRestoreInstanceState
1046 * @see #onRestart
1047 * @see #onPostResume
1048 * @see #onPause
1049 */
1050 protected void onResume() {
1051 mCalled = true;
1052 }
1053
1054 /**
1055 * Called when activity resume is complete (after {@link #onResume} has
1056 * been called). Applications will generally not implement this method;
1057 * it is intended for system classes to do final setup after application
1058 * resume code has run.
1059 *
1060 * <p><em>Derived classes must call through to the super class's
1061 * implementation of this method. If they do not, an exception will be
1062 * thrown.</em></p>
1063 *
1064 * @see #onResume
1065 */
1066 protected void onPostResume() {
1067 final Window win = getWindow();
1068 if (win != null) win.makeActive();
1069 mCalled = true;
1070 }
1071
1072 /**
1073 * This is called for activities that set launchMode to "singleTop" in
1074 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1075 * flag when calling {@link #startActivity}. In either case, when the
1076 * activity is re-launched while at the top of the activity stack instead
1077 * of a new instance of the activity being started, onNewIntent() will be
1078 * called on the existing instance with the Intent that was used to
1079 * re-launch it.
1080 *
1081 * <p>An activity will always be paused before receiving a new intent, so
1082 * you can count on {@link #onResume} being called after this method.
1083 *
1084 * <p>Note that {@link #getIntent} still returns the original Intent. You
1085 * can use {@link #setIntent} to update it to this new Intent.
1086 *
1087 * @param intent The new intent that was started for the activity.
1088 *
1089 * @see #getIntent
1090 * @see #setIntent
1091 * @see #onResume
1092 */
1093 protected void onNewIntent(Intent intent) {
1094 }
1095
1096 /**
1097 * The hook for {@link ActivityThread} to save the state of this activity.
1098 *
1099 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1100 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1101 *
1102 * @param outState The bundle to save the state to.
1103 */
1104 final void performSaveInstanceState(Bundle outState) {
1105 onSaveInstanceState(outState);
1106 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108
1109 /**
1110 * Called to retrieve per-instance state from an activity before being killed
1111 * so that the state can be restored in {@link #onCreate} or
1112 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1113 * will be passed to both).
1114 *
1115 * <p>This method is called before an activity may be killed so that when it
1116 * comes back some time in the future it can restore its state. For example,
1117 * if activity B is launched in front of activity A, and at some point activity
1118 * A is killed to reclaim resources, activity A will have a chance to save the
1119 * current state of its user interface via this method so that when the user
1120 * returns to activity A, the state of the user interface can be restored
1121 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1122 *
1123 * <p>Do not confuse this method with activity lifecycle callbacks such as
1124 * {@link #onPause}, which is always called when an activity is being placed
1125 * in the background or on its way to destruction, or {@link #onStop} which
1126 * is called before destruction. One example of when {@link #onPause} and
1127 * {@link #onStop} is called and not this method is when a user navigates back
1128 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1129 * on B because that particular instance will never be restored, so the
1130 * system avoids calling it. An example when {@link #onPause} is called and
1131 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1132 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1133 * killed during the lifetime of B since the state of the user interface of
1134 * A will stay intact.
1135 *
1136 * <p>The default implementation takes care of most of the UI per-instance
1137 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1138 * view in the hierarchy that has an id, and by saving the id of the currently
1139 * focused view (all of which is restored by the default implementation of
1140 * {@link #onRestoreInstanceState}). If you override this method to save additional
1141 * information not captured by each individual view, you will likely want to
1142 * call through to the default implementation, otherwise be prepared to save
1143 * all of the state of each view yourself.
1144 *
1145 * <p>If called, this method will occur before {@link #onStop}. There are
1146 * no guarantees about whether it will occur before or after {@link #onPause}.
1147 *
1148 * @param outState Bundle in which to place your saved state.
1149 *
1150 * @see #onCreate
1151 * @see #onRestoreInstanceState
1152 * @see #onPause
1153 */
1154 protected void onSaveInstanceState(Bundle outState) {
1155 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001156 Parcelable p = mFragments.saveAllState();
1157 if (p != null) {
1158 outState.putParcelable(FRAGMENTS_TAG, p);
1159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
1162 /**
1163 * Save the state of any managed dialogs.
1164 *
1165 * @param outState place to store the saved state.
1166 */
1167 private void saveManagedDialogs(Bundle outState) {
1168 if (mManagedDialogs == null) {
1169 return;
1170 }
1171
1172 final int numDialogs = mManagedDialogs.size();
1173 if (numDialogs == 0) {
1174 return;
1175 }
1176
1177 Bundle dialogState = new Bundle();
1178
1179 int[] ids = new int[mManagedDialogs.size()];
1180
1181 // save each dialog's bundle, gather the ids
1182 for (int i = 0; i < numDialogs; i++) {
1183 final int key = mManagedDialogs.keyAt(i);
1184 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001185 final ManagedDialog md = mManagedDialogs.valueAt(i);
1186 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1187 if (md.mArgs != null) {
1188 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
1191
1192 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1193 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1194 }
1195
1196
1197 /**
1198 * Called as part of the activity lifecycle when an activity is going into
1199 * the background, but has not (yet) been killed. The counterpart to
1200 * {@link #onResume}.
1201 *
1202 * <p>When activity B is launched in front of activity A, this callback will
1203 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1204 * so be sure to not do anything lengthy here.
1205 *
1206 * <p>This callback is mostly used for saving any persistent state the
1207 * activity is editing, to present a "edit in place" model to the user and
1208 * making sure nothing is lost if there are not enough resources to start
1209 * the new activity without first killing this one. This is also a good
1210 * place to do things like stop animations and other things that consume a
1211 * noticeable mount of CPU in order to make the switch to the next activity
1212 * as fast as possible, or to close resources that are exclusive access
1213 * such as the camera.
1214 *
1215 * <p>In situations where the system needs more memory it may kill paused
1216 * processes to reclaim resources. Because of this, you should be sure
1217 * that all of your state is saved by the time you return from
1218 * this function. In general {@link #onSaveInstanceState} is used to save
1219 * per-instance state in the activity and this method is used to store
1220 * global persistent data (in content providers, files, etc.)
1221 *
1222 * <p>After receiving this call you will usually receive a following call
1223 * to {@link #onStop} (after the next activity has been resumed and
1224 * displayed), however in some cases there will be a direct call back to
1225 * {@link #onResume} without going through the stopped state.
1226 *
1227 * <p><em>Derived classes must call through to the super class's
1228 * implementation of this method. If they do not, an exception will be
1229 * thrown.</em></p>
1230 *
1231 * @see #onResume
1232 * @see #onSaveInstanceState
1233 * @see #onStop
1234 */
1235 protected void onPause() {
1236 mCalled = true;
1237 }
1238
1239 /**
1240 * Called as part of the activity lifecycle when an activity is about to go
1241 * into the background as the result of user choice. For example, when the
1242 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1243 * when an incoming phone call causes the in-call Activity to be automatically
1244 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1245 * the activity being interrupted. In cases when it is invoked, this method
1246 * is called right before the activity's {@link #onPause} callback.
1247 *
1248 * <p>This callback and {@link #onUserInteraction} are intended to help
1249 * activities manage status bar notifications intelligently; specifically,
1250 * for helping activities determine the proper time to cancel a notfication.
1251 *
1252 * @see #onUserInteraction()
1253 */
1254 protected void onUserLeaveHint() {
1255 }
1256
1257 /**
1258 * Generate a new thumbnail for this activity. This method is called before
1259 * pausing the activity, and should draw into <var>outBitmap</var> the
1260 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1261 * can use the given <var>canvas</var>, which is configured to draw into the
1262 * bitmap, for rendering if desired.
1263 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001264 * <p>The default implementation returns fails and does not draw a thumbnail;
1265 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 *
1267 * @param outBitmap The bitmap to contain the thumbnail.
1268 * @param canvas Can be used to render into the bitmap.
1269 *
1270 * @return Return true if you have drawn into the bitmap; otherwise after
1271 * you return it will be filled with a default thumbnail.
1272 *
1273 * @see #onCreateDescription
1274 * @see #onSaveInstanceState
1275 * @see #onPause
1276 */
1277 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001278 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280
1281 /**
1282 * Generate a new description for this activity. This method is called
1283 * before pausing the activity and can, if desired, return some textual
1284 * description of its current state to be displayed to the user.
1285 *
1286 * <p>The default implementation returns null, which will cause you to
1287 * inherit the description from the previous activity. If all activities
1288 * return null, generally the label of the top activity will be used as the
1289 * description.
1290 *
1291 * @return A description of what the user is doing. It should be short and
1292 * sweet (only a few words).
1293 *
1294 * @see #onCreateThumbnail
1295 * @see #onSaveInstanceState
1296 * @see #onPause
1297 */
1298 public CharSequence onCreateDescription() {
1299 return null;
1300 }
1301
1302 /**
1303 * Called when you are no longer visible to the user. You will next
1304 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1305 * depending on later user activity.
1306 *
1307 * <p>Note that this method may never be called, in low memory situations
1308 * where the system does not have enough memory to keep your activity's
1309 * process running after its {@link #onPause} method is called.
1310 *
1311 * <p><em>Derived classes must call through to the super class's
1312 * implementation of this method. If they do not, an exception will be
1313 * thrown.</em></p>
1314 *
1315 * @see #onRestart
1316 * @see #onResume
1317 * @see #onSaveInstanceState
1318 * @see #onDestroy
1319 */
1320 protected void onStop() {
1321 mCalled = true;
1322 }
1323
1324 /**
1325 * Perform any final cleanup before an activity is destroyed. This can
1326 * happen either because the activity is finishing (someone called
1327 * {@link #finish} on it, or because the system is temporarily destroying
1328 * this instance of the activity to save space. You can distinguish
1329 * between these two scenarios with the {@link #isFinishing} method.
1330 *
1331 * <p><em>Note: do not count on this method being called as a place for
1332 * saving data! For example, if an activity is editing data in a content
1333 * provider, those edits should be committed in either {@link #onPause} or
1334 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1335 * free resources like threads that are associated with an activity, so
1336 * that a destroyed activity does not leave such things around while the
1337 * rest of its application is still running. There are situations where
1338 * the system will simply kill the activity's hosting process without
1339 * calling this method (or any others) in it, so it should not be used to
1340 * do things that are intended to remain around after the process goes
1341 * away.
1342 *
1343 * <p><em>Derived classes must call through to the super class's
1344 * implementation of this method. If they do not, an exception will be
1345 * thrown.</em></p>
1346 *
1347 * @see #onPause
1348 * @see #onStop
1349 * @see #finish
1350 * @see #isFinishing
1351 */
1352 protected void onDestroy() {
1353 mCalled = true;
1354
1355 // dismiss any dialogs we are managing.
1356 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 final int numDialogs = mManagedDialogs.size();
1358 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001359 final ManagedDialog md = mManagedDialogs.valueAt(i);
1360 if (md.mDialog.isShowing()) {
1361 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001364 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
1367 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001368 synchronized (mManagedCursors) {
1369 int numCursors = mManagedCursors.size();
1370 for (int i = 0; i < numCursors; i++) {
1371 ManagedCursor c = mManagedCursors.get(i);
1372 if (c != null) {
1373 c.mCursor.close();
1374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001376 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
Amith Yamasani49860442010-03-17 20:54:10 -07001378
1379 // Close any open search dialog
1380 if (mSearchManager != null) {
1381 mSearchManager.stopSearch();
1382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
1385 /**
1386 * Called by the system when the device configuration changes while your
1387 * activity is running. Note that this will <em>only</em> be called if
1388 * you have selected configurations you would like to handle with the
1389 * {@link android.R.attr#configChanges} attribute in your manifest. If
1390 * any configuration change occurs that is not selected to be reported
1391 * by that attribute, then instead of reporting it the system will stop
1392 * and restart the activity (to have it launched with the new
1393 * configuration).
1394 *
1395 * <p>At the time that this function has been called, your Resources
1396 * object will have been updated to return resource values matching the
1397 * new configuration.
1398 *
1399 * @param newConfig The new device configuration.
1400 */
1401 public void onConfigurationChanged(Configuration newConfig) {
1402 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001403
Dianne Hackborn9d071802010-12-08 14:49:15 -08001404 mFragments.dispatchConfigurationChanged(newConfig);
1405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 if (mWindow != null) {
1407 // Pass the configuration changed event to the window
1408 mWindow.onConfigurationChanged(newConfig);
1409 }
1410 }
1411
1412 /**
1413 * If this activity is being destroyed because it can not handle a
1414 * configuration parameter being changed (and thus its
1415 * {@link #onConfigurationChanged(Configuration)} method is
1416 * <em>not</em> being called), then you can use this method to discover
1417 * the set of changes that have occurred while in the process of being
1418 * destroyed. Note that there is no guarantee that these will be
1419 * accurate (other changes could have happened at any time), so you should
1420 * only use this as an optimization hint.
1421 *
1422 * @return Returns a bit field of the configuration parameters that are
1423 * changing, as defined by the {@link android.content.res.Configuration}
1424 * class.
1425 */
1426 public int getChangingConfigurations() {
1427 return mConfigChangeFlags;
1428 }
1429
1430 /**
1431 * Retrieve the non-configuration instance data that was previously
1432 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1433 * be available from the initial {@link #onCreate} and
1434 * {@link #onStart} calls to the new instance, allowing you to extract
1435 * any useful dynamic state from the previous instance.
1436 *
1437 * <p>Note that the data you retrieve here should <em>only</em> be used
1438 * as an optimization for handling configuration changes. You should always
1439 * be able to handle getting a null pointer back, and an activity must
1440 * still be able to restore itself to its previous state (through the
1441 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1442 * function returns null.
1443 *
1444 * @return Returns the object previously returned by
1445 * {@link #onRetainNonConfigurationInstance()}.
1446 */
1447 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001448 return mLastNonConfigurationInstances != null
1449 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
1451
1452 /**
1453 * Called by the system, as part of destroying an
1454 * activity due to a configuration change, when it is known that a new
1455 * instance will immediately be created for the new configuration. You
1456 * can return any object you like here, including the activity instance
1457 * itself, which can later be retrieved by calling
1458 * {@link #getLastNonConfigurationInstance()} in the new activity
1459 * instance.
1460 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001461 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1462 * or later, consider instead using a {@link Fragment} with
1463 * {@link Fragment#setRetainInstance(boolean)
1464 * Fragment.setRetainInstance(boolean}.</em>
1465 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 * <p>This function is called purely as an optimization, and you must
1467 * not rely on it being called. When it is called, a number of guarantees
1468 * will be made to help optimize configuration switching:
1469 * <ul>
1470 * <li> The function will be called between {@link #onStop} and
1471 * {@link #onDestroy}.
1472 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001473 * created after this one's {@link #onDestroy()} is called. In particular,
1474 * <em>no</em> messages will be dispatched during this time (when the returned
1475 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 * <li> The object you return here will <em>always</em> be available from
1477 * the {@link #getLastNonConfigurationInstance()} method of the following
1478 * activity instance as described there.
1479 * </ul>
1480 *
1481 * <p>These guarantees are designed so that an activity can use this API
1482 * to propagate extensive state from the old to new activity instance, from
1483 * loaded bitmaps, to network connections, to evenly actively running
1484 * threads. Note that you should <em>not</em> propagate any data that
1485 * may change based on the configuration, including any data loaded from
1486 * resources such as strings, layouts, or drawables.
1487 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001488 * <p>The guarantee of no message handling during the switch to the next
1489 * activity simplifies use with active objects. For example if your retained
1490 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1491 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1492 * not be called from the call here until you execute the next instance's
1493 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1494 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1495 * running in a separate thread.)
1496 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 * @return Return any Object holding the desired state to propagate to the
1498 * next activity instance.
1499 */
1500 public Object onRetainNonConfigurationInstance() {
1501 return null;
1502 }
1503
1504 /**
1505 * Retrieve the non-configuration instance data that was previously
1506 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1507 * be available from the initial {@link #onCreate} and
1508 * {@link #onStart} calls to the new instance, allowing you to extract
1509 * any useful dynamic state from the previous instance.
1510 *
1511 * <p>Note that the data you retrieve here should <em>only</em> be used
1512 * as an optimization for handling configuration changes. You should always
1513 * be able to handle getting a null pointer back, and an activity must
1514 * still be able to restore itself to its previous state (through the
1515 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1516 * function returns null.
1517 *
1518 * @return Returns the object previously returned by
1519 * {@link #onRetainNonConfigurationChildInstances()}
1520 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001521 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1522 return mLastNonConfigurationInstances != null
1523 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
1525
1526 /**
1527 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1528 * it should return either a mapping from child activity id strings to arbitrary objects,
1529 * or null. This method is intended to be used by Activity framework subclasses that control a
1530 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1531 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1532 */
1533 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1534 return null;
1535 }
1536
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001537 NonConfigurationInstances retainNonConfigurationInstances() {
1538 Object activity = onRetainNonConfigurationInstance();
1539 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1540 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001541 boolean retainLoaders = false;
1542 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001543 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001544 // have nothing useful to retain.
1545 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001546 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001547 if (lm.mRetaining) {
1548 retainLoaders = true;
1549 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001550 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001551 mAllLoaderManagers.removeAt(i);
1552 }
1553 }
1554 }
1555 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001556 return null;
1557 }
1558
1559 NonConfigurationInstances nci = new NonConfigurationInstances();
1560 nci.activity = activity;
1561 nci.children = children;
1562 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001563 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001564 return nci;
1565 }
1566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 public void onLowMemory() {
1568 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001569 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571
1572 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001573 * Return the FragmentManager for interacting with fragments associated
1574 * with this activity.
1575 */
1576 public FragmentManager getFragmentManager() {
1577 return mFragments;
1578 }
1579
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001580 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001581 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001582 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001583 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1584 if (lm != null) {
1585 lm.doDestroy();
1586 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001587 mAllLoaderManagers.remove(index);
1588 }
1589 }
1590
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001591 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001592 * Called when a Fragment is being attached to this activity, immediately
1593 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1594 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1595 */
1596 public void onAttachFragment(Fragment fragment) {
1597 }
1598
1599 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 * Wrapper around
1601 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1602 * that gives the resulting {@link Cursor} to call
1603 * {@link #startManagingCursor} so that the activity will manage its
1604 * lifecycle for you.
1605 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001606 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1607 * or later, consider instead using {@link LoaderManager} instead, available
1608 * via {@link #getLoaderManager()}.</em>
1609 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 * @param uri The URI of the content provider to query.
1611 * @param projection List of columns to return.
1612 * @param selection SQL WHERE clause.
1613 * @param sortOrder SQL ORDER BY clause.
1614 *
1615 * @return The Cursor that was returned by query().
1616 *
1617 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1618 * @see #startManagingCursor
1619 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001620 *
1621 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 */
Jason parks6ed50de2010-08-25 10:18:50 -05001623 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001624 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1625 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1627 if (c != null) {
1628 startManagingCursor(c);
1629 }
1630 return c;
1631 }
1632
1633 /**
1634 * Wrapper around
1635 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1636 * that gives the resulting {@link Cursor} to call
1637 * {@link #startManagingCursor} so that the activity will manage its
1638 * lifecycle for you.
1639 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001640 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1641 * or later, consider instead using {@link LoaderManager} instead, available
1642 * via {@link #getLoaderManager()}.</em>
1643 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 * @param uri The URI of the content provider to query.
1645 * @param projection List of columns to return.
1646 * @param selection SQL WHERE clause.
1647 * @param selectionArgs The arguments to selection, if any ?s are pesent
1648 * @param sortOrder SQL ORDER BY clause.
1649 *
1650 * @return The Cursor that was returned by query().
1651 *
1652 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1653 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001654 *
1655 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 */
Jason parks6ed50de2010-08-25 10:18:50 -05001657 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001658 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1659 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1661 if (c != null) {
1662 startManagingCursor(c);
1663 }
1664 return c;
1665 }
1666
1667 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 * This method allows the activity to take care of managing the given
1669 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1670 * That is, when the activity is stopped it will automatically call
1671 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1672 * it will call {@link Cursor#requery} for you. When the activity is
1673 * destroyed, all managed Cursors will be closed automatically.
1674 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001675 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1676 * or later, consider instead using {@link LoaderManager} instead, available
1677 * via {@link #getLoaderManager()}.</em>
1678 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 * @param c The Cursor to be managed.
1680 *
1681 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1682 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001683 *
1684 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 */
Jason parks6ed50de2010-08-25 10:18:50 -05001686 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 public void startManagingCursor(Cursor c) {
1688 synchronized (mManagedCursors) {
1689 mManagedCursors.add(new ManagedCursor(c));
1690 }
1691 }
1692
1693 /**
1694 * Given a Cursor that was previously given to
1695 * {@link #startManagingCursor}, stop the activity's management of that
1696 * cursor.
1697 *
1698 * @param c The Cursor that was being managed.
1699 *
1700 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001701 *
1702 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 */
Jason parks6ed50de2010-08-25 10:18:50 -05001704 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 public void stopManagingCursor(Cursor c) {
1706 synchronized (mManagedCursors) {
1707 final int N = mManagedCursors.size();
1708 for (int i=0; i<N; i++) {
1709 ManagedCursor mc = mManagedCursors.get(i);
1710 if (mc.mCursor == c) {
1711 mManagedCursors.remove(i);
1712 break;
1713 }
1714 }
1715 }
1716 }
1717
1718 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001719 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1720 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001721 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001723 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726
1727 /**
1728 * Finds a view that was identified by the id attribute from the XML that
1729 * was processed in {@link #onCreate}.
1730 *
1731 * @return The view if found or null otherwise.
1732 */
1733 public View findViewById(int id) {
1734 return getWindow().findViewById(id);
1735 }
Adam Powell33b97432010-04-20 10:01:14 -07001736
1737 /**
1738 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001739 *
Adam Powell33b97432010-04-20 10:01:14 -07001740 * @return The Activity's ActionBar, or null if it does not have one.
1741 */
1742 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001743 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001744 return mActionBar;
1745 }
1746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 /**
Adam Powell33b97432010-04-20 10:01:14 -07001748 * Creates a new ActionBar, locates the inflated ActionBarView,
1749 * initializes the ActionBar with the view, and sets mActionBar.
1750 */
1751 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001752 Window window = getWindow();
Adam Powell9b4c8042010-08-10 15:36:44 -07001753 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001754 return;
1755 }
1756
Adam Powell661c9082010-07-02 10:09:44 -07001757 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001758 }
1759
1760 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 * Set the activity content from a layout resource. The resource will be
1762 * inflated, adding all top-level views to the activity.
1763 *
1764 * @param layoutResID Resource ID to be inflated.
1765 */
1766 public void setContentView(int layoutResID) {
1767 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001768 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770
1771 /**
1772 * Set the activity content to an explicit view. This view is placed
1773 * directly into the activity's view hierarchy. It can itself be a complex
1774 * view hierarhcy.
1775 *
1776 * @param view The desired content to display.
1777 */
1778 public void setContentView(View view) {
1779 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001780 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
1782
1783 /**
1784 * Set the activity content to an explicit view. This view is placed
1785 * directly into the activity's view hierarchy. It can itself be a complex
1786 * view hierarhcy.
1787 *
1788 * @param view The desired content to display.
1789 * @param params Layout parameters for the view.
1790 */
1791 public void setContentView(View view, ViewGroup.LayoutParams params) {
1792 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001793 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795
1796 /**
1797 * Add an additional content view to the activity. Added after any existing
1798 * ones in the activity -- existing views are NOT removed.
1799 *
1800 * @param view The desired content to display.
1801 * @param params Layout parameters for the view.
1802 */
1803 public void addContentView(View view, ViewGroup.LayoutParams params) {
1804 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001805 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
1807
1808 /**
1809 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1810 * keys.
1811 *
1812 * @see #setDefaultKeyMode
1813 */
1814 static public final int DEFAULT_KEYS_DISABLE = 0;
1815 /**
1816 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1817 * key handling.
1818 *
1819 * @see #setDefaultKeyMode
1820 */
1821 static public final int DEFAULT_KEYS_DIALER = 1;
1822 /**
1823 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1824 * default key handling.
1825 *
1826 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1827 *
1828 * @see #setDefaultKeyMode
1829 */
1830 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1831 /**
1832 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1833 * will start an application-defined search. (If the application or activity does not
1834 * actually define a search, the the keys will be ignored.)
1835 *
1836 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1837 *
1838 * @see #setDefaultKeyMode
1839 */
1840 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1841
1842 /**
1843 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1844 * will start a global search (typically web search, but some platforms may define alternate
1845 * methods for global search)
1846 *
1847 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1848 *
1849 * @see #setDefaultKeyMode
1850 */
1851 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1852
1853 /**
1854 * Select the default key handling for this activity. This controls what
1855 * will happen to key events that are not otherwise handled. The default
1856 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1857 * floor. Other modes allow you to launch the dialer
1858 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1859 * menu without requiring the menu key be held down
1860 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1861 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1862 *
1863 * <p>Note that the mode selected here does not impact the default
1864 * handling of system keys, such as the "back" and "menu" keys, and your
1865 * activity and its views always get a first chance to receive and handle
1866 * all application keys.
1867 *
1868 * @param mode The desired default key mode constant.
1869 *
1870 * @see #DEFAULT_KEYS_DISABLE
1871 * @see #DEFAULT_KEYS_DIALER
1872 * @see #DEFAULT_KEYS_SHORTCUT
1873 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1874 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1875 * @see #onKeyDown
1876 */
1877 public final void setDefaultKeyMode(int mode) {
1878 mDefaultKeyMode = mode;
1879
1880 // Some modes use a SpannableStringBuilder to track & dispatch input events
1881 // This list must remain in sync with the switch in onKeyDown()
1882 switch (mode) {
1883 case DEFAULT_KEYS_DISABLE:
1884 case DEFAULT_KEYS_SHORTCUT:
1885 mDefaultKeySsb = null; // not used in these modes
1886 break;
1887 case DEFAULT_KEYS_DIALER:
1888 case DEFAULT_KEYS_SEARCH_LOCAL:
1889 case DEFAULT_KEYS_SEARCH_GLOBAL:
1890 mDefaultKeySsb = new SpannableStringBuilder();
1891 Selection.setSelection(mDefaultKeySsb,0);
1892 break;
1893 default:
1894 throw new IllegalArgumentException();
1895 }
1896 }
1897
1898 /**
1899 * Called when a key was pressed down and not handled by any of the views
1900 * inside of the activity. So, for example, key presses while the cursor
1901 * is inside a TextView will not trigger the event (unless it is a navigation
1902 * to another object) because TextView handles its own key presses.
1903 *
1904 * <p>If the focused view didn't want this event, this method is called.
1905 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001906 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1907 * by calling {@link #onBackPressed()}, though the behavior varies based
1908 * on the application compatibility mode: for
1909 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1910 * it will set up the dispatch to call {@link #onKeyUp} where the action
1911 * will be performed; for earlier applications, it will perform the
1912 * action immediately in on-down, as those versions of the platform
1913 * behaved.
1914 *
1915 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001916 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 *
1918 * @return Return <code>true</code> to prevent this event from being propagated
1919 * further, or <code>false</code> to indicate that you have not handled
1920 * this event and it should continue to be propagated.
1921 * @see #onKeyUp
1922 * @see android.view.KeyEvent
1923 */
1924 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001925 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001926 if (getApplicationInfo().targetSdkVersion
1927 >= Build.VERSION_CODES.ECLAIR) {
1928 event.startTracking();
1929 } else {
1930 onBackPressed();
1931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 return true;
1933 }
1934
1935 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1936 return false;
1937 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001938 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1939 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1940 return true;
1941 }
1942 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 } else {
1944 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1945 boolean clearSpannable = false;
1946 boolean handled;
1947 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1948 clearSpannable = true;
1949 handled = false;
1950 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001951 handled = TextKeyListener.getInstance().onKeyDown(
1952 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 if (handled && mDefaultKeySsb.length() > 0) {
1954 // something useable has been typed - dispatch it now.
1955
1956 final String str = mDefaultKeySsb.toString();
1957 clearSpannable = true;
1958
1959 switch (mDefaultKeyMode) {
1960 case DEFAULT_KEYS_DIALER:
1961 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1962 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1963 startActivity(intent);
1964 break;
1965 case DEFAULT_KEYS_SEARCH_LOCAL:
1966 startSearch(str, false, null, false);
1967 break;
1968 case DEFAULT_KEYS_SEARCH_GLOBAL:
1969 startSearch(str, false, null, true);
1970 break;
1971 }
1972 }
1973 }
1974 if (clearSpannable) {
1975 mDefaultKeySsb.clear();
1976 mDefaultKeySsb.clearSpans();
1977 Selection.setSelection(mDefaultKeySsb,0);
1978 }
1979 return handled;
1980 }
1981 }
1982
1983 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001984 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
1985 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
1986 * the event).
1987 */
1988 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1989 return false;
1990 }
1991
1992 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 * Called when a key was released and not handled by any of the views
1994 * inside of the activity. So, for example, key presses while the cursor
1995 * is inside a TextView will not trigger the event (unless it is a navigation
1996 * to another object) because TextView handles its own key presses.
1997 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001998 * <p>The default implementation handles KEYCODE_BACK to stop the activity
1999 * and go back.
2000 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 * @return Return <code>true</code> to prevent this event from being propagated
2002 * further, or <code>false</code> to indicate that you have not handled
2003 * this event and it should continue to be propagated.
2004 * @see #onKeyDown
2005 * @see KeyEvent
2006 */
2007 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002008 if (getApplicationInfo().targetSdkVersion
2009 >= Build.VERSION_CODES.ECLAIR) {
2010 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2011 && !event.isCanceled()) {
2012 onBackPressed();
2013 return true;
2014 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 return false;
2017 }
2018
2019 /**
2020 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2021 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2022 * the event).
2023 */
2024 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2025 return false;
2026 }
2027
2028 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002029 * Called when the activity has detected the user's press of the back
2030 * key. The default implementation simply finishes the current activity,
2031 * but you can override this to do whatever you want.
2032 */
2033 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002034 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002035 finish();
2036 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002037 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002038
2039 /**
2040 * Called when a key shortcut event is not handled by any of the views in the Activity.
2041 * Override this method to implement global key shortcuts for the Activity.
2042 * Key shortcuts can also be implemented by setting the
2043 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2044 *
2045 * @param keyCode The value in event.getKeyCode().
2046 * @param event Description of the key event.
2047 * @return True if the key shortcut was handled.
2048 */
2049 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2050 return false;
2051 }
2052
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002053 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 * Called when a touch screen event was not handled by any of the views
2055 * under it. This is most useful to process touch events that happen
2056 * outside of your window bounds, where there is no view to receive it.
2057 *
2058 * @param event The touch screen event being processed.
2059 *
2060 * @return Return true if you have consumed the event, false if you haven't.
2061 * The default implementation always returns false.
2062 */
2063 public boolean onTouchEvent(MotionEvent event) {
2064 return false;
2065 }
2066
2067 /**
2068 * Called when the trackball was moved and not handled by any of the
2069 * views inside of the activity. So, for example, if the trackball moves
2070 * while focus is on a button, you will receive a call here because
2071 * buttons do not normally do anything with trackball events. The call
2072 * here happens <em>before</em> trackball movements are converted to
2073 * DPAD key events, which then get sent back to the view hierarchy, and
2074 * will be processed at the point for things like focus navigation.
2075 *
2076 * @param event The trackball event being processed.
2077 *
2078 * @return Return true if you have consumed the event, false if you haven't.
2079 * The default implementation always returns false.
2080 */
2081 public boolean onTrackballEvent(MotionEvent event) {
2082 return false;
2083 }
Jeff Browncb1404e2011-01-15 18:14:15 -08002084
2085 /**
2086 * Called when a generic motion event was not handled by any of the
2087 * views inside of the activity.
2088 * <p>
2089 * Generic motion events are dispatched to the focused view to describe
2090 * the motions of input devices such as joysticks. The
2091 * {@link MotionEvent#getSource() source} of the motion event specifies
2092 * the class of input that was received. Implementations of this method
2093 * must examine the bits in the source before processing the event.
2094 * The following code example shows how this is done.
2095 * </p>
2096 * <code>
2097 * public boolean onGenericMotionEvent(MotionEvent event) {
2098 * if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
2099 * float x = event.getX();
2100 * float y = event.getY();
2101 * // process the joystick motion
2102 * return true;
2103 * }
2104 * return super.onGenericMotionEvent(event);
2105 * }
2106 * </code>
2107 *
2108 * @param event The generic motion event being processed.
2109 *
2110 * @return Return true if you have consumed the event, false if you haven't.
2111 * The default implementation always returns false.
2112 */
2113 public boolean onGenericMotionEvent(MotionEvent event) {
2114 return false;
2115 }
2116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 /**
2118 * Called whenever a key, touch, or trackball event is dispatched to the
2119 * activity. Implement this method if you wish to know that the user has
2120 * interacted with the device in some way while your activity is running.
2121 * This callback and {@link #onUserLeaveHint} are intended to help
2122 * activities manage status bar notifications intelligently; specifically,
2123 * for helping activities determine the proper time to cancel a notfication.
2124 *
2125 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2126 * be accompanied by calls to {@link #onUserInteraction}. This
2127 * ensures that your activity will be told of relevant user activity such
2128 * as pulling down the notification pane and touching an item there.
2129 *
2130 * <p>Note that this callback will be invoked for the touch down action
2131 * that begins a touch gesture, but may not be invoked for the touch-moved
2132 * and touch-up actions that follow.
2133 *
2134 * @see #onUserLeaveHint()
2135 */
2136 public void onUserInteraction() {
2137 }
2138
2139 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2140 // Update window manager if: we have a view, that view is
2141 // attached to its parent (which will be a RootView), and
2142 // this activity is not embedded.
2143 if (mParent == null) {
2144 View decor = mDecor;
2145 if (decor != null && decor.getParent() != null) {
2146 getWindowManager().updateViewLayout(decor, params);
2147 }
2148 }
2149 }
2150
2151 public void onContentChanged() {
2152 }
2153
2154 /**
2155 * Called when the current {@link Window} of the activity gains or loses
2156 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002157 * to the user. The default implementation clears the key tracking
2158 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002160 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 * is managed independently of activity lifecycles. As such, while focus
2162 * changes will generally have some relation to lifecycle changes (an
2163 * activity that is stopped will not generally get window focus), you
2164 * should not rely on any particular order between the callbacks here and
2165 * those in the other lifecycle methods such as {@link #onResume}.
2166 *
2167 * <p>As a general rule, however, a resumed activity will have window
2168 * focus... unless it has displayed other dialogs or popups that take
2169 * input focus, in which case the activity itself will not have focus
2170 * when the other windows have it. Likewise, the system may display
2171 * system-level windows (such as the status bar notification panel or
2172 * a system alert) which will temporarily take window input focus without
2173 * pausing the foreground activity.
2174 *
2175 * @param hasFocus Whether the window of this activity has focus.
2176 *
2177 * @see #hasWindowFocus()
2178 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002179 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 */
2181 public void onWindowFocusChanged(boolean hasFocus) {
2182 }
2183
2184 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002185 * Called when the main window associated with the activity has been
2186 * attached to the window manager.
2187 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2188 * for more information.
2189 * @see View#onAttachedToWindow
2190 */
2191 public void onAttachedToWindow() {
2192 }
2193
2194 /**
2195 * Called when the main window associated with the activity has been
2196 * detached from the window manager.
2197 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2198 * for more information.
2199 * @see View#onDetachedFromWindow
2200 */
2201 public void onDetachedFromWindow() {
2202 }
2203
2204 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 * Returns true if this activity's <em>main</em> window currently has window focus.
2206 * Note that this is not the same as the view itself having focus.
2207 *
2208 * @return True if this activity's main window currently has window focus.
2209 *
2210 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2211 */
2212 public boolean hasWindowFocus() {
2213 Window w = getWindow();
2214 if (w != null) {
2215 View d = w.getDecorView();
2216 if (d != null) {
2217 return d.hasWindowFocus();
2218 }
2219 }
2220 return false;
2221 }
2222
2223 /**
2224 * Called to process key events. You can override this to intercept all
2225 * key events before they are dispatched to the window. Be sure to call
2226 * this implementation for key events that should be handled normally.
2227 *
2228 * @param event The key event.
2229 *
2230 * @return boolean Return true if this event was consumed.
2231 */
2232 public boolean dispatchKeyEvent(KeyEvent event) {
2233 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002234 Window win = getWindow();
2235 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 return true;
2237 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002238 View decor = mDecor;
2239 if (decor == null) decor = win.getDecorView();
2240 return event.dispatch(this, decor != null
2241 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
2243
2244 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002245 * Called to process a key shortcut event.
2246 * You can override this to intercept all key shortcut events before they are
2247 * dispatched to the window. Be sure to call this implementation for key shortcut
2248 * events that should be handled normally.
2249 *
2250 * @param event The key shortcut event.
2251 * @return True if this event was consumed.
2252 */
2253 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2254 onUserInteraction();
2255 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2256 return true;
2257 }
2258 return onKeyShortcut(event.getKeyCode(), event);
2259 }
2260
2261 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 * Called to process touch screen events. You can override this to
2263 * intercept all touch screen events before they are dispatched to the
2264 * window. Be sure to call this implementation for touch screen events
2265 * that should be handled normally.
2266 *
2267 * @param ev The touch screen event.
2268 *
2269 * @return boolean Return true if this event was consumed.
2270 */
2271 public boolean dispatchTouchEvent(MotionEvent ev) {
2272 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2273 onUserInteraction();
2274 }
2275 if (getWindow().superDispatchTouchEvent(ev)) {
2276 return true;
2277 }
2278 return onTouchEvent(ev);
2279 }
2280
2281 /**
2282 * Called to process trackball events. You can override this to
2283 * intercept all trackball events before they are dispatched to the
2284 * window. Be sure to call this implementation for trackball events
2285 * that should be handled normally.
2286 *
2287 * @param ev The trackball event.
2288 *
2289 * @return boolean Return true if this event was consumed.
2290 */
2291 public boolean dispatchTrackballEvent(MotionEvent ev) {
2292 onUserInteraction();
2293 if (getWindow().superDispatchTrackballEvent(ev)) {
2294 return true;
2295 }
2296 return onTrackballEvent(ev);
2297 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002298
Jeff Browncb1404e2011-01-15 18:14:15 -08002299 /**
2300 * Called to process generic motion events. You can override this to
2301 * intercept all generic motion events before they are dispatched to the
2302 * window. Be sure to call this implementation for generic motion events
2303 * that should be handled normally.
2304 *
2305 * @param ev The generic motion event.
2306 *
2307 * @return boolean Return true if this event was consumed.
2308 */
2309 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
2310 onUserInteraction();
2311 if (getWindow().superDispatchGenericMotionEvent(ev)) {
2312 return true;
2313 }
2314 return onGenericMotionEvent(ev);
2315 }
2316
svetoslavganov75986cf2009-05-14 22:28:01 -07002317 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2318 event.setClassName(getClass().getName());
2319 event.setPackageName(getPackageName());
2320
2321 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002322 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2323 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002324 event.setFullScreen(isFullScreen);
2325
2326 CharSequence title = getTitle();
2327 if (!TextUtils.isEmpty(title)) {
2328 event.getText().add(title);
2329 }
2330
2331 return true;
2332 }
2333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 /**
2335 * Default implementation of
2336 * {@link android.view.Window.Callback#onCreatePanelView}
2337 * for activities. This
2338 * simply returns null so that all panel sub-windows will have the default
2339 * menu behavior.
2340 */
2341 public View onCreatePanelView(int featureId) {
2342 return null;
2343 }
2344
2345 /**
2346 * Default implementation of
2347 * {@link android.view.Window.Callback#onCreatePanelMenu}
2348 * for activities. This calls through to the new
2349 * {@link #onCreateOptionsMenu} method for the
2350 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2351 * so that subclasses of Activity don't need to deal with feature codes.
2352 */
2353 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2354 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002355 boolean show = onCreateOptionsMenu(menu);
2356 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2357 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 }
2359 return false;
2360 }
2361
2362 /**
2363 * Default implementation of
2364 * {@link android.view.Window.Callback#onPreparePanel}
2365 * for activities. This
2366 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2367 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2368 * panel, so that subclasses of
2369 * Activity don't need to deal with feature codes.
2370 */
2371 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2372 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2373 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002374 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 return goforit && menu.hasVisibleItems();
2376 }
2377 return true;
2378 }
2379
2380 /**
2381 * {@inheritDoc}
2382 *
2383 * @return The default implementation returns true.
2384 */
2385 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002386 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell049dd3d2010-12-02 13:43:59 -08002387 if (mActionBar != null) {
2388 mActionBar.dispatchMenuVisibilityChanged(true);
2389 } else {
2390 Log.e(TAG, "Tried to open action bar menu with no action bar");
2391 }
Adam Powell8515ee82010-11-30 14:09:55 -08002392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 return true;
2394 }
2395
2396 /**
2397 * Default implementation of
2398 * {@link android.view.Window.Callback#onMenuItemSelected}
2399 * for activities. This calls through to the new
2400 * {@link #onOptionsItemSelected} method for the
2401 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2402 * panel, so that subclasses of
2403 * Activity don't need to deal with feature codes.
2404 */
2405 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2406 switch (featureId) {
2407 case Window.FEATURE_OPTIONS_PANEL:
2408 // Put event logging here so it gets called even if subclass
2409 // doesn't call through to superclass's implmeentation of each
2410 // of these methods below
2411 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002412 if (onOptionsItemSelected(item)) {
2413 return true;
2414 }
2415 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416
2417 case Window.FEATURE_CONTEXT_MENU:
2418 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002419 if (onContextItemSelected(item)) {
2420 return true;
2421 }
2422 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 default:
2425 return false;
2426 }
2427 }
2428
2429 /**
2430 * Default implementation of
2431 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2432 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2433 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2434 * so that subclasses of Activity don't need to deal with feature codes.
2435 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2436 * {@link #onContextMenuClosed(Menu)} will be called.
2437 */
2438 public void onPanelClosed(int featureId, Menu menu) {
2439 switch (featureId) {
2440 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002441 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 onOptionsMenuClosed(menu);
2443 break;
2444
2445 case Window.FEATURE_CONTEXT_MENU:
2446 onContextMenuClosed(menu);
2447 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002448
2449 case Window.FEATURE_ACTION_BAR:
2450 mActionBar.dispatchMenuVisibilityChanged(false);
2451 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453 }
2454
2455 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002456 * Declare that the options menu has changed, so should be recreated.
2457 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2458 * time it needs to be displayed.
2459 */
2460 public void invalidateOptionsMenu() {
2461 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2462 }
2463
2464 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 * Initialize the contents of the Activity's standard options menu. You
2466 * should place your menu items in to <var>menu</var>.
2467 *
2468 * <p>This is only called once, the first time the options menu is
2469 * displayed. To update the menu every time it is displayed, see
2470 * {@link #onPrepareOptionsMenu}.
2471 *
2472 * <p>The default implementation populates the menu with standard system
2473 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2474 * they will be correctly ordered with application-defined menu items.
2475 * Deriving classes should always call through to the base implementation.
2476 *
2477 * <p>You can safely hold on to <var>menu</var> (and any items created
2478 * from it), making modifications to it as desired, until the next
2479 * time onCreateOptionsMenu() is called.
2480 *
2481 * <p>When you add items to the menu, you can implement the Activity's
2482 * {@link #onOptionsItemSelected} method to handle them there.
2483 *
2484 * @param menu The options menu in which you place your items.
2485 *
2486 * @return You must return true for the menu to be displayed;
2487 * if you return false it will not be shown.
2488 *
2489 * @see #onPrepareOptionsMenu
2490 * @see #onOptionsItemSelected
2491 */
2492 public boolean onCreateOptionsMenu(Menu menu) {
2493 if (mParent != null) {
2494 return mParent.onCreateOptionsMenu(menu);
2495 }
2496 return true;
2497 }
2498
2499 /**
2500 * Prepare the Screen's standard options menu to be displayed. This is
2501 * called right before the menu is shown, every time it is shown. You can
2502 * use this method to efficiently enable/disable items or otherwise
2503 * dynamically modify the contents.
2504 *
2505 * <p>The default implementation updates the system menu items based on the
2506 * activity's state. Deriving classes should always call through to the
2507 * base class implementation.
2508 *
2509 * @param menu The options menu as last shown or first initialized by
2510 * onCreateOptionsMenu().
2511 *
2512 * @return You must return true for the menu to be displayed;
2513 * if you return false it will not be shown.
2514 *
2515 * @see #onCreateOptionsMenu
2516 */
2517 public boolean onPrepareOptionsMenu(Menu menu) {
2518 if (mParent != null) {
2519 return mParent.onPrepareOptionsMenu(menu);
2520 }
2521 return true;
2522 }
2523
2524 /**
2525 * This hook is called whenever an item in your options menu is selected.
2526 * The default implementation simply returns false to have the normal
2527 * processing happen (calling the item's Runnable or sending a message to
2528 * its Handler as appropriate). You can use this method for any items
2529 * for which you would like to do processing without those other
2530 * facilities.
2531 *
2532 * <p>Derived classes should call through to the base class for it to
2533 * perform the default menu handling.
2534 *
2535 * @param item The menu item that was selected.
2536 *
2537 * @return boolean Return false to allow normal menu processing to
2538 * proceed, true to consume it here.
2539 *
2540 * @see #onCreateOptionsMenu
2541 */
2542 public boolean onOptionsItemSelected(MenuItem item) {
2543 if (mParent != null) {
2544 return mParent.onOptionsItemSelected(item);
2545 }
2546 return false;
2547 }
2548
2549 /**
2550 * This hook is called whenever the options menu is being closed (either by the user canceling
2551 * the menu with the back/menu button, or when an item is selected).
2552 *
2553 * @param menu The options menu as last shown or first initialized by
2554 * onCreateOptionsMenu().
2555 */
2556 public void onOptionsMenuClosed(Menu menu) {
2557 if (mParent != null) {
2558 mParent.onOptionsMenuClosed(menu);
2559 }
2560 }
2561
2562 /**
2563 * Programmatically opens the options menu. If the options menu is already
2564 * open, this method does nothing.
2565 */
2566 public void openOptionsMenu() {
2567 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2568 }
2569
2570 /**
2571 * Progammatically closes the options menu. If the options menu is already
2572 * closed, this method does nothing.
2573 */
2574 public void closeOptionsMenu() {
2575 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2576 }
2577
2578 /**
2579 * Called when a context menu for the {@code view} is about to be shown.
2580 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2581 * time the context menu is about to be shown and should be populated for
2582 * the view (or item inside the view for {@link AdapterView} subclasses,
2583 * this can be found in the {@code menuInfo})).
2584 * <p>
2585 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2586 * item has been selected.
2587 * <p>
2588 * It is not safe to hold onto the context menu after this method returns.
2589 * {@inheritDoc}
2590 */
2591 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2592 }
2593
2594 /**
2595 * Registers a context menu to be shown for the given view (multiple views
2596 * can show the context menu). This method will set the
2597 * {@link OnCreateContextMenuListener} on the view to this activity, so
2598 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2599 * called when it is time to show the context menu.
2600 *
2601 * @see #unregisterForContextMenu(View)
2602 * @param view The view that should show a context menu.
2603 */
2604 public void registerForContextMenu(View view) {
2605 view.setOnCreateContextMenuListener(this);
2606 }
2607
2608 /**
2609 * Prevents a context menu to be shown for the given view. This method will remove the
2610 * {@link OnCreateContextMenuListener} on the view.
2611 *
2612 * @see #registerForContextMenu(View)
2613 * @param view The view that should stop showing a context menu.
2614 */
2615 public void unregisterForContextMenu(View view) {
2616 view.setOnCreateContextMenuListener(null);
2617 }
2618
2619 /**
2620 * Programmatically opens the context menu for a particular {@code view}.
2621 * The {@code view} should have been added via
2622 * {@link #registerForContextMenu(View)}.
2623 *
2624 * @param view The view to show the context menu for.
2625 */
2626 public void openContextMenu(View view) {
2627 view.showContextMenu();
2628 }
2629
2630 /**
2631 * Programmatically closes the most recently opened context menu, if showing.
2632 */
2633 public void closeContextMenu() {
2634 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2635 }
2636
2637 /**
2638 * This hook is called whenever an item in a context menu is selected. The
2639 * default implementation simply returns false to have the normal processing
2640 * happen (calling the item's Runnable or sending a message to its Handler
2641 * as appropriate). You can use this method for any items for which you
2642 * would like to do processing without those other facilities.
2643 * <p>
2644 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2645 * View that added this menu item.
2646 * <p>
2647 * Derived classes should call through to the base class for it to perform
2648 * the default menu handling.
2649 *
2650 * @param item The context menu item that was selected.
2651 * @return boolean Return false to allow normal context menu processing to
2652 * proceed, true to consume it here.
2653 */
2654 public boolean onContextItemSelected(MenuItem item) {
2655 if (mParent != null) {
2656 return mParent.onContextItemSelected(item);
2657 }
2658 return false;
2659 }
2660
2661 /**
2662 * This hook is called whenever the context menu is being closed (either by
2663 * the user canceling the menu with the back/menu button, or when an item is
2664 * selected).
2665 *
2666 * @param menu The context menu that is being closed.
2667 */
2668 public void onContextMenuClosed(Menu menu) {
2669 if (mParent != null) {
2670 mParent.onContextMenuClosed(menu);
2671 }
2672 }
2673
2674 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002675 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002677 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 protected Dialog onCreateDialog(int id) {
2679 return null;
2680 }
2681
2682 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002683 * Callback for creating dialogs that are managed (saved and restored) for you
2684 * by the activity. The default implementation calls through to
2685 * {@link #onCreateDialog(int)} for compatibility.
2686 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002687 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2688 * or later, consider instead using a {@link DialogFragment} instead.</em>
2689 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002690 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2691 * this method the first time, and hang onto it thereafter. Any dialog
2692 * that is created by this method will automatically be saved and restored
2693 * for you, including whether it is showing.
2694 *
2695 * <p>If you would like the activity to manage saving and restoring dialogs
2696 * for you, you should override this method and handle any ids that are
2697 * passed to {@link #showDialog}.
2698 *
2699 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2700 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2701 *
2702 * @param id The id of the dialog.
2703 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2704 * @return The dialog. If you return null, the dialog will not be created.
2705 *
2706 * @see #onPrepareDialog(int, Dialog, Bundle)
2707 * @see #showDialog(int, Bundle)
2708 * @see #dismissDialog(int)
2709 * @see #removeDialog(int)
2710 */
2711 protected Dialog onCreateDialog(int id, Bundle args) {
2712 return onCreateDialog(id);
2713 }
2714
2715 /**
2716 * @deprecated Old no-arguments version of
2717 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2718 */
2719 @Deprecated
2720 protected void onPrepareDialog(int id, Dialog dialog) {
2721 dialog.setOwnerActivity(this);
2722 }
2723
2724 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002726 * shown. The default implementation calls through to
2727 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2728 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 * <p>
2730 * Override this if you need to update a managed dialog based on the state
2731 * of the application each time it is shown. For example, a time picker
2732 * dialog might want to be updated with the current time. You should call
2733 * through to the superclass's implementation. The default implementation
2734 * will set this Activity as the owner activity on the Dialog.
2735 *
2736 * @param id The id of the managed dialog.
2737 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002738 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2739 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 * @see #showDialog(int)
2741 * @see #dismissDialog(int)
2742 * @see #removeDialog(int)
2743 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002744 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2745 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747
2748 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002749 * Simple version of {@link #showDialog(int, Bundle)} that does not
2750 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2751 * with null arguments.
2752 */
2753 public final void showDialog(int id) {
2754 showDialog(id, null);
2755 }
2756
2757 /**
2758 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 * will be made with the same id the first time this is called for a given
2760 * id. From thereafter, the dialog will be automatically saved and restored.
2761 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002762 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2763 * or later, consider instead using a {@link DialogFragment} instead.</em>
2764 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002765 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 * be made to provide an opportunity to do any timely preparation.
2767 *
2768 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002769 * @param args Arguments to pass through to the dialog. These will be saved
2770 * and restored for you. Note that if the dialog is already created,
2771 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2772 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002773 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002774 * @return Returns true if the Dialog was created; false is returned if
2775 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2776 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002777 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002778 * @see #onCreateDialog(int, Bundle)
2779 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 * @see #dismissDialog(int)
2781 * @see #removeDialog(int)
2782 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002783 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002785 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002787 ManagedDialog md = mManagedDialogs.get(id);
2788 if (md == null) {
2789 md = new ManagedDialog();
2790 md.mDialog = createDialog(id, null, args);
2791 if (md.mDialog == null) {
2792 return false;
2793 }
2794 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
2796
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002797 md.mArgs = args;
2798 onPrepareDialog(id, md.mDialog, args);
2799 md.mDialog.show();
2800 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 }
2802
2803 /**
2804 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2805 *
2806 * @param id The id of the managed dialog.
2807 *
2808 * @throws IllegalArgumentException if the id was not previously shown via
2809 * {@link #showDialog(int)}.
2810 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002811 * @see #onCreateDialog(int, Bundle)
2812 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 * @see #showDialog(int)
2814 * @see #removeDialog(int)
2815 */
2816 public final void dismissDialog(int id) {
2817 if (mManagedDialogs == null) {
2818 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002820
2821 final ManagedDialog md = mManagedDialogs.get(id);
2822 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 throw missingDialog(id);
2824 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002825 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827
2828 /**
2829 * Creates an exception to throw if a user passed in a dialog id that is
2830 * unexpected.
2831 */
2832 private IllegalArgumentException missingDialog(int id) {
2833 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2834 + "shown via Activity#showDialog");
2835 }
2836
2837 /**
2838 * Removes any internal references to a dialog managed by this Activity.
2839 * If the dialog is showing, it will dismiss it as part of the clean up.
2840 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002841 * <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 -08002842 * want to avoid the overhead of saving and restoring it in the future.
2843 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002844 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2845 * will not throw an exception if you try to remove an ID that does not
2846 * currently have an associated dialog.</p>
2847 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 * @param id The id of the managed dialog.
2849 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002850 * @see #onCreateDialog(int, Bundle)
2851 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 * @see #showDialog(int)
2853 * @see #dismissDialog(int)
2854 */
2855 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002856 if (mManagedDialogs != null) {
2857 final ManagedDialog md = mManagedDialogs.get(id);
2858 if (md != null) {
2859 md.mDialog.dismiss();
2860 mManagedDialogs.remove(id);
2861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
2865 /**
2866 * This hook is called when the user signals the desire to start a search.
2867 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002868 * <p>You can use this function as a simple way to launch the search UI, in response to a
2869 * menu item, search button, or other widgets within your activity. Unless overidden,
2870 * calling this function is the same as calling
2871 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2872 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 *
2874 * <p>You can override this function to force global search, e.g. in response to a dedicated
2875 * search key, or to block search entirely (by simply returning false).
2876 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002877 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2878 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 *
2880 * @see android.app.SearchManager
2881 */
2882 public boolean onSearchRequested() {
2883 startSearch(null, false, null, false);
2884 return true;
2885 }
2886
2887 /**
2888 * This hook is called to launch the search UI.
2889 *
2890 * <p>It is typically called from onSearchRequested(), either directly from
2891 * Activity.onSearchRequested() or from an overridden version in any given
2892 * Activity. If your goal is simply to activate search, it is preferred to call
2893 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2894 * is to inject specific data such as context data, it is preferred to <i>override</i>
2895 * onSearchRequested(), so that any callers to it will benefit from the override.
2896 *
2897 * @param initialQuery Any non-null non-empty string will be inserted as
2898 * pre-entered text in the search query box.
2899 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2900 * any further typing will replace it. This is useful for cases where an entire pre-formed
2901 * query is being inserted. If false, the selection point will be placed at the end of the
2902 * inserted query. This is useful when the inserted query is text that the user entered,
2903 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2904 * if initialQuery is a non-empty string.</i>
2905 * @param appSearchData An application can insert application-specific
2906 * context here, in order to improve quality or specificity of its own
2907 * searches. This data will be returned with SEARCH intent(s). Null if
2908 * no extra data is required.
2909 * @param globalSearch If false, this will only launch the search that has been specifically
2910 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002911 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2913 *
2914 * @see android.app.SearchManager
2915 * @see #onSearchRequested
2916 */
2917 public void startSearch(String initialQuery, boolean selectInitialQuery,
2918 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002919 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002920 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 appSearchData, globalSearch);
2922 }
2923
2924 /**
krosaend2d60142009-08-17 08:56:48 -07002925 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2926 * the search dialog. Made available for testing purposes.
2927 *
2928 * @param query The query to trigger. If empty, the request will be ignored.
2929 * @param appSearchData An application can insert application-specific
2930 * context here, in order to improve quality or specificity of its own
2931 * searches. This data will be returned with SEARCH intent(s). Null if
2932 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002933 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002934 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002935 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002936 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002937 }
2938
2939 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 * Request that key events come to this activity. Use this if your
2941 * activity has no views with focus, but the activity still wants
2942 * a chance to process key events.
2943 *
2944 * @see android.view.Window#takeKeyEvents
2945 */
2946 public void takeKeyEvents(boolean get) {
2947 getWindow().takeKeyEvents(get);
2948 }
2949
2950 /**
2951 * Enable extended window features. This is a convenience for calling
2952 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2953 *
2954 * @param featureId The desired feature as defined in
2955 * {@link android.view.Window}.
2956 * @return Returns true if the requested feature is supported and now
2957 * enabled.
2958 *
2959 * @see android.view.Window#requestFeature
2960 */
2961 public final boolean requestWindowFeature(int featureId) {
2962 return getWindow().requestFeature(featureId);
2963 }
2964
2965 /**
2966 * Convenience for calling
2967 * {@link android.view.Window#setFeatureDrawableResource}.
2968 */
2969 public final void setFeatureDrawableResource(int featureId, int resId) {
2970 getWindow().setFeatureDrawableResource(featureId, resId);
2971 }
2972
2973 /**
2974 * Convenience for calling
2975 * {@link android.view.Window#setFeatureDrawableUri}.
2976 */
2977 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2978 getWindow().setFeatureDrawableUri(featureId, uri);
2979 }
2980
2981 /**
2982 * Convenience for calling
2983 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2984 */
2985 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2986 getWindow().setFeatureDrawable(featureId, drawable);
2987 }
2988
2989 /**
2990 * Convenience for calling
2991 * {@link android.view.Window#setFeatureDrawableAlpha}.
2992 */
2993 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2994 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2995 }
2996
2997 /**
2998 * Convenience for calling
2999 * {@link android.view.Window#getLayoutInflater}.
3000 */
3001 public LayoutInflater getLayoutInflater() {
3002 return getWindow().getLayoutInflater();
3003 }
3004
3005 /**
3006 * Returns a {@link MenuInflater} with this context.
3007 */
3008 public MenuInflater getMenuInflater() {
3009 return new MenuInflater(this);
3010 }
3011
3012 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003013 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3014 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 if (mParent == null) {
3016 super.onApplyThemeResource(theme, resid, first);
3017 } else {
3018 try {
3019 theme.setTo(mParent.getTheme());
3020 } catch (Exception e) {
3021 // Empty
3022 }
3023 theme.applyStyle(resid, false);
3024 }
3025 }
3026
3027 /**
3028 * Launch an activity for which you would like a result when it finished.
3029 * When this activity exits, your
3030 * onActivityResult() method will be called with the given requestCode.
3031 * Using a negative requestCode is the same as calling
3032 * {@link #startActivity} (the activity is not launched as a sub-activity).
3033 *
3034 * <p>Note that this method should only be used with Intent protocols
3035 * that are defined to return a result. In other protocols (such as
3036 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3037 * not get the result when you expect. For example, if the activity you
3038 * are launching uses the singleTask launch mode, it will not run in your
3039 * task and thus you will immediately receive a cancel result.
3040 *
3041 * <p>As a special case, if you call startActivityForResult() with a requestCode
3042 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3043 * activity, then your window will not be displayed until a result is
3044 * returned back from the started activity. This is to avoid visible
3045 * flickering when redirecting to another activity.
3046 *
3047 * <p>This method throws {@link android.content.ActivityNotFoundException}
3048 * if there was no Activity found to run the given Intent.
3049 *
3050 * @param intent The intent to start.
3051 * @param requestCode If >= 0, this code will be returned in
3052 * onActivityResult() when the activity exits.
3053 *
3054 * @throws android.content.ActivityNotFoundException
3055 *
3056 * @see #startActivity
3057 */
3058 public void startActivityForResult(Intent intent, int requestCode) {
3059 if (mParent == null) {
3060 Instrumentation.ActivityResult ar =
3061 mInstrumentation.execStartActivity(
3062 this, mMainThread.getApplicationThread(), mToken, this,
3063 intent, requestCode);
3064 if (ar != null) {
3065 mMainThread.sendActivityResult(
3066 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3067 ar.getResultData());
3068 }
3069 if (requestCode >= 0) {
3070 // If this start is requesting a result, we can avoid making
3071 // the activity visible until the result is received. Setting
3072 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3073 // activity hidden during this time, to avoid flickering.
3074 // This can only be done when a result is requested because
3075 // that guarantees we will get information back when the
3076 // activity is finished, no matter what happens to it.
3077 mStartedActivity = true;
3078 }
3079 } else {
3080 mParent.startActivityFromChild(this, intent, requestCode);
3081 }
3082 }
3083
3084 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003085 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003086 * to use a IntentSender to describe the activity to be started. If
3087 * the IntentSender is for an activity, that activity will be started
3088 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3089 * here; otherwise, its associated action will be executed (such as
3090 * sending a broadcast) as if you had called
3091 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003092 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003093 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003094 * @param requestCode If >= 0, this code will be returned in
3095 * onActivityResult() when the activity exits.
3096 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003097 * intent parameter to {@link IntentSender#sendIntent}.
3098 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003099 * would like to change.
3100 * @param flagsValues Desired values for any bits set in
3101 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003102 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003103 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003104 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3105 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3106 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003107 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003108 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003109 flagsMask, flagsValues, this);
3110 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003111 mParent.startIntentSenderFromChild(this, intent, requestCode,
3112 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003113 }
3114 }
3115
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003116 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003117 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003118 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003119 try {
3120 String resolvedType = null;
3121 if (fillInIntent != null) {
3122 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3123 }
3124 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003125 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003126 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3127 requestCode, flagsMask, flagsValues);
3128 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003129 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003130 }
3131 Instrumentation.checkStartActivityResult(result, null);
3132 } catch (RemoteException e) {
3133 }
3134 if (requestCode >= 0) {
3135 // If this start is requesting a result, we can avoid making
3136 // the activity visible until the result is received. Setting
3137 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3138 // activity hidden during this time, to avoid flickering.
3139 // This can only be done when a result is requested because
3140 // that guarantees we will get information back when the
3141 // activity is finished, no matter what happens to it.
3142 mStartedActivity = true;
3143 }
3144 }
3145
3146 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 * Launch a new activity. You will not receive any information about when
3148 * the activity exits. This implementation overrides the base version,
3149 * providing information about
3150 * the activity performing the launch. Because of this additional
3151 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3152 * required; if not specified, the new activity will be added to the
3153 * task of the caller.
3154 *
3155 * <p>This method throws {@link android.content.ActivityNotFoundException}
3156 * if there was no Activity found to run the given Intent.
3157 *
3158 * @param intent The intent to start.
3159 *
3160 * @throws android.content.ActivityNotFoundException
3161 *
3162 * @see #startActivityForResult
3163 */
3164 @Override
3165 public void startActivity(Intent intent) {
3166 startActivityForResult(intent, -1);
3167 }
3168
3169 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003170 * Launch a new activity. You will not receive any information about when
3171 * the activity exits. This implementation overrides the base version,
3172 * providing information about
3173 * the activity performing the launch. Because of this additional
3174 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3175 * required; if not specified, the new activity will be added to the
3176 * task of the caller.
3177 *
3178 * <p>This method throws {@link android.content.ActivityNotFoundException}
3179 * if there was no Activity found to run the given Intent.
3180 *
3181 * @param intents The intents to start.
3182 *
3183 * @throws android.content.ActivityNotFoundException
3184 *
3185 * @see #startActivityForResult
3186 */
3187 @Override
3188 public void startActivities(Intent[] intents) {
3189 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3190 mToken, this, intents);
3191 }
3192
3193 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003194 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003195 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003196 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003197 * for more information.
3198 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003199 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003200 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003201 * intent parameter to {@link IntentSender#sendIntent}.
3202 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003203 * would like to change.
3204 * @param flagsValues Desired values for any bits set in
3205 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003206 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003207 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003208 public void startIntentSender(IntentSender intent,
3209 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3210 throws IntentSender.SendIntentException {
3211 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3212 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003213 }
3214
3215 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 * A special variation to launch an activity only if a new activity
3217 * instance is needed to handle the given Intent. In other words, this is
3218 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3219 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3220 * singleTask or singleTop
3221 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3222 * and the activity
3223 * that handles <var>intent</var> is the same as your currently running
3224 * activity, then a new instance is not needed. In this case, instead of
3225 * the normal behavior of calling {@link #onNewIntent} this function will
3226 * return and you can handle the Intent yourself.
3227 *
3228 * <p>This function can only be called from a top-level activity; if it is
3229 * called from a child activity, a runtime exception will be thrown.
3230 *
3231 * @param intent The intent to start.
3232 * @param requestCode If >= 0, this code will be returned in
3233 * onActivityResult() when the activity exits, as described in
3234 * {@link #startActivityForResult}.
3235 *
3236 * @return If a new activity was launched then true is returned; otherwise
3237 * false is returned and you must handle the Intent yourself.
3238 *
3239 * @see #startActivity
3240 * @see #startActivityForResult
3241 */
3242 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3243 if (mParent == null) {
3244 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3245 try {
3246 result = ActivityManagerNative.getDefault()
3247 .startActivity(mMainThread.getApplicationThread(),
3248 intent, intent.resolveTypeIfNeeded(
3249 getContentResolver()),
3250 null, 0,
3251 mToken, mEmbeddedID, requestCode, true, false);
3252 } catch (RemoteException e) {
3253 // Empty
3254 }
3255
3256 Instrumentation.checkStartActivityResult(result, intent);
3257
3258 if (requestCode >= 0) {
3259 // If this start is requesting a result, we can avoid making
3260 // the activity visible until the result is received. Setting
3261 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3262 // activity hidden during this time, to avoid flickering.
3263 // This can only be done when a result is requested because
3264 // that guarantees we will get information back when the
3265 // activity is finished, no matter what happens to it.
3266 mStartedActivity = true;
3267 }
3268 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3269 }
3270
3271 throw new UnsupportedOperationException(
3272 "startActivityIfNeeded can only be called from a top-level activity");
3273 }
3274
3275 /**
3276 * Special version of starting an activity, for use when you are replacing
3277 * other activity components. You can use this to hand the Intent off
3278 * to the next Activity that can handle it. You typically call this in
3279 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3280 *
3281 * @param intent The intent to dispatch to the next activity. For
3282 * correct behavior, this must be the same as the Intent that started
3283 * your own activity; the only changes you can make are to the extras
3284 * inside of it.
3285 *
3286 * @return Returns a boolean indicating whether there was another Activity
3287 * to start: true if there was a next activity to start, false if there
3288 * wasn't. In general, if true is returned you will then want to call
3289 * finish() on yourself.
3290 */
3291 public boolean startNextMatchingActivity(Intent intent) {
3292 if (mParent == null) {
3293 try {
3294 return ActivityManagerNative.getDefault()
3295 .startNextMatchingActivity(mToken, intent);
3296 } catch (RemoteException e) {
3297 // Empty
3298 }
3299 return false;
3300 }
3301
3302 throw new UnsupportedOperationException(
3303 "startNextMatchingActivity can only be called from a top-level activity");
3304 }
3305
3306 /**
3307 * This is called when a child activity of this one calls its
3308 * {@link #startActivity} or {@link #startActivityForResult} method.
3309 *
3310 * <p>This method throws {@link android.content.ActivityNotFoundException}
3311 * if there was no Activity found to run the given Intent.
3312 *
3313 * @param child The activity making the call.
3314 * @param intent The intent to start.
3315 * @param requestCode Reply request code. < 0 if reply is not requested.
3316 *
3317 * @throws android.content.ActivityNotFoundException
3318 *
3319 * @see #startActivity
3320 * @see #startActivityForResult
3321 */
3322 public void startActivityFromChild(Activity child, Intent intent,
3323 int requestCode) {
3324 Instrumentation.ActivityResult ar =
3325 mInstrumentation.execStartActivity(
3326 this, mMainThread.getApplicationThread(), mToken, child,
3327 intent, requestCode);
3328 if (ar != null) {
3329 mMainThread.sendActivityResult(
3330 mToken, child.mEmbeddedID, requestCode,
3331 ar.getResultCode(), ar.getResultData());
3332 }
3333 }
3334
3335 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003336 * This is called when a Fragment in this activity calls its
3337 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3338 * method.
3339 *
3340 * <p>This method throws {@link android.content.ActivityNotFoundException}
3341 * if there was no Activity found to run the given Intent.
3342 *
3343 * @param fragment The fragment making the call.
3344 * @param intent The intent to start.
3345 * @param requestCode Reply request code. < 0 if reply is not requested.
3346 *
3347 * @throws android.content.ActivityNotFoundException
3348 *
3349 * @see Fragment#startActivity
3350 * @see Fragment#startActivityForResult
3351 */
3352 public void startActivityFromFragment(Fragment fragment, Intent intent,
3353 int requestCode) {
3354 Instrumentation.ActivityResult ar =
3355 mInstrumentation.execStartActivity(
3356 this, mMainThread.getApplicationThread(), mToken, fragment,
3357 intent, requestCode);
3358 if (ar != null) {
3359 mMainThread.sendActivityResult(
3360 mToken, fragment.mWho, requestCode,
3361 ar.getResultCode(), ar.getResultData());
3362 }
3363 }
3364
3365 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003366 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003367 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003368 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003369 * for more information.
3370 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003371 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3372 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3373 int extraFlags)
3374 throws IntentSender.SendIntentException {
3375 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003376 flagsMask, flagsValues, child);
3377 }
3378
3379 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003380 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3381 * or {@link #finish} to specify an explicit transition animation to
3382 * perform next.
3383 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003384 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003385 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003386 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003387 */
3388 public void overridePendingTransition(int enterAnim, int exitAnim) {
3389 try {
3390 ActivityManagerNative.getDefault().overridePendingTransition(
3391 mToken, getPackageName(), enterAnim, exitAnim);
3392 } catch (RemoteException e) {
3393 }
3394 }
3395
3396 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 * Call this to set the result that your activity will return to its
3398 * caller.
3399 *
3400 * @param resultCode The result code to propagate back to the originating
3401 * activity, often RESULT_CANCELED or RESULT_OK
3402 *
3403 * @see #RESULT_CANCELED
3404 * @see #RESULT_OK
3405 * @see #RESULT_FIRST_USER
3406 * @see #setResult(int, Intent)
3407 */
3408 public final void setResult(int resultCode) {
3409 synchronized (this) {
3410 mResultCode = resultCode;
3411 mResultData = null;
3412 }
3413 }
3414
3415 /**
3416 * Call this to set the result that your activity will return to its
3417 * caller.
3418 *
3419 * @param resultCode The result code to propagate back to the originating
3420 * activity, often RESULT_CANCELED or RESULT_OK
3421 * @param data The data to propagate back to the originating activity.
3422 *
3423 * @see #RESULT_CANCELED
3424 * @see #RESULT_OK
3425 * @see #RESULT_FIRST_USER
3426 * @see #setResult(int)
3427 */
3428 public final void setResult(int resultCode, Intent data) {
3429 synchronized (this) {
3430 mResultCode = resultCode;
3431 mResultData = data;
3432 }
3433 }
3434
3435 /**
3436 * Return the name of the package that invoked this activity. This is who
3437 * the data in {@link #setResult setResult()} will be sent to. You can
3438 * 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 The package of the activity that will receive your
3447 * reply, or null if none.
3448 */
3449 public String getCallingPackage() {
3450 try {
3451 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3452 } catch (RemoteException e) {
3453 return null;
3454 }
3455 }
3456
3457 /**
3458 * Return the name of the activity that invoked this activity. This is
3459 * who the data in {@link #setResult setResult()} will be sent to. You
3460 * can use this information to validate that the recipient is allowed to
3461 * receive the data.
3462 *
3463 * <p>Note: if the calling activity is not expecting a result (that is it
3464 * did not use the {@link #startActivityForResult}
3465 * form that includes a request code), then the calling package will be
3466 * null.
3467 *
3468 * @return String The full name of the activity that will receive your
3469 * reply, or null if none.
3470 */
3471 public ComponentName getCallingActivity() {
3472 try {
3473 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3474 } catch (RemoteException e) {
3475 return null;
3476 }
3477 }
3478
3479 /**
3480 * Control whether this activity's main window is visible. This is intended
3481 * only for the special case of an activity that is not going to show a
3482 * UI itself, but can't just finish prior to onResume() because it needs
3483 * to wait for a service binding or such. Setting this to false allows
3484 * you to prevent your UI from being shown during that time.
3485 *
3486 * <p>The default value for this is taken from the
3487 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3488 */
3489 public void setVisible(boolean visible) {
3490 if (mVisibleFromClient != visible) {
3491 mVisibleFromClient = visible;
3492 if (mVisibleFromServer) {
3493 if (visible) makeVisible();
3494 else mDecor.setVisibility(View.INVISIBLE);
3495 }
3496 }
3497 }
3498
3499 void makeVisible() {
3500 if (!mWindowAdded) {
3501 ViewManager wm = getWindowManager();
3502 wm.addView(mDecor, getWindow().getAttributes());
3503 mWindowAdded = true;
3504 }
3505 mDecor.setVisibility(View.VISIBLE);
3506 }
3507
3508 /**
3509 * Check to see whether this activity is in the process of finishing,
3510 * either because you called {@link #finish} on it or someone else
3511 * has requested that it finished. This is often used in
3512 * {@link #onPause} to determine whether the activity is simply pausing or
3513 * completely finishing.
3514 *
3515 * @return If the activity is finishing, returns true; else returns false.
3516 *
3517 * @see #finish
3518 */
3519 public boolean isFinishing() {
3520 return mFinished;
3521 }
3522
3523 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003524 * Check to see whether this activity is in the process of being destroyed in order to be
3525 * recreated with a new configuration. This is often used in
3526 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3527 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3528 *
3529 * @return If the activity is being torn down in order to be recreated with a new configuration,
3530 * returns true; else returns false.
3531 */
3532 public boolean isChangingConfigurations() {
3533 return mChangingConfigurations;
3534 }
3535
3536 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003537 * Cause this Activity to be recreated with a new instance. This results
3538 * in essentially the same flow as when the Activity is created due to
3539 * a configuration change -- the current instance will go through its
3540 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3541 */
3542 public void recreate() {
3543 if (mParent != null) {
3544 throw new IllegalStateException("Can only be called on top-level activity");
3545 }
3546 if (Looper.myLooper() != mMainThread.getLooper()) {
3547 throw new IllegalStateException("Must be called from main thread");
3548 }
3549 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3550 }
3551
3552 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 * Call this when your activity is done and should be closed. The
3554 * ActivityResult is propagated back to whoever launched you via
3555 * onActivityResult().
3556 */
3557 public void finish() {
3558 if (mParent == null) {
3559 int resultCode;
3560 Intent resultData;
3561 synchronized (this) {
3562 resultCode = mResultCode;
3563 resultData = mResultData;
3564 }
3565 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3566 try {
3567 if (ActivityManagerNative.getDefault()
3568 .finishActivity(mToken, resultCode, resultData)) {
3569 mFinished = true;
3570 }
3571 } catch (RemoteException e) {
3572 // Empty
3573 }
3574 } else {
3575 mParent.finishFromChild(this);
3576 }
3577 }
3578
3579 /**
3580 * This is called when a child activity of this one calls its
3581 * {@link #finish} method. The default implementation simply calls
3582 * finish() on this activity (the parent), finishing the entire group.
3583 *
3584 * @param child The activity making the call.
3585 *
3586 * @see #finish
3587 */
3588 public void finishFromChild(Activity child) {
3589 finish();
3590 }
3591
3592 /**
3593 * Force finish another activity that you had previously started with
3594 * {@link #startActivityForResult}.
3595 *
3596 * @param requestCode The request code of the activity that you had
3597 * given to startActivityForResult(). If there are multiple
3598 * activities started with this request code, they
3599 * will all be finished.
3600 */
3601 public void finishActivity(int requestCode) {
3602 if (mParent == null) {
3603 try {
3604 ActivityManagerNative.getDefault()
3605 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3606 } catch (RemoteException e) {
3607 // Empty
3608 }
3609 } else {
3610 mParent.finishActivityFromChild(this, requestCode);
3611 }
3612 }
3613
3614 /**
3615 * This is called when a child activity of this one calls its
3616 * finishActivity().
3617 *
3618 * @param child The activity making the call.
3619 * @param requestCode Request code that had been used to start the
3620 * activity.
3621 */
3622 public void finishActivityFromChild(Activity child, int requestCode) {
3623 try {
3624 ActivityManagerNative.getDefault()
3625 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3626 } catch (RemoteException e) {
3627 // Empty
3628 }
3629 }
3630
3631 /**
3632 * Called when an activity you launched exits, giving you the requestCode
3633 * you started it with, the resultCode it returned, and any additional
3634 * data from it. The <var>resultCode</var> will be
3635 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3636 * didn't return any result, or crashed during its operation.
3637 *
3638 * <p>You will receive this call immediately before onResume() when your
3639 * activity is re-starting.
3640 *
3641 * @param requestCode The integer request code originally supplied to
3642 * startActivityForResult(), allowing you to identify who this
3643 * result came from.
3644 * @param resultCode The integer result code returned by the child activity
3645 * through its setResult().
3646 * @param data An Intent, which can return result data to the caller
3647 * (various data can be attached to Intent "extras").
3648 *
3649 * @see #startActivityForResult
3650 * @see #createPendingResult
3651 * @see #setResult(int)
3652 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003653 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 }
3655
3656 /**
3657 * Create a new PendingIntent object which you can hand to others
3658 * for them to use to send result data back to your
3659 * {@link #onActivityResult} callback. The created object will be either
3660 * one-shot (becoming invalid after a result is sent back) or multiple
3661 * (allowing any number of results to be sent through it).
3662 *
3663 * @param requestCode Private request code for the sender that will be
3664 * associated with the result data when it is returned. The sender can not
3665 * modify this value, allowing you to identify incoming results.
3666 * @param data Default data to supply in the result, which may be modified
3667 * by the sender.
3668 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3669 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3670 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3671 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3672 * or any of the flags as supported by
3673 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3674 * of the intent that can be supplied when the actual send happens.
3675 *
3676 * @return Returns an existing or new PendingIntent matching the given
3677 * parameters. May return null only if
3678 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3679 * supplied.
3680 *
3681 * @see PendingIntent
3682 */
3683 public PendingIntent createPendingResult(int requestCode, Intent data,
3684 int flags) {
3685 String packageName = getPackageName();
3686 try {
3687 IIntentSender target =
3688 ActivityManagerNative.getDefault().getIntentSender(
3689 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3690 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003691 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 return target != null ? new PendingIntent(target) : null;
3693 } catch (RemoteException e) {
3694 // Empty
3695 }
3696 return null;
3697 }
3698
3699 /**
3700 * Change the desired orientation of this activity. If the activity
3701 * is currently in the foreground or otherwise impacting the screen
3702 * orientation, the screen will immediately be changed (possibly causing
3703 * the activity to be restarted). Otherwise, this will be used the next
3704 * time the activity is visible.
3705 *
3706 * @param requestedOrientation An orientation constant as used in
3707 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3708 */
3709 public void setRequestedOrientation(int requestedOrientation) {
3710 if (mParent == null) {
3711 try {
3712 ActivityManagerNative.getDefault().setRequestedOrientation(
3713 mToken, requestedOrientation);
3714 } catch (RemoteException e) {
3715 // Empty
3716 }
3717 } else {
3718 mParent.setRequestedOrientation(requestedOrientation);
3719 }
3720 }
3721
3722 /**
3723 * Return the current requested orientation of the activity. This will
3724 * either be the orientation requested in its component's manifest, or
3725 * the last requested orientation given to
3726 * {@link #setRequestedOrientation(int)}.
3727 *
3728 * @return Returns an orientation constant as used in
3729 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3730 */
3731 public int getRequestedOrientation() {
3732 if (mParent == null) {
3733 try {
3734 return ActivityManagerNative.getDefault()
3735 .getRequestedOrientation(mToken);
3736 } catch (RemoteException e) {
3737 // Empty
3738 }
3739 } else {
3740 return mParent.getRequestedOrientation();
3741 }
3742 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3743 }
3744
3745 /**
3746 * Return the identifier of the task this activity is in. This identifier
3747 * will remain the same for the lifetime of the activity.
3748 *
3749 * @return Task identifier, an opaque integer.
3750 */
3751 public int getTaskId() {
3752 try {
3753 return ActivityManagerNative.getDefault()
3754 .getTaskForActivity(mToken, false);
3755 } catch (RemoteException e) {
3756 return -1;
3757 }
3758 }
3759
3760 /**
3761 * Return whether this activity is the root of a task. The root is the
3762 * first activity in a task.
3763 *
3764 * @return True if this is the root activity, else false.
3765 */
3766 public boolean isTaskRoot() {
3767 try {
3768 return ActivityManagerNative.getDefault()
3769 .getTaskForActivity(mToken, true) >= 0;
3770 } catch (RemoteException e) {
3771 return false;
3772 }
3773 }
3774
3775 /**
3776 * Move the task containing this activity to the back of the activity
3777 * stack. The activity's order within the task is unchanged.
3778 *
3779 * @param nonRoot If false then this only works if the activity is the root
3780 * of a task; if true it will work for any activity in
3781 * a task.
3782 *
3783 * @return If the task was moved (or it was already at the
3784 * back) true is returned, else false.
3785 */
3786 public boolean moveTaskToBack(boolean nonRoot) {
3787 try {
3788 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3789 mToken, nonRoot);
3790 } catch (RemoteException e) {
3791 // Empty
3792 }
3793 return false;
3794 }
3795
3796 /**
3797 * Returns class name for this activity with the package prefix removed.
3798 * This is the default name used to read and write settings.
3799 *
3800 * @return The local class name.
3801 */
3802 public String getLocalClassName() {
3803 final String pkg = getPackageName();
3804 final String cls = mComponent.getClassName();
3805 int packageLen = pkg.length();
3806 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3807 || cls.charAt(packageLen) != '.') {
3808 return cls;
3809 }
3810 return cls.substring(packageLen+1);
3811 }
3812
3813 /**
3814 * Returns complete component name of this activity.
3815 *
3816 * @return Returns the complete component name for this activity
3817 */
3818 public ComponentName getComponentName()
3819 {
3820 return mComponent;
3821 }
3822
3823 /**
3824 * Retrieve a {@link SharedPreferences} object for accessing preferences
3825 * that are private to this activity. This simply calls the underlying
3826 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3827 * class name as the preferences name.
3828 *
3829 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3830 * operation, {@link #MODE_WORLD_READABLE} and
3831 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3832 *
3833 * @return Returns the single SharedPreferences instance that can be used
3834 * to retrieve and modify the preference values.
3835 */
3836 public SharedPreferences getPreferences(int mode) {
3837 return getSharedPreferences(getLocalClassName(), mode);
3838 }
3839
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003840 private void ensureSearchManager() {
3841 if (mSearchManager != null) {
3842 return;
3843 }
3844
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003845 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003846 }
3847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 @Override
3849 public Object getSystemService(String name) {
3850 if (getBaseContext() == null) {
3851 throw new IllegalStateException(
3852 "System services not available to Activities before onCreate()");
3853 }
3854
3855 if (WINDOW_SERVICE.equals(name)) {
3856 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003857 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003858 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003859 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
3861 return super.getSystemService(name);
3862 }
3863
3864 /**
3865 * Change the title associated with this activity. If this is a
3866 * top-level activity, the title for its window will change. If it
3867 * is an embedded activity, the parent can do whatever it wants
3868 * with it.
3869 */
3870 public void setTitle(CharSequence title) {
3871 mTitle = title;
3872 onTitleChanged(title, mTitleColor);
3873
3874 if (mParent != null) {
3875 mParent.onChildTitleChanged(this, title);
3876 }
3877 }
3878
3879 /**
3880 * Change the title associated with this activity. If this is a
3881 * top-level activity, the title for its window will change. If it
3882 * is an embedded activity, the parent can do whatever it wants
3883 * with it.
3884 */
3885 public void setTitle(int titleId) {
3886 setTitle(getText(titleId));
3887 }
3888
3889 public void setTitleColor(int textColor) {
3890 mTitleColor = textColor;
3891 onTitleChanged(mTitle, textColor);
3892 }
3893
3894 public final CharSequence getTitle() {
3895 return mTitle;
3896 }
3897
3898 public final int getTitleColor() {
3899 return mTitleColor;
3900 }
3901
3902 protected void onTitleChanged(CharSequence title, int color) {
3903 if (mTitleReady) {
3904 final Window win = getWindow();
3905 if (win != null) {
3906 win.setTitle(title);
3907 if (color != 0) {
3908 win.setTitleColor(color);
3909 }
3910 }
3911 }
3912 }
3913
3914 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3915 }
3916
3917 /**
3918 * Sets the visibility of the progress bar in the title.
3919 * <p>
3920 * In order for the progress bar to be shown, the feature must be requested
3921 * via {@link #requestWindowFeature(int)}.
3922 *
3923 * @param visible Whether to show the progress bars in the title.
3924 */
3925 public final void setProgressBarVisibility(boolean visible) {
3926 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3927 Window.PROGRESS_VISIBILITY_OFF);
3928 }
3929
3930 /**
3931 * Sets the visibility of the indeterminate progress bar in the title.
3932 * <p>
3933 * In order for the progress bar to be shown, the feature must be requested
3934 * via {@link #requestWindowFeature(int)}.
3935 *
3936 * @param visible Whether to show the progress bars in the title.
3937 */
3938 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3939 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3940 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3941 }
3942
3943 /**
3944 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3945 * is always indeterminate).
3946 * <p>
3947 * In order for the progress bar to be shown, the feature must be requested
3948 * via {@link #requestWindowFeature(int)}.
3949 *
3950 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3951 */
3952 public final void setProgressBarIndeterminate(boolean indeterminate) {
3953 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3954 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3955 }
3956
3957 /**
3958 * Sets the progress for the progress bars in the title.
3959 * <p>
3960 * In order for the progress bar to be shown, the feature must be requested
3961 * via {@link #requestWindowFeature(int)}.
3962 *
3963 * @param progress The progress for the progress bar. Valid ranges are from
3964 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3965 * bar will be completely filled and will fade out.
3966 */
3967 public final void setProgress(int progress) {
3968 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3969 }
3970
3971 /**
3972 * Sets the secondary progress for the progress bar in the title. This
3973 * progress is drawn between the primary progress (set via
3974 * {@link #setProgress(int)} and the background. It can be ideal for media
3975 * scenarios such as showing the buffering progress while the default
3976 * progress shows the play progress.
3977 * <p>
3978 * In order for the progress bar to be shown, the feature must be requested
3979 * via {@link #requestWindowFeature(int)}.
3980 *
3981 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3982 * 0 to 10000 (both inclusive).
3983 */
3984 public final void setSecondaryProgress(int secondaryProgress) {
3985 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3986 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3987 }
3988
3989 /**
3990 * Suggests an audio stream whose volume should be changed by the hardware
3991 * volume controls.
3992 * <p>
3993 * The suggested audio stream will be tied to the window of this Activity.
3994 * If the Activity is switched, the stream set here is no longer the
3995 * suggested stream. The client does not need to save and restore the old
3996 * suggested stream value in onPause and onResume.
3997 *
3998 * @param streamType The type of the audio stream whose volume should be
3999 * changed by the hardware volume controls. It is not guaranteed that
4000 * the hardware volume controls will always change this stream's
4001 * volume (for example, if a call is in progress, its stream's volume
4002 * may be changed instead). To reset back to the default, use
4003 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
4004 */
4005 public final void setVolumeControlStream(int streamType) {
4006 getWindow().setVolumeControlStream(streamType);
4007 }
4008
4009 /**
4010 * Gets the suggested audio stream whose volume should be changed by the
4011 * harwdare volume controls.
4012 *
4013 * @return The suggested audio stream type whose volume should be changed by
4014 * the hardware volume controls.
4015 * @see #setVolumeControlStream(int)
4016 */
4017 public final int getVolumeControlStream() {
4018 return getWindow().getVolumeControlStream();
4019 }
4020
4021 /**
4022 * Runs the specified action on the UI thread. If the current thread is the UI
4023 * thread, then the action is executed immediately. If the current thread is
4024 * not the UI thread, the action is posted to the event queue of the UI thread.
4025 *
4026 * @param action the action to run on the UI thread
4027 */
4028 public final void runOnUiThread(Runnable action) {
4029 if (Thread.currentThread() != mUiThread) {
4030 mHandler.post(action);
4031 } else {
4032 action.run();
4033 }
4034 }
4035
4036 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004037 * Standard implementation of
4038 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4039 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004040 * This implementation does nothing and is for
4041 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4042 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4043 *
4044 * @see android.view.LayoutInflater#createView
4045 * @see android.view.Window#getLayoutInflater
4046 */
4047 public View onCreateView(String name, Context context, AttributeSet attrs) {
4048 return null;
4049 }
4050
4051 /**
4052 * Standard implementation of
4053 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4054 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004055 * This implementation handles <fragment> tags to embed fragments inside
4056 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 *
4058 * @see android.view.LayoutInflater#createView
4059 * @see android.view.Window#getLayoutInflater
4060 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004061 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004062 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004063 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004064 }
4065
Dianne Hackborndef15372010-08-15 12:43:52 -07004066 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004067 TypedArray a =
4068 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004069 if (fname == null) {
4070 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4071 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004072 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004073 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4074 a.recycle();
4075
Dianne Hackborn625ac272010-09-17 18:29:22 -07004076 int containerId = parent != null ? parent.getId() : 0;
4077 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004078 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004079 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004080 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004081
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004082 // If we restored from a previous state, we may already have
4083 // instantiated this fragment from the state and should use
4084 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004085 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4086 if (fragment == null && tag != null) {
4087 fragment = mFragments.findFragmentByTag(tag);
4088 }
4089 if (fragment == null && containerId != View.NO_ID) {
4090 fragment = mFragments.findFragmentById(containerId);
4091 }
4092
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004093 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4094 + Integer.toHexString(id) + " fname=" + fname
4095 + " existing=" + fragment);
4096 if (fragment == null) {
4097 fragment = Fragment.instantiate(this, fname);
4098 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004099 fragment.mFragmentId = id != 0 ? id : containerId;
4100 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004101 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004102 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004103 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004104 fragment.mFragmentManager = mFragments;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004105 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4106 mFragments.addFragment(fragment, true);
4107
4108 } else if (fragment.mInLayout) {
4109 // A fragment already exists and it is not one we restored from
4110 // previous state.
4111 throw new IllegalArgumentException(attrs.getPositionDescription()
4112 + ": Duplicate id 0x" + Integer.toHexString(id)
4113 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4114 + " with another fragment for " + fname);
4115 } else {
4116 // This fragment was retained from a previous instance; get it
4117 // going now.
4118 fragment.mInLayout = true;
4119 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004120 // If this fragment is newly instantiated (either right now, or
4121 // from last saved state), then give it the attributes to
4122 // initialize itself.
4123 if (!fragment.mRetaining) {
4124 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4125 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004126 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004127 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004128
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004129 if (fragment.mView == null) {
4130 throw new IllegalStateException("Fragment " + fname
4131 + " did not create a view.");
4132 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004133 if (id != 0) {
4134 fragment.mView.setId(id);
4135 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004136 if (fragment.mView.getTag() == null) {
4137 fragment.mView.setTag(tag);
4138 }
4139 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 }
4141
Daniel Sandler69a48172010-06-23 16:29:36 -04004142 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004143 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004144 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004145 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004146 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004147 * @param fd The raw file descriptor that the dump is being sent to.
4148 * @param writer The PrintWriter to which you should dump your state. This will be
4149 * closed for you after you return.
4150 * @param args additional arguments to the dump request.
4151 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004152 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4153 writer.print(prefix); writer.print("Local Activity ");
4154 writer.print(Integer.toHexString(System.identityHashCode(this)));
4155 writer.println(" State:");
4156 String innerPrefix = prefix + " ";
4157 writer.print(innerPrefix); writer.print("mResumed=");
4158 writer.print(mResumed); writer.print(" mStopped=");
4159 writer.print(mStopped); writer.print(" mFinished=");
4160 writer.println(mFinished);
4161 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4162 writer.println(mLoadersStarted);
4163 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4164 writer.println(mChangingConfigurations);
4165 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4166 writer.println(mCurrentConfig);
4167 if (mLoaderManager != null) {
4168 writer.print(prefix); writer.print("Loader Manager ");
4169 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4170 writer.println(":");
4171 mLoaderManager.dump(prefix + " ", fd, writer, args);
4172 }
4173 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004174 }
4175
4176 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004177 * Bit indicating that this activity is "immersive" and should not be
4178 * interrupted by notifications if possible.
4179 *
4180 * This value is initially set by the manifest property
4181 * <code>android:immersive</code> but may be changed at runtime by
4182 * {@link #setImmersive}.
4183 *
4184 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004185 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004186 */
4187 public boolean isImmersive() {
4188 try {
4189 return ActivityManagerNative.getDefault().isImmersive(mToken);
4190 } catch (RemoteException e) {
4191 return false;
4192 }
4193 }
4194
4195 /**
4196 * Adjust the current immersive mode setting.
4197 *
4198 * Note that changing this value will have no effect on the activity's
4199 * {@link android.content.pm.ActivityInfo} structure; that is, if
4200 * <code>android:immersive</code> is set to <code>true</code>
4201 * in the application's manifest entry for this activity, the {@link
4202 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4203 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4204 * FLAG_IMMERSIVE} bit set.
4205 *
4206 * @see #isImmersive
4207 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004208 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004209 */
4210 public void setImmersive(boolean i) {
4211 try {
4212 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4213 } catch (RemoteException e) {
4214 // pass
4215 }
4216 }
4217
Adam Powell6e346362010-07-23 10:18:23 -07004218 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004219 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004220 *
4221 * @param callback Callback that will manage lifecycle events for this context mode
4222 * @return The ContextMode that was started, or null if it was canceled
4223 *
4224 * @see ActionMode
4225 */
Adam Powell5d279772010-07-27 16:34:07 -07004226 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004227 return mWindow.getDecorView().startActionMode(callback);
4228 }
4229
Adam Powelldebf3be2010-11-15 18:58:48 -08004230 /**
4231 * Give the Activity a chance to control the UI for an action mode requested
4232 * by the system.
4233 *
4234 * <p>Note: If you are looking for a notification callback that an action mode
4235 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4236 *
4237 * @param callback The callback that should control the new action mode
4238 * @return The new action mode, or <code>null</code> if the activity does not want to
4239 * provide special handling for this action mode. (It will be handled by the system.)
4240 */
4241 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004242 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004243 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004244 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004245 }
4246 return null;
4247 }
4248
Adam Powelldebf3be2010-11-15 18:58:48 -08004249 /**
4250 * Notifies the Activity that an action mode has been started.
4251 * Activity subclasses overriding this method should call the superclass implementation.
4252 *
4253 * @param mode The new action mode.
4254 */
4255 public void onActionModeStarted(ActionMode mode) {
4256 }
4257
4258 /**
4259 * Notifies the activity that an action mode has finished.
4260 * Activity subclasses overriding this method should call the superclass implementation.
4261 *
4262 * @param mode The action mode that just finished.
4263 */
4264 public void onActionModeFinished(ActionMode mode) {
4265 }
4266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 // ------------------ Internal API ------------------
4268
4269 final void setParent(Activity parent) {
4270 mParent = parent;
4271 }
4272
4273 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4274 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004275 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004277 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004278 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 }
4280
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004281 final void attach(Context context, ActivityThread aThread,
4282 Instrumentation instr, IBinder token, int ident,
4283 Application application, Intent intent, ActivityInfo info,
4284 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004285 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004286 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 attachBaseContext(context);
4288
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004289 mFragments.attachActivity(this);
4290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 mWindow = PolicyManager.makeNewWindow(this);
4292 mWindow.setCallback(this);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004293 mWindow.getLayoutInflater().setFactory2(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4295 mWindow.setSoftInputMode(info.softInputMode);
4296 }
4297 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 mMainThread = aThread;
4300 mInstrumentation = instr;
4301 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004302 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 mApplication = application;
4304 mIntent = intent;
4305 mComponent = intent.getComponent();
4306 mActivityInfo = info;
4307 mTitle = title;
4308 mParent = parent;
4309 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004310 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311
Romain Guy529b60a2010-08-03 18:05:47 -07004312 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4313 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 if (mParent != null) {
4315 mWindow.setContainer(mParent.getWindow());
4316 }
4317 mWindowManager = mWindow.getWindowManager();
4318 mCurrentConfig = config;
4319 }
4320
4321 final IBinder getActivityToken() {
4322 return mParent != null ? mParent.getActivityToken() : mToken;
4323 }
4324
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004325 final void performCreate(Bundle icicle) {
4326 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004327 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4328 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004329 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004330 }
4331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004333 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004335 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 mInstrumentation.callActivityOnStart(this);
4337 if (!mCalled) {
4338 throw new SuperNotCalledException(
4339 "Activity " + mComponent.toShortString() +
4340 " did not call through to super.onStart()");
4341 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004342 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004343 if (mAllLoaderManagers != null) {
4344 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4345 mAllLoaderManagers.valueAt(i).finishRetain();
4346 }
4347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 }
4349
4350 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004351 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004352
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004353 synchronized (mManagedCursors) {
4354 final int N = mManagedCursors.size();
4355 for (int i=0; i<N; i++) {
4356 ManagedCursor mc = mManagedCursors.get(i);
4357 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004358 if (!mc.mCursor.requery()) {
4359 throw new IllegalStateException(
4360 "trying to requery an already closed cursor");
4361 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004362 mc.mReleased = false;
4363 mc.mUpdated = false;
4364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 }
4366 }
4367
4368 if (mStopped) {
4369 mStopped = false;
4370 mCalled = false;
4371 mInstrumentation.callActivityOnRestart(this);
4372 if (!mCalled) {
4373 throw new SuperNotCalledException(
4374 "Activity " + mComponent.toShortString() +
4375 " did not call through to super.onRestart()");
4376 }
4377 performStart();
4378 }
4379 }
4380
4381 final void performResume() {
4382 performRestart();
4383
Dianne Hackborn445646c2010-06-25 15:52:59 -07004384 mFragments.execPendingActions();
4385
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004386 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06004389 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 mInstrumentation.callActivityOnResume(this);
4391 if (!mCalled) {
4392 throw new SuperNotCalledException(
4393 "Activity " + mComponent.toShortString() +
4394 " did not call through to super.onResume()");
4395 }
4396
4397 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004399
4400 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004401 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 onPostResume();
4404 if (!mCalled) {
4405 throw new SuperNotCalledException(
4406 "Activity " + mComponent.toShortString() +
4407 " did not call through to super.onPostResume()");
4408 }
4409 }
4410
4411 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004412 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004413 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 onPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004415 if (!mCalled && getApplicationInfo().targetSdkVersion
4416 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4417 throw new SuperNotCalledException(
4418 "Activity " + mComponent.toShortString() +
4419 " did not call through to super.onPause()");
4420 }
Jeff Hamilton52d32032011-01-08 15:31:26 -06004421 mResumed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 }
4423
4424 final void performUserLeaving() {
4425 onUserInteraction();
4426 onUserLeaveHint();
4427 }
4428
4429 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004430 if (mLoadersStarted) {
4431 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004432 if (mLoaderManager != null) {
4433 if (!mChangingConfigurations) {
4434 mLoaderManager.doStop();
4435 } else {
4436 mLoaderManager.doRetain();
4437 }
4438 }
4439 }
4440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 if (!mStopped) {
4442 if (mWindow != null) {
4443 mWindow.closeAllPanels();
4444 }
4445
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004446 mFragments.dispatchStop();
4447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 mCalled = false;
4449 mInstrumentation.callActivityOnStop(this);
4450 if (!mCalled) {
4451 throw new SuperNotCalledException(
4452 "Activity " + mComponent.toShortString() +
4453 " did not call through to super.onStop()");
4454 }
4455
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004456 synchronized (mManagedCursors) {
4457 final int N = mManagedCursors.size();
4458 for (int i=0; i<N; i++) {
4459 ManagedCursor mc = mManagedCursors.get(i);
4460 if (!mc.mReleased) {
4461 mc.mCursor.deactivate();
4462 mc.mReleased = true;
4463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 }
4465 }
4466
4467 mStopped = true;
4468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 }
4470
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004471 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004472 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004473 mFragments.dispatchDestroy();
4474 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004475 if (mLoaderManager != null) {
4476 mLoaderManager.doDestroy();
4477 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004478 }
4479
Jeff Hamilton52d32032011-01-08 15:31:26 -06004480 /**
4481 * @hide
4482 */
4483 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 return mResumed;
4485 }
4486
4487 void dispatchActivityResult(String who, int requestCode,
4488 int resultCode, Intent data) {
4489 if (Config.LOGV) Log.v(
4490 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4491 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004492 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 if (who == null) {
4494 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004495 } else {
4496 Fragment frag = mFragments.findFragmentByWho(who);
4497 if (frag != null) {
4498 frag.onActivityResult(requestCode, resultCode, data);
4499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
4501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502}