blob: 938c47dc4d1530b17cabd8583ec961d3e955a11f [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;
Jim Miller0b2a6d02010-07-13 18:01:29 -070076import android.widget.FrameLayout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
Dianne Hackborn625ac272010-09-17 18:29:22 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
Adam Powell6e346362010-07-23 10:18:23 -070080import java.util.ArrayList;
81import java.util.HashMap;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -080082import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84/**
85 * An activity is a single, focused thing that the user can do. Almost all
86 * activities interact with the user, so the Activity class takes care of
87 * creating a window for you in which you can place your UI with
88 * {@link #setContentView}. While activities are often presented to the user
89 * as full-screen windows, they can also be used in other ways: as floating
90 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
91 * or embedded inside of another activity (using {@link ActivityGroup}).
92 *
93 * There are two methods almost all subclasses of Activity will implement:
94 *
95 * <ul>
96 * <li> {@link #onCreate} is where you initialize your activity. Most
97 * importantly, here you will usually call {@link #setContentView(int)}
98 * with a layout resource defining your UI, and using {@link #findViewById}
99 * to retrieve the widgets in that UI that you need to interact with
100 * programmatically.
101 *
102 * <li> {@link #onPause} is where you deal with the user leaving your
103 * activity. Most importantly, any changes made by the user should at this
104 * point be committed (usually to the
105 * {@link android.content.ContentProvider} holding the data).
106 * </ul>
107 *
108 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
109 * activity classes must have a corresponding
110 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
111 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
112 *
113 * <p>The Activity class is an important part of an application's overall lifecycle,
114 * and the way activities are launched and put together is a fundamental
115 * part of the platform's application model. For a detailed perspective on the structure of
116 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
117 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
118 *
119 * <p>Topics covered here:
120 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700121 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
123 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
124 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
125 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
126 * <li><a href="#Permissions">Permissions</a>
127 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
128 * </ol>
129 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700130 * <a name="Fragments"></a>
131 * <h3>Fragments</h3>
132 *
133 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
134 * implementations can make use of the {@link Fragment} class to better
135 * modularize their code, build more sophisticated user interfaces for larger
136 * screens, and help scale their application between small and large screens.
137 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 * <a name="ActivityLifecycle"></a>
139 * <h3>Activity Lifecycle</h3>
140 *
141 * <p>Activities in the system are managed as an <em>activity stack</em>.
142 * When a new activity is started, it is placed on the top of the stack
143 * and becomes the running activity -- the previous activity always remains
144 * below it in the stack, and will not come to the foreground again until
145 * the new activity exits.</p>
146 *
147 * <p>An activity has essentially four states:</p>
148 * <ul>
149 * <li> If an activity in the foreground of the screen (at the top of
150 * the stack),
151 * it is <em>active</em> or <em>running</em>. </li>
152 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
153 * or transparent activity has focus on top of your activity), it
154 * is <em>paused</em>. A paused activity is completely alive (it
155 * maintains all state and member information and remains attached to
156 * the window manager), but can be killed by the system in extreme
157 * low memory situations.
158 * <li>If an activity is completely obscured by another activity,
159 * it is <em>stopped</em>. It still retains all state and member information,
160 * however, it is no longer visible to the user so its window is hidden
161 * and it will often be killed by the system when memory is needed
162 * elsewhere.</li>
163 * <li>If an activity is paused or stopped, the system can drop the activity
164 * from memory by either asking it to finish, or simply killing its
165 * process. When it is displayed again to the user, it must be
166 * completely restarted and restored to its previous state.</li>
167 * </ul>
168 *
169 * <p>The following diagram shows the important state paths of an Activity.
170 * The square rectangles represent callback methods you can implement to
171 * perform operations when the Activity moves between states. The colored
172 * ovals are major states the Activity can be in.</p>
173 *
174 * <p><img src="../../../images/activity_lifecycle.png"
175 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
176 *
177 * <p>There are three key loops you may be interested in monitoring within your
178 * activity:
179 *
180 * <ul>
181 * <li>The <b>entire lifetime</b> of an activity happens between the first call
182 * to {@link android.app.Activity#onCreate} through to a single final call
183 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
184 * of "global" state in onCreate(), and release all remaining resources in
185 * onDestroy(). For example, if it has a thread running in the background
186 * to download data from the network, it may create that thread in onCreate()
187 * and then stop the thread in onDestroy().
188 *
189 * <li>The <b>visible lifetime</b> of an activity happens between a call to
190 * {@link android.app.Activity#onStart} until a corresponding call to
191 * {@link android.app.Activity#onStop}. During this time the user can see the
192 * activity on-screen, though it may not be in the foreground and interacting
193 * with the user. Between these two methods you can maintain resources that
194 * are needed to show the activity to the user. For example, you can register
195 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
196 * that impact your UI, and unregister it in onStop() when the user an no
197 * longer see what you are displaying. The onStart() and onStop() methods
198 * can be called multiple times, as the activity becomes visible and hidden
199 * to the user.
200 *
201 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
202 * {@link android.app.Activity#onResume} until a corresponding call to
203 * {@link android.app.Activity#onPause}. During this time the activity is
204 * in front of all other activities and interacting with the user. An activity
205 * can frequently go between the resumed and paused states -- for example when
206 * the device goes to sleep, when an activity result is delivered, when a new
207 * intent is delivered -- so the code in these methods should be fairly
208 * lightweight.
209 * </ul>
210 *
211 * <p>The entire lifecycle of an activity is defined by the following
212 * Activity methods. All of these are hooks that you can override
213 * to do appropriate work when the activity changes state. All
214 * activities will implement {@link android.app.Activity#onCreate}
215 * to do their initial setup; many will also implement
216 * {@link android.app.Activity#onPause} to commit changes to data and
217 * otherwise prepare to stop interacting with the user. You should always
218 * call up to your superclass when implementing these methods.</p>
219 *
220 * </p>
221 * <pre class="prettyprint">
222 * public class Activity extends ApplicationContext {
223 * protected void onCreate(Bundle savedInstanceState);
224 *
225 * protected void onStart();
226 *
227 * protected void onRestart();
228 *
229 * protected void onResume();
230 *
231 * protected void onPause();
232 *
233 * protected void onStop();
234 *
235 * protected void onDestroy();
236 * }
237 * </pre>
238 *
239 * <p>In general the movement through an activity's lifecycle looks like
240 * this:</p>
241 *
242 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
243 * <colgroup align="left" span="3" />
244 * <colgroup align="left" />
245 * <colgroup align="center" />
246 * <colgroup align="center" />
247 *
248 * <thead>
249 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
250 * </thead>
251 *
252 * <tbody>
253 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
254 * <td>Called when the activity is first created.
255 * This is where you should do all of your normal static set up:
256 * create views, bind data to lists, etc. This method also
257 * provides you with a Bundle containing the activity's previously
258 * frozen state, if there was one.
259 * <p>Always followed by <code>onStart()</code>.</td>
260 * <td align="center">No</td>
261 * <td align="center"><code>onStart()</code></td>
262 * </tr>
263 *
264 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
265 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
266 * <td>Called after your activity has been stopped, prior to it being
267 * started again.
268 * <p>Always followed by <code>onStart()</code></td>
269 * <td align="center">No</td>
270 * <td align="center"><code>onStart()</code></td>
271 * </tr>
272 *
273 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
274 * <td>Called when the activity is becoming visible to the user.
275 * <p>Followed by <code>onResume()</code> if the activity comes
276 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
277 * <td align="center">No</td>
278 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
279 * </tr>
280 *
281 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
282 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
283 * <td>Called when the activity will start
284 * interacting with the user. At this point your activity is at
285 * the top of the activity stack, with user input going to it.
286 * <p>Always followed by <code>onPause()</code>.</td>
287 * <td align="center">No</td>
288 * <td align="center"><code>onPause()</code></td>
289 * </tr>
290 *
291 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
292 * <td>Called when the system is about to start resuming a previous
293 * activity. This is typically used to commit unsaved changes to
294 * persistent data, stop animations and other things that may be consuming
295 * CPU, etc. Implementations of this method must be very quick because
296 * the next activity will not be resumed until this method returns.
297 * <p>Followed by either <code>onResume()</code> if the activity
298 * returns back to the front, or <code>onStop()</code> if it becomes
299 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800300 * <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 -0800301 * <td align="center"><code>onResume()</code> or<br>
302 * <code>onStop()</code></td>
303 * </tr>
304 *
305 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
306 * <td>Called when the activity is no longer visible to the user, because
307 * another activity has been resumed and is covering this one. This
308 * may happen either because a new activity is being started, an existing
309 * one is being brought in front of this one, or this one is being
310 * destroyed.
311 * <p>Followed by either <code>onRestart()</code> if
312 * this activity is coming back to interact with the user, or
313 * <code>onDestroy()</code> if this activity is going away.</td>
314 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
315 * <td align="center"><code>onRestart()</code> or<br>
316 * <code>onDestroy()</code></td>
317 * </tr>
318 *
319 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
320 * <td>The final call you receive before your
321 * activity is destroyed. This can happen either because the
322 * activity is finishing (someone called {@link Activity#finish} on
323 * it, or because the system is temporarily destroying this
324 * instance of the activity to save space. You can distinguish
325 * between these two scenarios with the {@link
326 * Activity#isFinishing} method.</td>
327 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
328 * <td align="center"><em>nothing</em></td>
329 * </tr>
330 * </tbody>
331 * </table>
332 *
333 * <p>Note the "Killable" column in the above table -- for those methods that
334 * are marked as being killable, after that method returns the process hosting the
335 * activity may killed by the system <em>at any time</em> without another line
336 * of its code being executed. Because of this, you should use the
337 * {@link #onPause} method to write any persistent data (such as user edits)
338 * to storage. In addition, the method
339 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
340 * in such a background state, allowing you to save away any dynamic instance
341 * state in your activity into the given Bundle, to be later received in
342 * {@link #onCreate} if the activity needs to be re-created.
343 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
344 * section for more information on how the lifecycle of a process is tied
345 * to the activities it is hosting. Note that it is important to save
346 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
347 * because the later is not part of the lifecycle callbacks, so will not
348 * be called in every situation as described in its documentation.</p>
349 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800350 * <p class="note">Be aware that these semantics will change slightly between
351 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
352 * vs. those targeting prior platforms. Starting with Honeycomb, an application
353 * is not in the killable state until its {@link #onStop} has returned. This
354 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
355 * safely called after {@link #onPause()} and allows and application to safely
356 * wait until {@link #onStop()} to save persistent state.</p>
357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * <p>For those methods that are not marked as being killable, the activity's
359 * process will not be killed by the system starting from the time the method
360 * is called and continuing after it returns. Thus an activity is in the killable
361 * state, for example, between after <code>onPause()</code> to the start of
362 * <code>onResume()</code>.</p>
363 *
364 * <a name="ConfigurationChanges"></a>
365 * <h3>Configuration Changes</h3>
366 *
367 * <p>If the configuration of the device (as defined by the
368 * {@link Configuration Resources.Configuration} class) changes,
369 * then anything displaying a user interface will need to update to match that
370 * configuration. Because Activity is the primary mechanism for interacting
371 * with the user, it includes special support for handling configuration
372 * changes.</p>
373 *
374 * <p>Unless you specify otherwise, a configuration change (such as a change
375 * in screen orientation, language, input devices, etc) will cause your
376 * current activity to be <em>destroyed</em>, going through the normal activity
377 * lifecycle process of {@link #onPause},
378 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
379 * had been in the foreground or visible to the user, once {@link #onDestroy} is
380 * called in that instance then a new instance of the activity will be
381 * created, with whatever savedInstanceState the previous instance had generated
382 * from {@link #onSaveInstanceState}.</p>
383 *
384 * <p>This is done because any application resource,
385 * including layout files, can change based on any configuration value. Thus
386 * the only safe way to handle a configuration change is to re-retrieve all
387 * resources, including layouts, drawables, and strings. Because activities
388 * must already know how to save their state and re-create themselves from
389 * that state, this is a convenient way to have an activity restart itself
390 * with a new configuration.</p>
391 *
392 * <p>In some special cases, you may want to bypass restarting of your
393 * activity based on one or more types of configuration changes. This is
394 * done with the {@link android.R.attr#configChanges android:configChanges}
395 * attribute in its manifest. For any types of configuration changes you say
396 * that you handle there, you will receive a call to your current activity's
397 * {@link #onConfigurationChanged} method instead of being restarted. If
398 * a configuration change involves any that you do not handle, however, the
399 * activity will still be restarted and {@link #onConfigurationChanged}
400 * will not be called.</p>
401 *
402 * <a name="StartingActivities"></a>
403 * <h3>Starting Activities and Getting Results</h3>
404 *
405 * <p>The {@link android.app.Activity#startActivity}
406 * method is used to start a
407 * new activity, which will be placed at the top of the activity stack. It
408 * takes a single argument, an {@link android.content.Intent Intent},
409 * which describes the activity
410 * to be executed.</p>
411 *
412 * <p>Sometimes you want to get a result back from an activity when it
413 * ends. For example, you may start an activity that lets the user pick
414 * a person in a list of contacts; when it ends, it returns the person
415 * that was selected. To do this, you call the
416 * {@link android.app.Activity#startActivityForResult(Intent, int)}
417 * version with a second integer parameter identifying the call. The result
418 * will come back through your {@link android.app.Activity#onActivityResult}
419 * method.</p>
420 *
421 * <p>When an activity exits, it can call
422 * {@link android.app.Activity#setResult(int)}
423 * to return data back to its parent. It must always supply a result code,
424 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
425 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
426 * return back an Intent containing any additional data it wants. All of this
427 * information appears back on the
428 * parent's <code>Activity.onActivityResult()</code>, along with the integer
429 * identifier it originally supplied.</p>
430 *
431 * <p>If a child activity fails for any reason (such as crashing), the parent
432 * activity will receive a result with the code RESULT_CANCELED.</p>
433 *
434 * <pre class="prettyprint">
435 * public class MyActivity extends Activity {
436 * ...
437 *
438 * static final int PICK_CONTACT_REQUEST = 0;
439 *
440 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
441 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
442 * // When the user center presses, let them pick a contact.
443 * startActivityForResult(
444 * new Intent(Intent.ACTION_PICK,
445 * new Uri("content://contacts")),
446 * PICK_CONTACT_REQUEST);
447 * return true;
448 * }
449 * return false;
450 * }
451 *
452 * protected void onActivityResult(int requestCode, int resultCode,
453 * Intent data) {
454 * if (requestCode == PICK_CONTACT_REQUEST) {
455 * if (resultCode == RESULT_OK) {
456 * // A contact was picked. Here we will just display it
457 * // to the user.
458 * startActivity(new Intent(Intent.ACTION_VIEW, data));
459 * }
460 * }
461 * }
462 * }
463 * </pre>
464 *
465 * <a name="SavingPersistentState"></a>
466 * <h3>Saving Persistent State</h3>
467 *
468 * <p>There are generally two kinds of persistent state than an activity
469 * will deal with: shared document-like data (typically stored in a SQLite
470 * database using a {@linkplain android.content.ContentProvider content provider})
471 * and internal state such as user preferences.</p>
472 *
473 * <p>For content provider data, we suggest that activities use a
474 * "edit in place" user model. That is, any edits a user makes are effectively
475 * made immediately without requiring an additional confirmation step.
476 * Supporting this model is generally a simple matter of following two rules:</p>
477 *
478 * <ul>
479 * <li> <p>When creating a new document, the backing database entry or file for
480 * it is created immediately. For example, if the user chooses to write
481 * a new e-mail, a new entry for that e-mail is created as soon as they
482 * start entering data, so that if they go to any other activity after
483 * that point this e-mail will now appear in the list of drafts.</p>
484 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
485 * commit to the backing content provider or file any changes the user
486 * has made. This ensures that those changes will be seen by any other
487 * activity that is about to run. You will probably want to commit
488 * your data even more aggressively at key times during your
489 * activity's lifecycle: for example before starting a new
490 * activity, before finishing your own activity, when the user
491 * switches between input fields, etc.</p>
492 * </ul>
493 *
494 * <p>This model is designed to prevent data loss when a user is navigating
495 * between activities, and allows the system to safely kill an activity (because
496 * system resources are needed somewhere else) at any time after it has been
497 * paused. Note this implies
498 * that the user pressing BACK from your activity does <em>not</em>
499 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800500 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
502 *
503 * <p>See the {@linkplain android.content.ContentProvider content package} for
504 * more information about content providers. These are a key aspect of how
505 * different activities invoke and propagate data between themselves.</p>
506 *
507 * <p>The Activity class also provides an API for managing internal persistent state
508 * associated with an activity. This can be used, for example, to remember
509 * the user's preferred initial display in a calendar (day view or week view)
510 * or the user's default home page in a web browser.</p>
511 *
512 * <p>Activity persistent state is managed
513 * with the method {@link #getPreferences},
514 * allowing you to retrieve and
515 * modify a set of name/value pairs associated with the activity. To use
516 * preferences that are shared across multiple application components
517 * (activities, receivers, services, providers), you can use the underlying
518 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
519 * to retrieve a preferences
520 * object stored under a specific name.
521 * (Note that it is not possible to share settings data across application
522 * packages -- for that you will need a content provider.)</p>
523 *
524 * <p>Here is an excerpt from a calendar activity that stores the user's
525 * preferred view mode in its persistent settings:</p>
526 *
527 * <pre class="prettyprint">
528 * public class CalendarActivity extends Activity {
529 * ...
530 *
531 * static final int DAY_VIEW_MODE = 0;
532 * static final int WEEK_VIEW_MODE = 1;
533 *
534 * private SharedPreferences mPrefs;
535 * private int mCurViewMode;
536 *
537 * protected void onCreate(Bundle savedInstanceState) {
538 * super.onCreate(savedInstanceState);
539 *
540 * SharedPreferences mPrefs = getSharedPreferences();
541 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
542 * }
543 *
544 * protected void onPause() {
545 * super.onPause();
546 *
547 * SharedPreferences.Editor ed = mPrefs.edit();
548 * ed.putInt("view_mode", mCurViewMode);
549 * ed.commit();
550 * }
551 * }
552 * </pre>
553 *
554 * <a name="Permissions"></a>
555 * <h3>Permissions</h3>
556 *
557 * <p>The ability to start a particular Activity can be enforced when it is
558 * declared in its
559 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
560 * tag. By doing so, other applications will need to declare a corresponding
561 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
562 * element in their own manifest to be able to start that activity.
563 *
564 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
565 * document for more information on permissions and security in general.
566 *
567 * <a name="ProcessLifecycle"></a>
568 * <h3>Process Lifecycle</h3>
569 *
570 * <p>The Android system attempts to keep application process around for as
571 * long as possible, but eventually will need to remove old processes when
572 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
573 * Lifecycle</a>, the decision about which process to remove is intimately
574 * tied to the state of the user's interaction with it. In general, there
575 * are four states a process can be in based on the activities running in it,
576 * listed here in order of importance. The system will kill less important
577 * processes (the last ones) before it resorts to killing more important
578 * processes (the first ones).
579 *
580 * <ol>
581 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
582 * that the user is currently interacting with) is considered the most important.
583 * Its process will only be killed as a last resort, if it uses more memory
584 * than is available on the device. Generally at this point the device has
585 * reached a memory paging state, so this is required in order to keep the user
586 * interface responsive.
587 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
588 * but not in the foreground, such as one sitting behind a foreground dialog)
589 * is considered extremely important and will not be killed unless that is
590 * required to keep the foreground activity running.
591 * <li> <p>A <b>background activity</b> (an activity that is not visible to
592 * the user and has been paused) is no longer critical, so the system may
593 * safely kill its process to reclaim memory for other foreground or
594 * visible processes. If its process needs to be killed, when the user navigates
595 * back to the activity (making it visible on the screen again), its
596 * {@link #onCreate} method will be called with the savedInstanceState it had previously
597 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
598 * state as the user last left it.
599 * <li> <p>An <b>empty process</b> is one hosting no activities or other
600 * application components (such as {@link Service} or
601 * {@link android.content.BroadcastReceiver} classes). These are killed very
602 * quickly by the system as memory becomes low. For this reason, any
603 * background operation you do outside of an activity must be executed in the
604 * context of an activity BroadcastReceiver or Service to ensure that the system
605 * knows it needs to keep your process around.
606 * </ol>
607 *
608 * <p>Sometimes an Activity may need to do a long-running operation that exists
609 * independently of the activity lifecycle itself. An example may be a camera
610 * application that allows you to upload a picture to a web site. The upload
611 * may take a long time, and the application should allow the user to leave
612 * the application will it is executing. To accomplish this, your Activity
613 * should start a {@link Service} in which the upload takes place. This allows
614 * the system to properly prioritize your process (considering it to be more
615 * important than other non-visible applications) for the duration of the
616 * upload, independent of whether the original activity is paused, stopped,
617 * or finished.
618 */
619public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700620 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 Window.Callback, KeyEvent.Callback,
622 OnCreateContextMenuListener, ComponentCallbacks {
623 private static final String TAG = "Activity";
624
625 /** Standard activity result: operation canceled. */
626 public static final int RESULT_CANCELED = 0;
627 /** Standard activity result: operation succeeded. */
628 public static final int RESULT_OK = -1;
629 /** Start of user-defined activity results. */
630 public static final int RESULT_FIRST_USER = 1;
631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700633 private static final String FRAGMENTS_TAG = "android:fragments";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
635 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
636 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800637 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800639 private static class ManagedDialog {
640 Dialog mDialog;
641 Bundle mArgs;
642 }
643 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644
645 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
646 private Instrumentation mInstrumentation;
647 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700648 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 /*package*/ String mEmbeddedID;
650 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700651 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 private ComponentName mComponent;
653 /*package*/ ActivityInfo mActivityInfo;
654 /*package*/ ActivityThread mMainThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 Activity mParent;
656 boolean mCalled;
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700657 boolean mCheckedForLoaderManager;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700658 boolean mLoadersStarted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 private boolean mResumed;
660 private boolean mStopped;
661 boolean mFinished;
662 boolean mStartedActivity;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700663 /** true if the activity is going through a transient pause */
664 /*package*/ boolean mTemporaryPause = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500665 /** true if the activity is being destroyed in order to recreate it with a new configuration */
666 /*package*/ boolean mChangingConfigurations = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 /*package*/ int mConfigChangeFlags;
668 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100669 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700671 static final class NonConfigurationInstances {
672 Object activity;
673 HashMap<String, Object> children;
674 ArrayList<Fragment> fragments;
Dianne Hackborn4911b782010-07-15 12:54:39 -0700675 SparseArray<LoaderManagerImpl> loaders;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700676 }
677 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 private Window mWindow;
680
681 private WindowManager mWindowManager;
682 /*package*/ View mDecor = null;
683 /*package*/ boolean mWindowAdded = false;
684 /*package*/ boolean mVisibleFromServer = false;
685 /*package*/ boolean mVisibleFromClient = true;
Adam Powellac695c62010-07-20 18:19:27 -0700686 /*package*/ ActionBarImpl mActionBar = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 private CharSequence mTitle;
689 private int mTitleColor = 0;
690
Dianne Hackbornb7a2e472010-08-12 16:20:42 -0700691 final FragmentManagerImpl mFragments = new FragmentManagerImpl();
Dianne Hackborn2dedce62010-04-15 14:45:25 -0700692
Dianne Hackborn4911b782010-07-15 12:54:39 -0700693 SparseArray<LoaderManagerImpl> mAllLoaderManagers;
694 LoaderManagerImpl mLoaderManager;
Dianne Hackbornc8017682010-07-06 13:34:38 -0700695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 private static final class ManagedCursor {
697 ManagedCursor(Cursor cursor) {
698 mCursor = cursor;
699 mReleased = false;
700 mUpdated = false;
701 }
702
703 private final Cursor mCursor;
704 private boolean mReleased;
705 private boolean mUpdated;
706 }
707 private final ArrayList<ManagedCursor> mManagedCursors =
708 new ArrayList<ManagedCursor>();
709
710 // protected by synchronized (this)
711 int mResultCode = RESULT_CANCELED;
712 Intent mResultData = null;
713
714 private boolean mTitleReady = false;
715
716 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
717 private SpannableStringBuilder mDefaultKeySsb = null;
718
719 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
720
721 private Thread mUiThread;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700722 final Handler mHandler = new Handler();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 /** Return the intent that started this activity. */
725 public Intent getIntent() {
726 return mIntent;
727 }
728
729 /**
730 * Change the intent returned by {@link #getIntent}. This holds a
731 * reference to the given intent; it does not copy it. Often used in
732 * conjunction with {@link #onNewIntent}.
733 *
734 * @param newIntent The new Intent object to return from getIntent
735 *
736 * @see #getIntent
737 * @see #onNewIntent
738 */
739 public void setIntent(Intent newIntent) {
740 mIntent = newIntent;
741 }
742
743 /** Return the application that owns this activity. */
744 public final Application getApplication() {
745 return mApplication;
746 }
747
748 /** Is this activity embedded inside of another activity? */
749 public final boolean isChild() {
750 return mParent != null;
751 }
752
753 /** Return the parent activity if this view is an embedded child. */
754 public final Activity getParent() {
755 return mParent;
756 }
757
758 /** Retrieve the window manager for showing custom windows. */
759 public WindowManager getWindowManager() {
760 return mWindowManager;
761 }
762
763 /**
764 * Retrieve the current {@link android.view.Window} for the activity.
765 * This can be used to directly access parts of the Window API that
766 * are not available through Activity/Screen.
767 *
768 * @return Window The current window, or null if the activity is not
769 * visual.
770 */
771 public Window getWindow() {
772 return mWindow;
773 }
774
775 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -0700776 * Return the LoaderManager for this fragment, creating it if needed.
777 */
778 public LoaderManager getLoaderManager() {
779 if (mLoaderManager != null) {
780 return mLoaderManager;
781 }
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700782 mCheckedForLoaderManager = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700783 mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700784 return mLoaderManager;
785 }
786
Dianne Hackborn5e0d5952010-08-05 13:45:35 -0700787 LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
Dianne Hackbornc8017682010-07-06 13:34:38 -0700788 if (mAllLoaderManagers == null) {
Dianne Hackborn4911b782010-07-15 12:54:39 -0700789 mAllLoaderManagers = new SparseArray<LoaderManagerImpl>();
Dianne Hackbornc8017682010-07-06 13:34:38 -0700790 }
Dianne Hackborn4911b782010-07-15 12:54:39 -0700791 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700792 if (lm == null) {
793 if (create) {
794 lm = new LoaderManagerImpl(this, started);
795 mAllLoaderManagers.put(index, lm);
796 }
797 } else {
798 lm.updateActivity(this);
Dianne Hackbornc8017682010-07-06 13:34:38 -0700799 }
800 return lm;
801 }
802
803 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 * Calls {@link android.view.Window#getCurrentFocus} on the
805 * Window of this Activity to return the currently focused view.
806 *
807 * @return View The current View with focus or null.
808 *
809 * @see #getWindow
810 * @see android.view.Window#getCurrentFocus
811 */
812 public View getCurrentFocus() {
813 return mWindow != null ? mWindow.getCurrentFocus() : null;
814 }
815
816 @Override
817 public int getWallpaperDesiredMinimumWidth() {
818 int width = super.getWallpaperDesiredMinimumWidth();
819 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
820 }
821
822 @Override
823 public int getWallpaperDesiredMinimumHeight() {
824 int height = super.getWallpaperDesiredMinimumHeight();
825 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
826 }
827
828 /**
829 * Called when the activity is starting. This is where most initialization
830 * should go: calling {@link #setContentView(int)} to inflate the
831 * activity's UI, using {@link #findViewById} to programmatically interact
832 * with widgets in the UI, calling
833 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
834 * cursors for data being displayed, etc.
835 *
836 * <p>You can call {@link #finish} from within this function, in
837 * which case onDestroy() will be immediately called without any of the rest
838 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
839 * {@link #onPause}, etc) executing.
840 *
841 * <p><em>Derived classes must call through to the super class's
842 * implementation of this method. If they do not, an exception will be
843 * thrown.</em></p>
844 *
845 * @param savedInstanceState If the activity is being re-initialized after
846 * previously being shut down then this Bundle contains the data it most
847 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
848 *
849 * @see #onStart
850 * @see #onSaveInstanceState
851 * @see #onRestoreInstanceState
852 * @see #onPostCreate
853 */
854 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackborn2707d602010-07-09 18:01:20 -0700855 if (mLastNonConfigurationInstances != null) {
856 mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
857 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700858 if (savedInstanceState != null) {
859 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
860 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
861 ? mLastNonConfigurationInstances.fragments : null);
862 }
863 mFragments.dispatchCreate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 mCalled = true;
865 }
866
867 /**
868 * The hook for {@link ActivityThread} to restore the state of this activity.
869 *
870 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
871 * {@link #restoreManagedDialogs(android.os.Bundle)}.
872 *
873 * @param savedInstanceState contains the saved state
874 */
875 final void performRestoreInstanceState(Bundle savedInstanceState) {
876 onRestoreInstanceState(savedInstanceState);
877 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
880 /**
881 * This method is called after {@link #onStart} when the activity is
882 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -0800883 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 * to restore their state, but it is sometimes convenient to do it here
885 * after all of the initialization has been done or to allow subclasses to
886 * decide whether to use your default implementation. The default
887 * implementation of this method performs a restore of any view state that
888 * had previously been frozen by {@link #onSaveInstanceState}.
889 *
890 * <p>This method is called between {@link #onStart} and
891 * {@link #onPostCreate}.
892 *
893 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
894 *
895 * @see #onCreate
896 * @see #onPostCreate
897 * @see #onResume
898 * @see #onSaveInstanceState
899 */
900 protected void onRestoreInstanceState(Bundle savedInstanceState) {
901 if (mWindow != null) {
902 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
903 if (windowState != null) {
904 mWindow.restoreHierarchyState(windowState);
905 }
906 }
907 }
908
909 /**
910 * Restore the state of any saved managed dialogs.
911 *
912 * @param savedInstanceState The bundle to restore from.
913 */
914 private void restoreManagedDialogs(Bundle savedInstanceState) {
915 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
916 if (b == null) {
917 return;
918 }
919
920 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
921 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800922 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 for (int i = 0; i < numDialogs; i++) {
924 final Integer dialogId = ids[i];
925 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
926 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700927 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
928 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800929 final ManagedDialog md = new ManagedDialog();
930 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
931 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
932 if (md.mDialog != null) {
933 mManagedDialogs.put(dialogId, md);
934 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
935 md.mDialog.onRestoreInstanceState(dialogState);
936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938 }
939 }
940
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800941 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
942 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700943 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800944 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700945 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700946 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700947 return dialog;
948 }
949
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800950 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 return SAVED_DIALOG_KEY_PREFIX + key;
952 }
953
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800954 private static String savedDialogArgsKeyFor(int key) {
955 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957
958 /**
959 * Called when activity start-up is complete (after {@link #onStart}
960 * and {@link #onRestoreInstanceState} have been called). Applications will
961 * generally not implement this method; it is intended for system
962 * classes to do final initialization after application code has run.
963 *
964 * <p><em>Derived classes must call through to the super class's
965 * implementation of this method. If they do not, an exception will be
966 * thrown.</em></p>
967 *
968 * @param savedInstanceState If the activity is being re-initialized after
969 * previously being shut down then this Bundle contains the data it most
970 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
971 * @see #onCreate
972 */
973 protected void onPostCreate(Bundle savedInstanceState) {
974 if (!isChild()) {
975 mTitleReady = true;
976 onTitleChanged(getTitle(), getTitleColor());
977 }
978 mCalled = true;
979 }
980
981 /**
982 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
983 * the activity had been stopped, but is now again being displayed to the
984 * user. It will be followed by {@link #onResume}.
985 *
986 * <p><em>Derived classes must call through to the super class's
987 * implementation of this method. If they do not, an exception will be
988 * thrown.</em></p>
989 *
990 * @see #onCreate
991 * @see #onStop
992 * @see #onResume
993 */
994 protected void onStart() {
995 mCalled = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -0700996
997 if (!mLoadersStarted) {
998 mLoadersStarted = true;
999 if (mLoaderManager != null) {
1000 mLoaderManager.doStart();
1001 } else if (!mCheckedForLoaderManager) {
1002 mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
1003 }
1004 mCheckedForLoaderManager = true;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
1007
1008 /**
1009 * Called after {@link #onStop} when the current activity is being
1010 * re-displayed to the user (the user has navigated back to it). It will
1011 * be followed by {@link #onStart} and then {@link #onResume}.
1012 *
1013 * <p>For activities that are using raw {@link Cursor} objects (instead of
1014 * creating them through
1015 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1016 * this is usually the place
1017 * where the cursor should be requeried (because you had deactivated it in
1018 * {@link #onStop}.
1019 *
1020 * <p><em>Derived classes must call through to the super class's
1021 * implementation of this method. If they do not, an exception will be
1022 * thrown.</em></p>
1023 *
1024 * @see #onStop
1025 * @see #onStart
1026 * @see #onResume
1027 */
1028 protected void onRestart() {
1029 mCalled = true;
1030 }
1031
1032 /**
1033 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1034 * {@link #onPause}, for your activity to start interacting with the user.
1035 * This is a good place to begin animations, open exclusive-access devices
1036 * (such as the camera), etc.
1037 *
1038 * <p>Keep in mind that onResume is not the best indicator that your activity
1039 * is visible to the user; a system window such as the keyguard may be in
1040 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1041 * activity is visible to the user (for example, to resume a game).
1042 *
1043 * <p><em>Derived classes must call through to the super class's
1044 * implementation of this method. If they do not, an exception will be
1045 * thrown.</em></p>
1046 *
1047 * @see #onRestoreInstanceState
1048 * @see #onRestart
1049 * @see #onPostResume
1050 * @see #onPause
1051 */
1052 protected void onResume() {
1053 mCalled = true;
1054 }
1055
1056 /**
1057 * Called when activity resume is complete (after {@link #onResume} has
1058 * been called). Applications will generally not implement this method;
1059 * it is intended for system classes to do final setup after application
1060 * resume code has run.
1061 *
1062 * <p><em>Derived classes must call through to the super class's
1063 * implementation of this method. If they do not, an exception will be
1064 * thrown.</em></p>
1065 *
1066 * @see #onResume
1067 */
1068 protected void onPostResume() {
1069 final Window win = getWindow();
1070 if (win != null) win.makeActive();
1071 mCalled = true;
1072 }
1073
1074 /**
1075 * This is called for activities that set launchMode to "singleTop" in
1076 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1077 * flag when calling {@link #startActivity}. In either case, when the
1078 * activity is re-launched while at the top of the activity stack instead
1079 * of a new instance of the activity being started, onNewIntent() will be
1080 * called on the existing instance with the Intent that was used to
1081 * re-launch it.
1082 *
1083 * <p>An activity will always be paused before receiving a new intent, so
1084 * you can count on {@link #onResume} being called after this method.
1085 *
1086 * <p>Note that {@link #getIntent} still returns the original Intent. You
1087 * can use {@link #setIntent} to update it to this new Intent.
1088 *
1089 * @param intent The new intent that was started for the activity.
1090 *
1091 * @see #getIntent
1092 * @see #setIntent
1093 * @see #onResume
1094 */
1095 protected void onNewIntent(Intent intent) {
1096 }
1097
1098 /**
1099 * The hook for {@link ActivityThread} to save the state of this activity.
1100 *
1101 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1102 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1103 *
1104 * @param outState The bundle to save the state to.
1105 */
1106 final void performSaveInstanceState(Bundle outState) {
1107 onSaveInstanceState(outState);
1108 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110
1111 /**
1112 * Called to retrieve per-instance state from an activity before being killed
1113 * so that the state can be restored in {@link #onCreate} or
1114 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1115 * will be passed to both).
1116 *
1117 * <p>This method is called before an activity may be killed so that when it
1118 * comes back some time in the future it can restore its state. For example,
1119 * if activity B is launched in front of activity A, and at some point activity
1120 * A is killed to reclaim resources, activity A will have a chance to save the
1121 * current state of its user interface via this method so that when the user
1122 * returns to activity A, the state of the user interface can be restored
1123 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1124 *
1125 * <p>Do not confuse this method with activity lifecycle callbacks such as
1126 * {@link #onPause}, which is always called when an activity is being placed
1127 * in the background or on its way to destruction, or {@link #onStop} which
1128 * is called before destruction. One example of when {@link #onPause} and
1129 * {@link #onStop} is called and not this method is when a user navigates back
1130 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1131 * on B because that particular instance will never be restored, so the
1132 * system avoids calling it. An example when {@link #onPause} is called and
1133 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1134 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1135 * killed during the lifetime of B since the state of the user interface of
1136 * A will stay intact.
1137 *
1138 * <p>The default implementation takes care of most of the UI per-instance
1139 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1140 * view in the hierarchy that has an id, and by saving the id of the currently
1141 * focused view (all of which is restored by the default implementation of
1142 * {@link #onRestoreInstanceState}). If you override this method to save additional
1143 * information not captured by each individual view, you will likely want to
1144 * call through to the default implementation, otherwise be prepared to save
1145 * all of the state of each view yourself.
1146 *
1147 * <p>If called, this method will occur before {@link #onStop}. There are
1148 * no guarantees about whether it will occur before or after {@link #onPause}.
1149 *
1150 * @param outState Bundle in which to place your saved state.
1151 *
1152 * @see #onCreate
1153 * @see #onRestoreInstanceState
1154 * @see #onPause
1155 */
1156 protected void onSaveInstanceState(Bundle outState) {
1157 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001158 Parcelable p = mFragments.saveAllState();
1159 if (p != null) {
1160 outState.putParcelable(FRAGMENTS_TAG, p);
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163
1164 /**
1165 * Save the state of any managed dialogs.
1166 *
1167 * @param outState place to store the saved state.
1168 */
1169 private void saveManagedDialogs(Bundle outState) {
1170 if (mManagedDialogs == null) {
1171 return;
1172 }
1173
1174 final int numDialogs = mManagedDialogs.size();
1175 if (numDialogs == 0) {
1176 return;
1177 }
1178
1179 Bundle dialogState = new Bundle();
1180
1181 int[] ids = new int[mManagedDialogs.size()];
1182
1183 // save each dialog's bundle, gather the ids
1184 for (int i = 0; i < numDialogs; i++) {
1185 final int key = mManagedDialogs.keyAt(i);
1186 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001187 final ManagedDialog md = mManagedDialogs.valueAt(i);
1188 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1189 if (md.mArgs != null) {
1190 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
1193
1194 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1195 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1196 }
1197
1198
1199 /**
1200 * Called as part of the activity lifecycle when an activity is going into
1201 * the background, but has not (yet) been killed. The counterpart to
1202 * {@link #onResume}.
1203 *
1204 * <p>When activity B is launched in front of activity A, this callback will
1205 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1206 * so be sure to not do anything lengthy here.
1207 *
1208 * <p>This callback is mostly used for saving any persistent state the
1209 * activity is editing, to present a "edit in place" model to the user and
1210 * making sure nothing is lost if there are not enough resources to start
1211 * the new activity without first killing this one. This is also a good
1212 * place to do things like stop animations and other things that consume a
1213 * noticeable mount of CPU in order to make the switch to the next activity
1214 * as fast as possible, or to close resources that are exclusive access
1215 * such as the camera.
1216 *
1217 * <p>In situations where the system needs more memory it may kill paused
1218 * processes to reclaim resources. Because of this, you should be sure
1219 * that all of your state is saved by the time you return from
1220 * this function. In general {@link #onSaveInstanceState} is used to save
1221 * per-instance state in the activity and this method is used to store
1222 * global persistent data (in content providers, files, etc.)
1223 *
1224 * <p>After receiving this call you will usually receive a following call
1225 * to {@link #onStop} (after the next activity has been resumed and
1226 * displayed), however in some cases there will be a direct call back to
1227 * {@link #onResume} without going through the stopped state.
1228 *
1229 * <p><em>Derived classes must call through to the super class's
1230 * implementation of this method. If they do not, an exception will be
1231 * thrown.</em></p>
1232 *
1233 * @see #onResume
1234 * @see #onSaveInstanceState
1235 * @see #onStop
1236 */
1237 protected void onPause() {
1238 mCalled = true;
1239 }
1240
1241 /**
1242 * Called as part of the activity lifecycle when an activity is about to go
1243 * into the background as the result of user choice. For example, when the
1244 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1245 * when an incoming phone call causes the in-call Activity to be automatically
1246 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1247 * the activity being interrupted. In cases when it is invoked, this method
1248 * is called right before the activity's {@link #onPause} callback.
1249 *
1250 * <p>This callback and {@link #onUserInteraction} are intended to help
1251 * activities manage status bar notifications intelligently; specifically,
1252 * for helping activities determine the proper time to cancel a notfication.
1253 *
1254 * @see #onUserInteraction()
1255 */
1256 protected void onUserLeaveHint() {
1257 }
1258
1259 /**
1260 * Generate a new thumbnail for this activity. This method is called before
1261 * pausing the activity, and should draw into <var>outBitmap</var> the
1262 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1263 * can use the given <var>canvas</var>, which is configured to draw into the
1264 * bitmap, for rendering if desired.
1265 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001266 * <p>The default implementation returns fails and does not draw a thumbnail;
1267 * this will result in the platform creating its own thumbnail if needed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 *
1269 * @param outBitmap The bitmap to contain the thumbnail.
1270 * @param canvas Can be used to render into the bitmap.
1271 *
1272 * @return Return true if you have drawn into the bitmap; otherwise after
1273 * you return it will be filled with a default thumbnail.
1274 *
1275 * @see #onCreateDescription
1276 * @see #onSaveInstanceState
1277 * @see #onPause
1278 */
1279 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001280 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282
1283 /**
1284 * Generate a new description for this activity. This method is called
1285 * before pausing the activity and can, if desired, return some textual
1286 * description of its current state to be displayed to the user.
1287 *
1288 * <p>The default implementation returns null, which will cause you to
1289 * inherit the description from the previous activity. If all activities
1290 * return null, generally the label of the top activity will be used as the
1291 * description.
1292 *
1293 * @return A description of what the user is doing. It should be short and
1294 * sweet (only a few words).
1295 *
1296 * @see #onCreateThumbnail
1297 * @see #onSaveInstanceState
1298 * @see #onPause
1299 */
1300 public CharSequence onCreateDescription() {
1301 return null;
1302 }
1303
1304 /**
1305 * Called when you are no longer visible to the user. You will next
1306 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1307 * depending on later user activity.
1308 *
1309 * <p>Note that this method may never be called, in low memory situations
1310 * where the system does not have enough memory to keep your activity's
1311 * process running after its {@link #onPause} method is called.
1312 *
1313 * <p><em>Derived classes must call through to the super class's
1314 * implementation of this method. If they do not, an exception will be
1315 * thrown.</em></p>
1316 *
1317 * @see #onRestart
1318 * @see #onResume
1319 * @see #onSaveInstanceState
1320 * @see #onDestroy
1321 */
1322 protected void onStop() {
1323 mCalled = true;
1324 }
1325
1326 /**
1327 * Perform any final cleanup before an activity is destroyed. This can
1328 * happen either because the activity is finishing (someone called
1329 * {@link #finish} on it, or because the system is temporarily destroying
1330 * this instance of the activity to save space. You can distinguish
1331 * between these two scenarios with the {@link #isFinishing} method.
1332 *
1333 * <p><em>Note: do not count on this method being called as a place for
1334 * saving data! For example, if an activity is editing data in a content
1335 * provider, those edits should be committed in either {@link #onPause} or
1336 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1337 * free resources like threads that are associated with an activity, so
1338 * that a destroyed activity does not leave such things around while the
1339 * rest of its application is still running. There are situations where
1340 * the system will simply kill the activity's hosting process without
1341 * calling this method (or any others) in it, so it should not be used to
1342 * do things that are intended to remain around after the process goes
1343 * away.
1344 *
1345 * <p><em>Derived classes must call through to the super class's
1346 * implementation of this method. If they do not, an exception will be
1347 * thrown.</em></p>
1348 *
1349 * @see #onPause
1350 * @see #onStop
1351 * @see #finish
1352 * @see #isFinishing
1353 */
1354 protected void onDestroy() {
1355 mCalled = true;
1356
1357 // dismiss any dialogs we are managing.
1358 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 final int numDialogs = mManagedDialogs.size();
1360 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001361 final ManagedDialog md = mManagedDialogs.valueAt(i);
1362 if (md.mDialog.isShowing()) {
1363 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001366 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368
1369 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001370 synchronized (mManagedCursors) {
1371 int numCursors = mManagedCursors.size();
1372 for (int i = 0; i < numCursors; i++) {
1373 ManagedCursor c = mManagedCursors.get(i);
1374 if (c != null) {
1375 c.mCursor.close();
1376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001378 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
Amith Yamasani49860442010-03-17 20:54:10 -07001380
1381 // Close any open search dialog
1382 if (mSearchManager != null) {
1383 mSearchManager.stopSearch();
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386
1387 /**
1388 * Called by the system when the device configuration changes while your
1389 * activity is running. Note that this will <em>only</em> be called if
1390 * you have selected configurations you would like to handle with the
1391 * {@link android.R.attr#configChanges} attribute in your manifest. If
1392 * any configuration change occurs that is not selected to be reported
1393 * by that attribute, then instead of reporting it the system will stop
1394 * and restart the activity (to have it launched with the new
1395 * configuration).
1396 *
1397 * <p>At the time that this function has been called, your Resources
1398 * object will have been updated to return resource values matching the
1399 * new configuration.
1400 *
1401 * @param newConfig The new device configuration.
1402 */
1403 public void onConfigurationChanged(Configuration newConfig) {
1404 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001405
Dianne Hackborn9d071802010-12-08 14:49:15 -08001406 mFragments.dispatchConfigurationChanged(newConfig);
1407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 if (mWindow != null) {
1409 // Pass the configuration changed event to the window
1410 mWindow.onConfigurationChanged(newConfig);
1411 }
1412 }
1413
1414 /**
1415 * If this activity is being destroyed because it can not handle a
1416 * configuration parameter being changed (and thus its
1417 * {@link #onConfigurationChanged(Configuration)} method is
1418 * <em>not</em> being called), then you can use this method to discover
1419 * the set of changes that have occurred while in the process of being
1420 * destroyed. Note that there is no guarantee that these will be
1421 * accurate (other changes could have happened at any time), so you should
1422 * only use this as an optimization hint.
1423 *
1424 * @return Returns a bit field of the configuration parameters that are
1425 * changing, as defined by the {@link android.content.res.Configuration}
1426 * class.
1427 */
1428 public int getChangingConfigurations() {
1429 return mConfigChangeFlags;
1430 }
1431
1432 /**
1433 * Retrieve the non-configuration instance data that was previously
1434 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1435 * be available from the initial {@link #onCreate} and
1436 * {@link #onStart} calls to the new instance, allowing you to extract
1437 * any useful dynamic state from the previous instance.
1438 *
1439 * <p>Note that the data you retrieve here should <em>only</em> be used
1440 * as an optimization for handling configuration changes. You should always
1441 * be able to handle getting a null pointer back, and an activity must
1442 * still be able to restore itself to its previous state (through the
1443 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1444 * function returns null.
1445 *
1446 * @return Returns the object previously returned by
1447 * {@link #onRetainNonConfigurationInstance()}.
1448 */
1449 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001450 return mLastNonConfigurationInstances != null
1451 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
1454 /**
1455 * Called by the system, as part of destroying an
1456 * activity due to a configuration change, when it is known that a new
1457 * instance will immediately be created for the new configuration. You
1458 * can return any object you like here, including the activity instance
1459 * itself, which can later be retrieved by calling
1460 * {@link #getLastNonConfigurationInstance()} in the new activity
1461 * instance.
1462 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001463 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1464 * or later, consider instead using a {@link Fragment} with
1465 * {@link Fragment#setRetainInstance(boolean)
1466 * Fragment.setRetainInstance(boolean}.</em>
1467 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 * <p>This function is called purely as an optimization, and you must
1469 * not rely on it being called. When it is called, a number of guarantees
1470 * will be made to help optimize configuration switching:
1471 * <ul>
1472 * <li> The function will be called between {@link #onStop} and
1473 * {@link #onDestroy}.
1474 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001475 * created after this one's {@link #onDestroy()} is called. In particular,
1476 * <em>no</em> messages will be dispatched during this time (when the returned
1477 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 * <li> The object you return here will <em>always</em> be available from
1479 * the {@link #getLastNonConfigurationInstance()} method of the following
1480 * activity instance as described there.
1481 * </ul>
1482 *
1483 * <p>These guarantees are designed so that an activity can use this API
1484 * to propagate extensive state from the old to new activity instance, from
1485 * loaded bitmaps, to network connections, to evenly actively running
1486 * threads. Note that you should <em>not</em> propagate any data that
1487 * may change based on the configuration, including any data loaded from
1488 * resources such as strings, layouts, or drawables.
1489 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001490 * <p>The guarantee of no message handling during the switch to the next
1491 * activity simplifies use with active objects. For example if your retained
1492 * state is an {@link android.os.AsyncTask} you are guaranteed that its
1493 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
1494 * not be called from the call here until you execute the next instance's
1495 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
1496 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
1497 * running in a separate thread.)
1498 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 * @return Return any Object holding the desired state to propagate to the
1500 * next activity instance.
1501 */
1502 public Object onRetainNonConfigurationInstance() {
1503 return null;
1504 }
1505
1506 /**
1507 * Retrieve the non-configuration instance data that was previously
1508 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1509 * be available from the initial {@link #onCreate} and
1510 * {@link #onStart} calls to the new instance, allowing you to extract
1511 * any useful dynamic state from the previous instance.
1512 *
1513 * <p>Note that the data you retrieve here should <em>only</em> be used
1514 * as an optimization for handling configuration changes. You should always
1515 * be able to handle getting a null pointer back, and an activity must
1516 * still be able to restore itself to its previous state (through the
1517 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1518 * function returns null.
1519 *
1520 * @return Returns the object previously returned by
1521 * {@link #onRetainNonConfigurationChildInstances()}
1522 */
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001523 HashMap<String, Object> getLastNonConfigurationChildInstances() {
1524 return mLastNonConfigurationInstances != null
1525 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527
1528 /**
1529 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1530 * it should return either a mapping from child activity id strings to arbitrary objects,
1531 * or null. This method is intended to be used by Activity framework subclasses that control a
1532 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1533 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1534 */
1535 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1536 return null;
1537 }
1538
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001539 NonConfigurationInstances retainNonConfigurationInstances() {
1540 Object activity = onRetainNonConfigurationInstance();
1541 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
1542 ArrayList<Fragment> fragments = mFragments.retainNonConfig();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001543 boolean retainLoaders = false;
1544 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001545 // prune out any loader managers that were already stopped and so
Dianne Hackborn2707d602010-07-09 18:01:20 -07001546 // have nothing useful to retain.
1547 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
Dianne Hackborn4911b782010-07-15 12:54:39 -07001548 LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001549 if (lm.mRetaining) {
1550 retainLoaders = true;
1551 } else {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001552 lm.doDestroy();
Dianne Hackborn2707d602010-07-09 18:01:20 -07001553 mAllLoaderManagers.removeAt(i);
1554 }
1555 }
1556 }
1557 if (activity == null && children == null && fragments == null && !retainLoaders) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001558 return null;
1559 }
1560
1561 NonConfigurationInstances nci = new NonConfigurationInstances();
1562 nci.activity = activity;
1563 nci.children = children;
1564 nci.fragments = fragments;
Dianne Hackborn2707d602010-07-09 18:01:20 -07001565 nci.loaders = mAllLoaderManagers;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001566 return nci;
1567 }
1568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 public void onLowMemory() {
1570 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08001571 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
1574 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001575 * Return the FragmentManager for interacting with fragments associated
1576 * with this activity.
1577 */
1578 public FragmentManager getFragmentManager() {
1579 return mFragments;
1580 }
1581
1582 /**
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001583 * Start a series of edit operations on the Fragments associated with
1584 * this activity.
Dianne Hackborndef15372010-08-15 12:43:52 -07001585 * @deprecated use {@link #getFragmentManager}.
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001586 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001587 @Deprecated
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001588 public FragmentTransaction openFragmentTransaction() {
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07001589 return mFragments.openTransaction();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001590 }
1591
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001592 void invalidateFragmentIndex(int index) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001593 //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001594 if (mAllLoaderManagers != null) {
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07001595 LoaderManagerImpl lm = mAllLoaderManagers.get(index);
1596 if (lm != null) {
1597 lm.doDestroy();
1598 }
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07001599 mAllLoaderManagers.remove(index);
1600 }
1601 }
1602
Dianne Hackborn2dedce62010-04-15 14:45:25 -07001603 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07001604 * Called when a Fragment is being attached to this activity, immediately
1605 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
1606 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
1607 */
1608 public void onAttachFragment(Fragment fragment) {
1609 }
1610
1611 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 * Wrapper around
1613 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1614 * that gives the resulting {@link Cursor} to call
1615 * {@link #startManagingCursor} so that the activity will manage its
1616 * lifecycle for you.
1617 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001618 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1619 * or later, consider instead using {@link LoaderManager} instead, available
1620 * via {@link #getLoaderManager()}.</em>
1621 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 * @param uri The URI of the content provider to query.
1623 * @param projection List of columns to return.
1624 * @param selection SQL WHERE clause.
1625 * @param sortOrder SQL ORDER BY clause.
1626 *
1627 * @return The Cursor that was returned by query().
1628 *
1629 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1630 * @see #startManagingCursor
1631 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05001632 *
1633 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 */
Jason parks6ed50de2010-08-25 10:18:50 -05001635 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001636 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1637 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1639 if (c != null) {
1640 startManagingCursor(c);
1641 }
1642 return c;
1643 }
1644
1645 /**
1646 * Wrapper around
1647 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1648 * that gives the resulting {@link Cursor} to call
1649 * {@link #startManagingCursor} so that the activity will manage its
1650 * lifecycle for you.
1651 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001652 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1653 * or later, consider instead using {@link LoaderManager} instead, available
1654 * via {@link #getLoaderManager()}.</em>
1655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 * @param uri The URI of the content provider to query.
1657 * @param projection List of columns to return.
1658 * @param selection SQL WHERE clause.
1659 * @param selectionArgs The arguments to selection, if any ?s are pesent
1660 * @param sortOrder SQL ORDER BY clause.
1661 *
1662 * @return The Cursor that was returned by query().
1663 *
1664 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1665 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001666 *
1667 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 */
Jason parks6ed50de2010-08-25 10:18:50 -05001669 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07001670 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
1671 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1673 if (c != null) {
1674 startManagingCursor(c);
1675 }
1676 return c;
1677 }
1678
1679 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 * This method allows the activity to take care of managing the given
1681 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1682 * That is, when the activity is stopped it will automatically call
1683 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1684 * it will call {@link Cursor#requery} for you. When the activity is
1685 * destroyed, all managed Cursors will be closed automatically.
1686 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07001687 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
1688 * or later, consider instead using {@link LoaderManager} instead, available
1689 * via {@link #getLoaderManager()}.</em>
1690 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 * @param c The Cursor to be managed.
1692 *
1693 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1694 * @see #stopManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001695 *
1696 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 */
Jason parks6ed50de2010-08-25 10:18:50 -05001698 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 public void startManagingCursor(Cursor c) {
1700 synchronized (mManagedCursors) {
1701 mManagedCursors.add(new ManagedCursor(c));
1702 }
1703 }
1704
1705 /**
1706 * Given a Cursor that was previously given to
1707 * {@link #startManagingCursor}, stop the activity's management of that
1708 * cursor.
1709 *
1710 * @param c The Cursor that was being managed.
1711 *
1712 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05001713 *
1714 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 */
Jason parks6ed50de2010-08-25 10:18:50 -05001716 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 public void stopManagingCursor(Cursor c) {
1718 synchronized (mManagedCursors) {
1719 final int N = mManagedCursors.size();
1720 for (int i=0; i<N; i++) {
1721 ManagedCursor mc = mManagedCursors.get(i);
1722 if (mc.mCursor == c) {
1723 mManagedCursors.remove(i);
1724 break;
1725 }
1726 }
1727 }
1728 }
1729
1730 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07001731 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
1732 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08001733 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07001735 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738
1739 /**
1740 * Finds a view that was identified by the id attribute from the XML that
1741 * was processed in {@link #onCreate}.
1742 *
1743 * @return The view if found or null otherwise.
1744 */
1745 public View findViewById(int id) {
1746 return getWindow().findViewById(id);
1747 }
Adam Powell33b97432010-04-20 10:01:14 -07001748
1749 /**
1750 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07001751 *
Adam Powell33b97432010-04-20 10:01:14 -07001752 * @return The Activity's ActionBar, or null if it does not have one.
1753 */
1754 public ActionBar getActionBar() {
Adam Powell42c0fe82010-08-10 16:36:56 -07001755 initActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07001756 return mActionBar;
1757 }
1758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 /**
Adam Powell33b97432010-04-20 10:01:14 -07001760 * Creates a new ActionBar, locates the inflated ActionBarView,
1761 * initializes the ActionBar with the view, and sets mActionBar.
1762 */
1763 private void initActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07001764 Window window = getWindow();
Adam Powell9b4c8042010-08-10 15:36:44 -07001765 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07001766 return;
1767 }
1768
Adam Powell661c9082010-07-02 10:09:44 -07001769 mActionBar = new ActionBarImpl(this);
Adam Powell33b97432010-04-20 10:01:14 -07001770 }
1771
1772 /**
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001773 * Finds a fragment that was identified by the given id either when inflated
1774 * from XML or as the container ID when added in a transaction. This only
1775 * returns fragments that are currently added to the activity's content.
1776 * @return The fragment if found or null otherwise.
Dianne Hackborndef15372010-08-15 12:43:52 -07001777 * @deprecated use {@link #getFragmentManager}.
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001778 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001779 @Deprecated
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001780 public Fragment findFragmentById(int id) {
1781 return mFragments.findFragmentById(id);
1782 }
1783
1784 /**
1785 * Finds a fragment that was identified by the given tag either when inflated
1786 * from XML or as supplied when added in a transaction. This only
1787 * returns fragments that are currently added to the activity's content.
1788 * @return The fragment if found or null otherwise.
Dianne Hackborndef15372010-08-15 12:43:52 -07001789 * @deprecated use {@link #getFragmentManager}.
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001790 */
Dianne Hackborndef15372010-08-15 12:43:52 -07001791 @Deprecated
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001792 public Fragment findFragmentByTag(String tag) {
1793 return mFragments.findFragmentByTag(tag);
1794 }
1795
1796 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 * Set the activity content from a layout resource. The resource will be
1798 * inflated, adding all top-level views to the activity.
1799 *
1800 * @param layoutResID Resource ID to be inflated.
1801 */
1802 public void setContentView(int layoutResID) {
1803 getWindow().setContentView(layoutResID);
Adam Powell33b97432010-04-20 10:01:14 -07001804 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
1806
1807 /**
1808 * Set the activity content to an explicit view. This view is placed
1809 * directly into the activity's view hierarchy. It can itself be a complex
1810 * view hierarhcy.
1811 *
1812 * @param view The desired content to display.
1813 */
1814 public void setContentView(View view) {
1815 getWindow().setContentView(view);
Adam Powell33b97432010-04-20 10:01:14 -07001816 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818
1819 /**
1820 * Set the activity content to an explicit view. This view is placed
1821 * directly into the activity's view hierarchy. It can itself be a complex
1822 * view hierarhcy.
1823 *
1824 * @param view The desired content to display.
1825 * @param params Layout parameters for the view.
1826 */
1827 public void setContentView(View view, ViewGroup.LayoutParams params) {
1828 getWindow().setContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001829 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831
1832 /**
1833 * Add an additional content view to the activity. Added after any existing
1834 * ones in the activity -- existing views are NOT removed.
1835 *
1836 * @param view The desired content to display.
1837 * @param params Layout parameters for the view.
1838 */
1839 public void addContentView(View view, ViewGroup.LayoutParams params) {
1840 getWindow().addContentView(view, params);
Adam Powell33b97432010-04-20 10:01:14 -07001841 initActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
1844 /**
1845 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1846 * keys.
1847 *
1848 * @see #setDefaultKeyMode
1849 */
1850 static public final int DEFAULT_KEYS_DISABLE = 0;
1851 /**
1852 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1853 * key handling.
1854 *
1855 * @see #setDefaultKeyMode
1856 */
1857 static public final int DEFAULT_KEYS_DIALER = 1;
1858 /**
1859 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1860 * default key handling.
1861 *
1862 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1863 *
1864 * @see #setDefaultKeyMode
1865 */
1866 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1867 /**
1868 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1869 * will start an application-defined search. (If the application or activity does not
1870 * actually define a search, the the keys will be ignored.)
1871 *
1872 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1873 *
1874 * @see #setDefaultKeyMode
1875 */
1876 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1877
1878 /**
1879 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1880 * will start a global search (typically web search, but some platforms may define alternate
1881 * methods for global search)
1882 *
1883 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1884 *
1885 * @see #setDefaultKeyMode
1886 */
1887 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1888
1889 /**
1890 * Select the default key handling for this activity. This controls what
1891 * will happen to key events that are not otherwise handled. The default
1892 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1893 * floor. Other modes allow you to launch the dialer
1894 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1895 * menu without requiring the menu key be held down
1896 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1897 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1898 *
1899 * <p>Note that the mode selected here does not impact the default
1900 * handling of system keys, such as the "back" and "menu" keys, and your
1901 * activity and its views always get a first chance to receive and handle
1902 * all application keys.
1903 *
1904 * @param mode The desired default key mode constant.
1905 *
1906 * @see #DEFAULT_KEYS_DISABLE
1907 * @see #DEFAULT_KEYS_DIALER
1908 * @see #DEFAULT_KEYS_SHORTCUT
1909 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1910 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1911 * @see #onKeyDown
1912 */
1913 public final void setDefaultKeyMode(int mode) {
1914 mDefaultKeyMode = mode;
1915
1916 // Some modes use a SpannableStringBuilder to track & dispatch input events
1917 // This list must remain in sync with the switch in onKeyDown()
1918 switch (mode) {
1919 case DEFAULT_KEYS_DISABLE:
1920 case DEFAULT_KEYS_SHORTCUT:
1921 mDefaultKeySsb = null; // not used in these modes
1922 break;
1923 case DEFAULT_KEYS_DIALER:
1924 case DEFAULT_KEYS_SEARCH_LOCAL:
1925 case DEFAULT_KEYS_SEARCH_GLOBAL:
1926 mDefaultKeySsb = new SpannableStringBuilder();
1927 Selection.setSelection(mDefaultKeySsb,0);
1928 break;
1929 default:
1930 throw new IllegalArgumentException();
1931 }
1932 }
1933
1934 /**
1935 * Called when a key was pressed down and not handled by any of the views
1936 * inside of the activity. So, for example, key presses while the cursor
1937 * is inside a TextView will not trigger the event (unless it is a navigation
1938 * to another object) because TextView handles its own key presses.
1939 *
1940 * <p>If the focused view didn't want this event, this method is called.
1941 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001942 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1943 * by calling {@link #onBackPressed()}, though the behavior varies based
1944 * on the application compatibility mode: for
1945 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1946 * it will set up the dispatch to call {@link #onKeyUp} where the action
1947 * will be performed; for earlier applications, it will perform the
1948 * action immediately in on-down, as those versions of the platform
1949 * behaved.
1950 *
1951 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001952 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 *
1954 * @return Return <code>true</code> to prevent this event from being propagated
1955 * further, or <code>false</code> to indicate that you have not handled
1956 * this event and it should continue to be propagated.
1957 * @see #onKeyUp
1958 * @see android.view.KeyEvent
1959 */
1960 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001961 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001962 if (getApplicationInfo().targetSdkVersion
1963 >= Build.VERSION_CODES.ECLAIR) {
1964 event.startTracking();
1965 } else {
1966 onBackPressed();
1967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 return true;
1969 }
1970
1971 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1972 return false;
1973 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001974 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1975 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1976 return true;
1977 }
1978 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 } else {
1980 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1981 boolean clearSpannable = false;
1982 boolean handled;
1983 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1984 clearSpannable = true;
1985 handled = false;
1986 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001987 handled = TextKeyListener.getInstance().onKeyDown(
1988 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 if (handled && mDefaultKeySsb.length() > 0) {
1990 // something useable has been typed - dispatch it now.
1991
1992 final String str = mDefaultKeySsb.toString();
1993 clearSpannable = true;
1994
1995 switch (mDefaultKeyMode) {
1996 case DEFAULT_KEYS_DIALER:
1997 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1998 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1999 startActivity(intent);
2000 break;
2001 case DEFAULT_KEYS_SEARCH_LOCAL:
2002 startSearch(str, false, null, false);
2003 break;
2004 case DEFAULT_KEYS_SEARCH_GLOBAL:
2005 startSearch(str, false, null, true);
2006 break;
2007 }
2008 }
2009 }
2010 if (clearSpannable) {
2011 mDefaultKeySsb.clear();
2012 mDefaultKeySsb.clearSpans();
2013 Selection.setSelection(mDefaultKeySsb,0);
2014 }
2015 return handled;
2016 }
2017 }
2018
2019 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002020 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2021 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2022 * the event).
2023 */
2024 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2025 return false;
2026 }
2027
2028 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 * Called when a key was released and not handled by any of the views
2030 * inside of the activity. So, for example, key presses while the cursor
2031 * is inside a TextView will not trigger the event (unless it is a navigation
2032 * to another object) because TextView handles its own key presses.
2033 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002034 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2035 * and go back.
2036 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 * @return Return <code>true</code> to prevent this event from being propagated
2038 * further, or <code>false</code> to indicate that you have not handled
2039 * this event and it should continue to be propagated.
2040 * @see #onKeyDown
2041 * @see KeyEvent
2042 */
2043 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07002044 if (getApplicationInfo().targetSdkVersion
2045 >= Build.VERSION_CODES.ECLAIR) {
2046 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2047 && !event.isCanceled()) {
2048 onBackPressed();
2049 return true;
2050 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 return false;
2053 }
2054
2055 /**
2056 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2057 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2058 * the event).
2059 */
2060 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2061 return false;
2062 }
2063
2064 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002065 * Called when the activity has detected the user's press of the back
2066 * key. The default implementation simply finishes the current activity,
2067 * but you can override this to do whatever you want.
2068 */
2069 public void onBackPressed() {
Dianne Hackborn3a57fb92010-11-15 17:58:52 -08002070 if (!mFragments.popBackStackImmediate()) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07002071 finish();
2072 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002073 }
Jeff Brown64da12a2011-01-04 19:57:47 -08002074
2075 /**
2076 * Called when a key shortcut event is not handled by any of the views in the Activity.
2077 * Override this method to implement global key shortcuts for the Activity.
2078 * Key shortcuts can also be implemented by setting the
2079 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2080 *
2081 * @param keyCode The value in event.getKeyCode().
2082 * @param event Description of the key event.
2083 * @return True if the key shortcut was handled.
2084 */
2085 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2086 return false;
2087 }
2088
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002089 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 * Called when a touch screen event was not handled by any of the views
2091 * under it. This is most useful to process touch events that happen
2092 * outside of your window bounds, where there is no view to receive it.
2093 *
2094 * @param event The touch screen event being processed.
2095 *
2096 * @return Return true if you have consumed the event, false if you haven't.
2097 * The default implementation always returns false.
2098 */
2099 public boolean onTouchEvent(MotionEvent event) {
2100 return false;
2101 }
2102
2103 /**
2104 * Called when the trackball was moved and not handled by any of the
2105 * views inside of the activity. So, for example, if the trackball moves
2106 * while focus is on a button, you will receive a call here because
2107 * buttons do not normally do anything with trackball events. The call
2108 * here happens <em>before</em> trackball movements are converted to
2109 * DPAD key events, which then get sent back to the view hierarchy, and
2110 * will be processed at the point for things like focus navigation.
2111 *
2112 * @param event The trackball event being processed.
2113 *
2114 * @return Return true if you have consumed the event, false if you haven't.
2115 * The default implementation always returns false.
2116 */
2117 public boolean onTrackballEvent(MotionEvent event) {
2118 return false;
2119 }
2120
2121 /**
2122 * Called whenever a key, touch, or trackball event is dispatched to the
2123 * activity. Implement this method if you wish to know that the user has
2124 * interacted with the device in some way while your activity is running.
2125 * This callback and {@link #onUserLeaveHint} are intended to help
2126 * activities manage status bar notifications intelligently; specifically,
2127 * for helping activities determine the proper time to cancel a notfication.
2128 *
2129 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2130 * be accompanied by calls to {@link #onUserInteraction}. This
2131 * ensures that your activity will be told of relevant user activity such
2132 * as pulling down the notification pane and touching an item there.
2133 *
2134 * <p>Note that this callback will be invoked for the touch down action
2135 * that begins a touch gesture, but may not be invoked for the touch-moved
2136 * and touch-up actions that follow.
2137 *
2138 * @see #onUserLeaveHint()
2139 */
2140 public void onUserInteraction() {
2141 }
2142
2143 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2144 // Update window manager if: we have a view, that view is
2145 // attached to its parent (which will be a RootView), and
2146 // this activity is not embedded.
2147 if (mParent == null) {
2148 View decor = mDecor;
2149 if (decor != null && decor.getParent() != null) {
2150 getWindowManager().updateViewLayout(decor, params);
2151 }
2152 }
2153 }
2154
2155 public void onContentChanged() {
2156 }
2157
2158 /**
2159 * Called when the current {@link Window} of the activity gains or loses
2160 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002161 * to the user. The default implementation clears the key tracking
2162 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07002164 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 * is managed independently of activity lifecycles. As such, while focus
2166 * changes will generally have some relation to lifecycle changes (an
2167 * activity that is stopped will not generally get window focus), you
2168 * should not rely on any particular order between the callbacks here and
2169 * those in the other lifecycle methods such as {@link #onResume}.
2170 *
2171 * <p>As a general rule, however, a resumed activity will have window
2172 * focus... unless it has displayed other dialogs or popups that take
2173 * input focus, in which case the activity itself will not have focus
2174 * when the other windows have it. Likewise, the system may display
2175 * system-level windows (such as the status bar notification panel or
2176 * a system alert) which will temporarily take window input focus without
2177 * pausing the foreground activity.
2178 *
2179 * @param hasFocus Whether the window of this activity has focus.
2180 *
2181 * @see #hasWindowFocus()
2182 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002183 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 */
2185 public void onWindowFocusChanged(boolean hasFocus) {
2186 }
2187
2188 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002189 * Called when the main window associated with the activity has been
2190 * attached to the window manager.
2191 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2192 * for more information.
2193 * @see View#onAttachedToWindow
2194 */
2195 public void onAttachedToWindow() {
2196 }
2197
2198 /**
2199 * Called when the main window associated with the activity has been
2200 * detached from the window manager.
2201 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2202 * for more information.
2203 * @see View#onDetachedFromWindow
2204 */
2205 public void onDetachedFromWindow() {
2206 }
2207
2208 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 * Returns true if this activity's <em>main</em> window currently has window focus.
2210 * Note that this is not the same as the view itself having focus.
2211 *
2212 * @return True if this activity's main window currently has window focus.
2213 *
2214 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2215 */
2216 public boolean hasWindowFocus() {
2217 Window w = getWindow();
2218 if (w != null) {
2219 View d = w.getDecorView();
2220 if (d != null) {
2221 return d.hasWindowFocus();
2222 }
2223 }
2224 return false;
2225 }
2226
2227 /**
2228 * Called to process key events. You can override this to intercept all
2229 * key events before they are dispatched to the window. Be sure to call
2230 * this implementation for key events that should be handled normally.
2231 *
2232 * @param event The key event.
2233 *
2234 * @return boolean Return true if this event was consumed.
2235 */
2236 public boolean dispatchKeyEvent(KeyEvent event) {
2237 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002238 Window win = getWindow();
2239 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 return true;
2241 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002242 View decor = mDecor;
2243 if (decor == null) decor = win.getDecorView();
2244 return event.dispatch(this, decor != null
2245 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247
2248 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08002249 * Called to process a key shortcut event.
2250 * You can override this to intercept all key shortcut events before they are
2251 * dispatched to the window. Be sure to call this implementation for key shortcut
2252 * events that should be handled normally.
2253 *
2254 * @param event The key shortcut event.
2255 * @return True if this event was consumed.
2256 */
2257 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
2258 onUserInteraction();
2259 if (getWindow().superDispatchKeyShortcutEvent(event)) {
2260 return true;
2261 }
2262 return onKeyShortcut(event.getKeyCode(), event);
2263 }
2264
2265 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 * Called to process touch screen events. You can override this to
2267 * intercept all touch screen events before they are dispatched to the
2268 * window. Be sure to call this implementation for touch screen events
2269 * that should be handled normally.
2270 *
2271 * @param ev The touch screen event.
2272 *
2273 * @return boolean Return true if this event was consumed.
2274 */
2275 public boolean dispatchTouchEvent(MotionEvent ev) {
2276 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2277 onUserInteraction();
2278 }
2279 if (getWindow().superDispatchTouchEvent(ev)) {
2280 return true;
2281 }
2282 return onTouchEvent(ev);
2283 }
2284
2285 /**
2286 * Called to process trackball events. You can override this to
2287 * intercept all trackball events before they are dispatched to the
2288 * window. Be sure to call this implementation for trackball events
2289 * that should be handled normally.
2290 *
2291 * @param ev The trackball event.
2292 *
2293 * @return boolean Return true if this event was consumed.
2294 */
2295 public boolean dispatchTrackballEvent(MotionEvent ev) {
2296 onUserInteraction();
2297 if (getWindow().superDispatchTrackballEvent(ev)) {
2298 return true;
2299 }
2300 return onTrackballEvent(ev);
2301 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002302
2303 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2304 event.setClassName(getClass().getName());
2305 event.setPackageName(getPackageName());
2306
2307 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002308 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2309 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002310 event.setFullScreen(isFullScreen);
2311
2312 CharSequence title = getTitle();
2313 if (!TextUtils.isEmpty(title)) {
2314 event.getText().add(title);
2315 }
2316
2317 return true;
2318 }
2319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 /**
2321 * Default implementation of
2322 * {@link android.view.Window.Callback#onCreatePanelView}
2323 * for activities. This
2324 * simply returns null so that all panel sub-windows will have the default
2325 * menu behavior.
2326 */
2327 public View onCreatePanelView(int featureId) {
2328 return null;
2329 }
2330
2331 /**
2332 * Default implementation of
2333 * {@link android.view.Window.Callback#onCreatePanelMenu}
2334 * for activities. This calls through to the new
2335 * {@link #onCreateOptionsMenu} method for the
2336 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2337 * so that subclasses of Activity don't need to deal with feature codes.
2338 */
2339 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2340 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002341 boolean show = onCreateOptionsMenu(menu);
2342 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
2343 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 }
2345 return false;
2346 }
2347
2348 /**
2349 * Default implementation of
2350 * {@link android.view.Window.Callback#onPreparePanel}
2351 * for activities. This
2352 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2353 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2354 * panel, so that subclasses of
2355 * Activity don't need to deal with feature codes.
2356 */
2357 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2358 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2359 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002360 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 return goforit && menu.hasVisibleItems();
2362 }
2363 return true;
2364 }
2365
2366 /**
2367 * {@inheritDoc}
2368 *
2369 * @return The default implementation returns true.
2370 */
2371 public boolean onMenuOpened(int featureId, Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08002372 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powell049dd3d2010-12-02 13:43:59 -08002373 if (mActionBar != null) {
2374 mActionBar.dispatchMenuVisibilityChanged(true);
2375 } else {
2376 Log.e(TAG, "Tried to open action bar menu with no action bar");
2377 }
Adam Powell8515ee82010-11-30 14:09:55 -08002378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 return true;
2380 }
2381
2382 /**
2383 * Default implementation of
2384 * {@link android.view.Window.Callback#onMenuItemSelected}
2385 * for activities. This calls through to the new
2386 * {@link #onOptionsItemSelected} method for the
2387 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2388 * panel, so that subclasses of
2389 * Activity don't need to deal with feature codes.
2390 */
2391 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2392 switch (featureId) {
2393 case Window.FEATURE_OPTIONS_PANEL:
2394 // Put event logging here so it gets called even if subclass
2395 // doesn't call through to superclass's implmeentation of each
2396 // of these methods below
2397 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002398 if (onOptionsItemSelected(item)) {
2399 return true;
2400 }
2401 return mFragments.dispatchOptionsItemSelected(item);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402
2403 case Window.FEATURE_CONTEXT_MENU:
2404 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07002405 if (onContextItemSelected(item)) {
2406 return true;
2407 }
2408 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08002409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 default:
2411 return false;
2412 }
2413 }
2414
2415 /**
2416 * Default implementation of
2417 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2418 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2419 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2420 * so that subclasses of Activity don't need to deal with feature codes.
2421 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2422 * {@link #onContextMenuClosed(Menu)} will be called.
2423 */
2424 public void onPanelClosed(int featureId, Menu menu) {
2425 switch (featureId) {
2426 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002427 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 onOptionsMenuClosed(menu);
2429 break;
2430
2431 case Window.FEATURE_CONTEXT_MENU:
2432 onContextMenuClosed(menu);
2433 break;
Adam Powell8515ee82010-11-30 14:09:55 -08002434
2435 case Window.FEATURE_ACTION_BAR:
2436 mActionBar.dispatchMenuVisibilityChanged(false);
2437 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 }
2439 }
2440
2441 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07002442 * Declare that the options menu has changed, so should be recreated.
2443 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
2444 * time it needs to be displayed.
2445 */
2446 public void invalidateOptionsMenu() {
2447 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
2448 }
2449
2450 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 * Initialize the contents of the Activity's standard options menu. You
2452 * should place your menu items in to <var>menu</var>.
2453 *
2454 * <p>This is only called once, the first time the options menu is
2455 * displayed. To update the menu every time it is displayed, see
2456 * {@link #onPrepareOptionsMenu}.
2457 *
2458 * <p>The default implementation populates the menu with standard system
2459 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2460 * they will be correctly ordered with application-defined menu items.
2461 * Deriving classes should always call through to the base implementation.
2462 *
2463 * <p>You can safely hold on to <var>menu</var> (and any items created
2464 * from it), making modifications to it as desired, until the next
2465 * time onCreateOptionsMenu() is called.
2466 *
2467 * <p>When you add items to the menu, you can implement the Activity's
2468 * {@link #onOptionsItemSelected} method to handle them there.
2469 *
2470 * @param menu The options menu in which you place your items.
2471 *
2472 * @return You must return true for the menu to be displayed;
2473 * if you return false it will not be shown.
2474 *
2475 * @see #onPrepareOptionsMenu
2476 * @see #onOptionsItemSelected
2477 */
2478 public boolean onCreateOptionsMenu(Menu menu) {
2479 if (mParent != null) {
2480 return mParent.onCreateOptionsMenu(menu);
2481 }
2482 return true;
2483 }
2484
2485 /**
2486 * Prepare the Screen's standard options menu to be displayed. This is
2487 * called right before the menu is shown, every time it is shown. You can
2488 * use this method to efficiently enable/disable items or otherwise
2489 * dynamically modify the contents.
2490 *
2491 * <p>The default implementation updates the system menu items based on the
2492 * activity's state. Deriving classes should always call through to the
2493 * base class implementation.
2494 *
2495 * @param menu The options menu as last shown or first initialized by
2496 * onCreateOptionsMenu().
2497 *
2498 * @return You must return true for the menu to be displayed;
2499 * if you return false it will not be shown.
2500 *
2501 * @see #onCreateOptionsMenu
2502 */
2503 public boolean onPrepareOptionsMenu(Menu menu) {
2504 if (mParent != null) {
2505 return mParent.onPrepareOptionsMenu(menu);
2506 }
2507 return true;
2508 }
2509
2510 /**
2511 * This hook is called whenever an item in your options menu is selected.
2512 * The default implementation simply returns false to have the normal
2513 * processing happen (calling the item's Runnable or sending a message to
2514 * its Handler as appropriate). You can use this method for any items
2515 * for which you would like to do processing without those other
2516 * facilities.
2517 *
2518 * <p>Derived classes should call through to the base class for it to
2519 * perform the default menu handling.
2520 *
2521 * @param item The menu item that was selected.
2522 *
2523 * @return boolean Return false to allow normal menu processing to
2524 * proceed, true to consume it here.
2525 *
2526 * @see #onCreateOptionsMenu
2527 */
2528 public boolean onOptionsItemSelected(MenuItem item) {
2529 if (mParent != null) {
2530 return mParent.onOptionsItemSelected(item);
2531 }
2532 return false;
2533 }
2534
2535 /**
2536 * This hook is called whenever the options menu is being closed (either by the user canceling
2537 * the menu with the back/menu button, or when an item is selected).
2538 *
2539 * @param menu The options menu as last shown or first initialized by
2540 * onCreateOptionsMenu().
2541 */
2542 public void onOptionsMenuClosed(Menu menu) {
2543 if (mParent != null) {
2544 mParent.onOptionsMenuClosed(menu);
2545 }
2546 }
2547
2548 /**
2549 * Programmatically opens the options menu. If the options menu is already
2550 * open, this method does nothing.
2551 */
2552 public void openOptionsMenu() {
2553 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2554 }
2555
2556 /**
2557 * Progammatically closes the options menu. If the options menu is already
2558 * closed, this method does nothing.
2559 */
2560 public void closeOptionsMenu() {
2561 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2562 }
2563
2564 /**
2565 * Called when a context menu for the {@code view} is about to be shown.
2566 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2567 * time the context menu is about to be shown and should be populated for
2568 * the view (or item inside the view for {@link AdapterView} subclasses,
2569 * this can be found in the {@code menuInfo})).
2570 * <p>
2571 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2572 * item has been selected.
2573 * <p>
2574 * It is not safe to hold onto the context menu after this method returns.
2575 * {@inheritDoc}
2576 */
2577 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2578 }
2579
2580 /**
2581 * Registers a context menu to be shown for the given view (multiple views
2582 * can show the context menu). This method will set the
2583 * {@link OnCreateContextMenuListener} on the view to this activity, so
2584 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2585 * called when it is time to show the context menu.
2586 *
2587 * @see #unregisterForContextMenu(View)
2588 * @param view The view that should show a context menu.
2589 */
2590 public void registerForContextMenu(View view) {
2591 view.setOnCreateContextMenuListener(this);
2592 }
2593
2594 /**
2595 * Prevents a context menu to be shown for the given view. This method will remove the
2596 * {@link OnCreateContextMenuListener} on the view.
2597 *
2598 * @see #registerForContextMenu(View)
2599 * @param view The view that should stop showing a context menu.
2600 */
2601 public void unregisterForContextMenu(View view) {
2602 view.setOnCreateContextMenuListener(null);
2603 }
2604
2605 /**
2606 * Programmatically opens the context menu for a particular {@code view}.
2607 * The {@code view} should have been added via
2608 * {@link #registerForContextMenu(View)}.
2609 *
2610 * @param view The view to show the context menu for.
2611 */
2612 public void openContextMenu(View view) {
2613 view.showContextMenu();
2614 }
2615
2616 /**
2617 * Programmatically closes the most recently opened context menu, if showing.
2618 */
2619 public void closeContextMenu() {
2620 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2621 }
2622
2623 /**
2624 * This hook is called whenever an item in a context menu is selected. The
2625 * default implementation simply returns false to have the normal processing
2626 * happen (calling the item's Runnable or sending a message to its Handler
2627 * as appropriate). You can use this method for any items for which you
2628 * would like to do processing without those other facilities.
2629 * <p>
2630 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2631 * View that added this menu item.
2632 * <p>
2633 * Derived classes should call through to the base class for it to perform
2634 * the default menu handling.
2635 *
2636 * @param item The context menu item that was selected.
2637 * @return boolean Return false to allow normal context menu processing to
2638 * proceed, true to consume it here.
2639 */
2640 public boolean onContextItemSelected(MenuItem item) {
2641 if (mParent != null) {
2642 return mParent.onContextItemSelected(item);
2643 }
2644 return false;
2645 }
2646
2647 /**
2648 * This hook is called whenever the context menu is being closed (either by
2649 * the user canceling the menu with the back/menu button, or when an item is
2650 * selected).
2651 *
2652 * @param menu The context menu that is being closed.
2653 */
2654 public void onContextMenuClosed(Menu menu) {
2655 if (mParent != null) {
2656 mParent.onContextMenuClosed(menu);
2657 }
2658 }
2659
2660 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002661 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002663 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 protected Dialog onCreateDialog(int id) {
2665 return null;
2666 }
2667
2668 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002669 * Callback for creating dialogs that are managed (saved and restored) for you
2670 * by the activity. The default implementation calls through to
2671 * {@link #onCreateDialog(int)} for compatibility.
2672 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002673 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2674 * or later, consider instead using a {@link DialogFragment} instead.</em>
2675 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002676 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2677 * this method the first time, and hang onto it thereafter. Any dialog
2678 * that is created by this method will automatically be saved and restored
2679 * for you, including whether it is showing.
2680 *
2681 * <p>If you would like the activity to manage saving and restoring dialogs
2682 * for you, you should override this method and handle any ids that are
2683 * passed to {@link #showDialog}.
2684 *
2685 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2686 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2687 *
2688 * @param id The id of the dialog.
2689 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2690 * @return The dialog. If you return null, the dialog will not be created.
2691 *
2692 * @see #onPrepareDialog(int, Dialog, Bundle)
2693 * @see #showDialog(int, Bundle)
2694 * @see #dismissDialog(int)
2695 * @see #removeDialog(int)
2696 */
2697 protected Dialog onCreateDialog(int id, Bundle args) {
2698 return onCreateDialog(id);
2699 }
2700
2701 /**
2702 * @deprecated Old no-arguments version of
2703 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2704 */
2705 @Deprecated
2706 protected void onPrepareDialog(int id, Dialog dialog) {
2707 dialog.setOwnerActivity(this);
2708 }
2709
2710 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002712 * shown. The default implementation calls through to
2713 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2714 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 * <p>
2716 * Override this if you need to update a managed dialog based on the state
2717 * of the application each time it is shown. For example, a time picker
2718 * dialog might want to be updated with the current time. You should call
2719 * through to the superclass's implementation. The default implementation
2720 * will set this Activity as the owner activity on the Dialog.
2721 *
2722 * @param id The id of the managed dialog.
2723 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002724 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2725 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 * @see #showDialog(int)
2727 * @see #dismissDialog(int)
2728 * @see #removeDialog(int)
2729 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002730 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2731 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
2733
2734 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002735 * Simple version of {@link #showDialog(int, Bundle)} that does not
2736 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2737 * with null arguments.
2738 */
2739 public final void showDialog(int id) {
2740 showDialog(id, null);
2741 }
2742
2743 /**
2744 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 * will be made with the same id the first time this is called for a given
2746 * id. From thereafter, the dialog will be automatically saved and restored.
2747 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07002748 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2749 * or later, consider instead using a {@link DialogFragment} instead.</em>
2750 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002751 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 * be made to provide an opportunity to do any timely preparation.
2753 *
2754 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002755 * @param args Arguments to pass through to the dialog. These will be saved
2756 * and restored for you. Note that if the dialog is already created,
2757 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2758 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002759 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002760 * @return Returns true if the Dialog was created; false is returned if
2761 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2762 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002763 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002764 * @see #onCreateDialog(int, Bundle)
2765 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 * @see #dismissDialog(int)
2767 * @see #removeDialog(int)
2768 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002769 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002771 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002773 ManagedDialog md = mManagedDialogs.get(id);
2774 if (md == null) {
2775 md = new ManagedDialog();
2776 md.mDialog = createDialog(id, null, args);
2777 if (md.mDialog == null) {
2778 return false;
2779 }
2780 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002783 md.mArgs = args;
2784 onPrepareDialog(id, md.mDialog, args);
2785 md.mDialog.show();
2786 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 }
2788
2789 /**
2790 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2791 *
2792 * @param id The id of the managed dialog.
2793 *
2794 * @throws IllegalArgumentException if the id was not previously shown via
2795 * {@link #showDialog(int)}.
2796 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002797 * @see #onCreateDialog(int, Bundle)
2798 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 * @see #showDialog(int)
2800 * @see #removeDialog(int)
2801 */
2802 public final void dismissDialog(int id) {
2803 if (mManagedDialogs == null) {
2804 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002806
2807 final ManagedDialog md = mManagedDialogs.get(id);
2808 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 throw missingDialog(id);
2810 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002811 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813
2814 /**
2815 * Creates an exception to throw if a user passed in a dialog id that is
2816 * unexpected.
2817 */
2818 private IllegalArgumentException missingDialog(int id) {
2819 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2820 + "shown via Activity#showDialog");
2821 }
2822
2823 /**
2824 * Removes any internal references to a dialog managed by this Activity.
2825 * If the dialog is showing, it will dismiss it as part of the clean up.
2826 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002827 * <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 -08002828 * want to avoid the overhead of saving and restoring it in the future.
2829 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002830 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
2831 * will not throw an exception if you try to remove an ID that does not
2832 * currently have an associated dialog.</p>
2833 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 * @param id The id of the managed dialog.
2835 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002836 * @see #onCreateDialog(int, Bundle)
2837 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 * @see #showDialog(int)
2839 * @see #dismissDialog(int)
2840 */
2841 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07002842 if (mManagedDialogs != null) {
2843 final ManagedDialog md = mManagedDialogs.get(id);
2844 if (md != null) {
2845 md.mDialog.dismiss();
2846 mManagedDialogs.remove(id);
2847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 }
2850
2851 /**
2852 * This hook is called when the user signals the desire to start a search.
2853 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002854 * <p>You can use this function as a simple way to launch the search UI, in response to a
2855 * menu item, search button, or other widgets within your activity. Unless overidden,
2856 * calling this function is the same as calling
2857 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2858 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 *
2860 * <p>You can override this function to force global search, e.g. in response to a dedicated
2861 * search key, or to block search entirely (by simply returning false).
2862 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002863 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2864 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 *
2866 * @see android.app.SearchManager
2867 */
2868 public boolean onSearchRequested() {
2869 startSearch(null, false, null, false);
2870 return true;
2871 }
2872
2873 /**
2874 * This hook is called to launch the search UI.
2875 *
2876 * <p>It is typically called from onSearchRequested(), either directly from
2877 * Activity.onSearchRequested() or from an overridden version in any given
2878 * Activity. If your goal is simply to activate search, it is preferred to call
2879 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2880 * is to inject specific data such as context data, it is preferred to <i>override</i>
2881 * onSearchRequested(), so that any callers to it will benefit from the override.
2882 *
2883 * @param initialQuery Any non-null non-empty string will be inserted as
2884 * pre-entered text in the search query box.
2885 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2886 * any further typing will replace it. This is useful for cases where an entire pre-formed
2887 * query is being inserted. If false, the selection point will be placed at the end of the
2888 * inserted query. This is useful when the inserted query is text that the user entered,
2889 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2890 * if initialQuery is a non-empty string.</i>
2891 * @param appSearchData An application can insert application-specific
2892 * context here, in order to improve quality or specificity of its own
2893 * searches. This data will be returned with SEARCH intent(s). Null if
2894 * no extra data is required.
2895 * @param globalSearch If false, this will only launch the search that has been specifically
2896 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002897 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2899 *
2900 * @see android.app.SearchManager
2901 * @see #onSearchRequested
2902 */
2903 public void startSearch(String initialQuery, boolean selectInitialQuery,
2904 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002905 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002906 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 appSearchData, globalSearch);
2908 }
2909
2910 /**
krosaend2d60142009-08-17 08:56:48 -07002911 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2912 * the search dialog. Made available for testing purposes.
2913 *
2914 * @param query The query to trigger. If empty, the request will be ignored.
2915 * @param appSearchData An application can insert application-specific
2916 * context here, in order to improve quality or specificity of its own
2917 * searches. This data will be returned with SEARCH intent(s). Null if
2918 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002919 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002920 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002921 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002922 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002923 }
2924
2925 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 * Request that key events come to this activity. Use this if your
2927 * activity has no views with focus, but the activity still wants
2928 * a chance to process key events.
2929 *
2930 * @see android.view.Window#takeKeyEvents
2931 */
2932 public void takeKeyEvents(boolean get) {
2933 getWindow().takeKeyEvents(get);
2934 }
2935
2936 /**
2937 * Enable extended window features. This is a convenience for calling
2938 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2939 *
2940 * @param featureId The desired feature as defined in
2941 * {@link android.view.Window}.
2942 * @return Returns true if the requested feature is supported and now
2943 * enabled.
2944 *
2945 * @see android.view.Window#requestFeature
2946 */
2947 public final boolean requestWindowFeature(int featureId) {
2948 return getWindow().requestFeature(featureId);
2949 }
2950
2951 /**
2952 * Convenience for calling
2953 * {@link android.view.Window#setFeatureDrawableResource}.
2954 */
2955 public final void setFeatureDrawableResource(int featureId, int resId) {
2956 getWindow().setFeatureDrawableResource(featureId, resId);
2957 }
2958
2959 /**
2960 * Convenience for calling
2961 * {@link android.view.Window#setFeatureDrawableUri}.
2962 */
2963 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2964 getWindow().setFeatureDrawableUri(featureId, uri);
2965 }
2966
2967 /**
2968 * Convenience for calling
2969 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2970 */
2971 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2972 getWindow().setFeatureDrawable(featureId, drawable);
2973 }
2974
2975 /**
2976 * Convenience for calling
2977 * {@link android.view.Window#setFeatureDrawableAlpha}.
2978 */
2979 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2980 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2981 }
2982
2983 /**
2984 * Convenience for calling
2985 * {@link android.view.Window#getLayoutInflater}.
2986 */
2987 public LayoutInflater getLayoutInflater() {
2988 return getWindow().getLayoutInflater();
2989 }
2990
2991 /**
2992 * Returns a {@link MenuInflater} with this context.
2993 */
2994 public MenuInflater getMenuInflater() {
2995 return new MenuInflater(this);
2996 }
2997
2998 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002999 protected void onApplyThemeResource(Resources.Theme theme, int resid,
3000 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 if (mParent == null) {
3002 super.onApplyThemeResource(theme, resid, first);
3003 } else {
3004 try {
3005 theme.setTo(mParent.getTheme());
3006 } catch (Exception e) {
3007 // Empty
3008 }
3009 theme.applyStyle(resid, false);
3010 }
3011 }
3012
3013 /**
3014 * Launch an activity for which you would like a result when it finished.
3015 * When this activity exits, your
3016 * onActivityResult() method will be called with the given requestCode.
3017 * Using a negative requestCode is the same as calling
3018 * {@link #startActivity} (the activity is not launched as a sub-activity).
3019 *
3020 * <p>Note that this method should only be used with Intent protocols
3021 * that are defined to return a result. In other protocols (such as
3022 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
3023 * not get the result when you expect. For example, if the activity you
3024 * are launching uses the singleTask launch mode, it will not run in your
3025 * task and thus you will immediately receive a cancel result.
3026 *
3027 * <p>As a special case, if you call startActivityForResult() with a requestCode
3028 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
3029 * activity, then your window will not be displayed until a result is
3030 * returned back from the started activity. This is to avoid visible
3031 * flickering when redirecting to another activity.
3032 *
3033 * <p>This method throws {@link android.content.ActivityNotFoundException}
3034 * if there was no Activity found to run the given Intent.
3035 *
3036 * @param intent The intent to start.
3037 * @param requestCode If >= 0, this code will be returned in
3038 * onActivityResult() when the activity exits.
3039 *
3040 * @throws android.content.ActivityNotFoundException
3041 *
3042 * @see #startActivity
3043 */
3044 public void startActivityForResult(Intent intent, int requestCode) {
3045 if (mParent == null) {
3046 Instrumentation.ActivityResult ar =
3047 mInstrumentation.execStartActivity(
3048 this, mMainThread.getApplicationThread(), mToken, this,
3049 intent, requestCode);
3050 if (ar != null) {
3051 mMainThread.sendActivityResult(
3052 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3053 ar.getResultData());
3054 }
3055 if (requestCode >= 0) {
3056 // If this start is requesting a result, we can avoid making
3057 // the activity visible until the result is received. Setting
3058 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3059 // activity hidden during this time, to avoid flickering.
3060 // This can only be done when a result is requested because
3061 // that guarantees we will get information back when the
3062 // activity is finished, no matter what happens to it.
3063 mStartedActivity = true;
3064 }
3065 } else {
3066 mParent.startActivityFromChild(this, intent, requestCode);
3067 }
3068 }
3069
3070 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003071 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003072 * to use a IntentSender to describe the activity to be started. If
3073 * the IntentSender is for an activity, that activity will be started
3074 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
3075 * here; otherwise, its associated action will be executed (such as
3076 * sending a broadcast) as if you had called
3077 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003078 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003079 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003080 * @param requestCode If >= 0, this code will be returned in
3081 * onActivityResult() when the activity exits.
3082 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003083 * intent parameter to {@link IntentSender#sendIntent}.
3084 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003085 * would like to change.
3086 * @param flagsValues Desired values for any bits set in
3087 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003088 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003089 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003090 public void startIntentSenderForResult(IntentSender intent, int requestCode,
3091 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3092 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003093 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003094 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003095 flagsMask, flagsValues, this);
3096 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003097 mParent.startIntentSenderFromChild(this, intent, requestCode,
3098 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003099 }
3100 }
3101
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003102 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003103 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003104 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003105 try {
3106 String resolvedType = null;
3107 if (fillInIntent != null) {
3108 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
3109 }
3110 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003111 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003112 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
3113 requestCode, flagsMask, flagsValues);
3114 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003115 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003116 }
3117 Instrumentation.checkStartActivityResult(result, null);
3118 } catch (RemoteException e) {
3119 }
3120 if (requestCode >= 0) {
3121 // If this start is requesting a result, we can avoid making
3122 // the activity visible until the result is received. Setting
3123 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3124 // activity hidden during this time, to avoid flickering.
3125 // This can only be done when a result is requested because
3126 // that guarantees we will get information back when the
3127 // activity is finished, no matter what happens to it.
3128 mStartedActivity = true;
3129 }
3130 }
3131
3132 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 * Launch a new activity. You will not receive any information about when
3134 * the activity exits. This implementation overrides the base version,
3135 * providing information about
3136 * the activity performing the launch. Because of this additional
3137 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3138 * required; if not specified, the new activity will be added to the
3139 * task of the caller.
3140 *
3141 * <p>This method throws {@link android.content.ActivityNotFoundException}
3142 * if there was no Activity found to run the given Intent.
3143 *
3144 * @param intent The intent to start.
3145 *
3146 * @throws android.content.ActivityNotFoundException
3147 *
3148 * @see #startActivityForResult
3149 */
3150 @Override
3151 public void startActivity(Intent intent) {
3152 startActivityForResult(intent, -1);
3153 }
3154
3155 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003156 * Launch a new activity. You will not receive any information about when
3157 * the activity exits. This implementation overrides the base version,
3158 * providing information about
3159 * the activity performing the launch. Because of this additional
3160 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
3161 * required; if not specified, the new activity will be added to the
3162 * task of the caller.
3163 *
3164 * <p>This method throws {@link android.content.ActivityNotFoundException}
3165 * if there was no Activity found to run the given Intent.
3166 *
3167 * @param intents The intents to start.
3168 *
3169 * @throws android.content.ActivityNotFoundException
3170 *
3171 * @see #startActivityForResult
3172 */
3173 @Override
3174 public void startActivities(Intent[] intents) {
3175 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
3176 mToken, this, intents);
3177 }
3178
3179 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003180 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003181 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003182 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003183 * for more information.
3184 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003185 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003186 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003187 * intent parameter to {@link IntentSender#sendIntent}.
3188 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003189 * would like to change.
3190 * @param flagsValues Desired values for any bits set in
3191 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003192 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003193 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003194 public void startIntentSender(IntentSender intent,
3195 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
3196 throws IntentSender.SendIntentException {
3197 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
3198 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003199 }
3200
3201 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 * A special variation to launch an activity only if a new activity
3203 * instance is needed to handle the given Intent. In other words, this is
3204 * just like {@link #startActivityForResult(Intent, int)} except: if you are
3205 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
3206 * singleTask or singleTop
3207 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
3208 * and the activity
3209 * that handles <var>intent</var> is the same as your currently running
3210 * activity, then a new instance is not needed. In this case, instead of
3211 * the normal behavior of calling {@link #onNewIntent} this function will
3212 * return and you can handle the Intent yourself.
3213 *
3214 * <p>This function can only be called from a top-level activity; if it is
3215 * called from a child activity, a runtime exception will be thrown.
3216 *
3217 * @param intent The intent to start.
3218 * @param requestCode If >= 0, this code will be returned in
3219 * onActivityResult() when the activity exits, as described in
3220 * {@link #startActivityForResult}.
3221 *
3222 * @return If a new activity was launched then true is returned; otherwise
3223 * false is returned and you must handle the Intent yourself.
3224 *
3225 * @see #startActivity
3226 * @see #startActivityForResult
3227 */
3228 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
3229 if (mParent == null) {
3230 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
3231 try {
3232 result = ActivityManagerNative.getDefault()
3233 .startActivity(mMainThread.getApplicationThread(),
3234 intent, intent.resolveTypeIfNeeded(
3235 getContentResolver()),
3236 null, 0,
3237 mToken, mEmbeddedID, requestCode, true, false);
3238 } catch (RemoteException e) {
3239 // Empty
3240 }
3241
3242 Instrumentation.checkStartActivityResult(result, intent);
3243
3244 if (requestCode >= 0) {
3245 // If this start is requesting a result, we can avoid making
3246 // the activity visible until the result is received. Setting
3247 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
3248 // activity hidden during this time, to avoid flickering.
3249 // This can only be done when a result is requested because
3250 // that guarantees we will get information back when the
3251 // activity is finished, no matter what happens to it.
3252 mStartedActivity = true;
3253 }
3254 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
3255 }
3256
3257 throw new UnsupportedOperationException(
3258 "startActivityIfNeeded can only be called from a top-level activity");
3259 }
3260
3261 /**
3262 * Special version of starting an activity, for use when you are replacing
3263 * other activity components. You can use this to hand the Intent off
3264 * to the next Activity that can handle it. You typically call this in
3265 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3266 *
3267 * @param intent The intent to dispatch to the next activity. For
3268 * correct behavior, this must be the same as the Intent that started
3269 * your own activity; the only changes you can make are to the extras
3270 * inside of it.
3271 *
3272 * @return Returns a boolean indicating whether there was another Activity
3273 * to start: true if there was a next activity to start, false if there
3274 * wasn't. In general, if true is returned you will then want to call
3275 * finish() on yourself.
3276 */
3277 public boolean startNextMatchingActivity(Intent intent) {
3278 if (mParent == null) {
3279 try {
3280 return ActivityManagerNative.getDefault()
3281 .startNextMatchingActivity(mToken, intent);
3282 } catch (RemoteException e) {
3283 // Empty
3284 }
3285 return false;
3286 }
3287
3288 throw new UnsupportedOperationException(
3289 "startNextMatchingActivity can only be called from a top-level activity");
3290 }
3291
3292 /**
3293 * This is called when a child activity of this one calls its
3294 * {@link #startActivity} or {@link #startActivityForResult} method.
3295 *
3296 * <p>This method throws {@link android.content.ActivityNotFoundException}
3297 * if there was no Activity found to run the given Intent.
3298 *
3299 * @param child The activity making the call.
3300 * @param intent The intent to start.
3301 * @param requestCode Reply request code. < 0 if reply is not requested.
3302 *
3303 * @throws android.content.ActivityNotFoundException
3304 *
3305 * @see #startActivity
3306 * @see #startActivityForResult
3307 */
3308 public void startActivityFromChild(Activity child, Intent intent,
3309 int requestCode) {
3310 Instrumentation.ActivityResult ar =
3311 mInstrumentation.execStartActivity(
3312 this, mMainThread.getApplicationThread(), mToken, child,
3313 intent, requestCode);
3314 if (ar != null) {
3315 mMainThread.sendActivityResult(
3316 mToken, child.mEmbeddedID, requestCode,
3317 ar.getResultCode(), ar.getResultData());
3318 }
3319 }
3320
3321 /**
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003322 * This is called when a Fragment in this activity calls its
3323 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
3324 * method.
3325 *
3326 * <p>This method throws {@link android.content.ActivityNotFoundException}
3327 * if there was no Activity found to run the given Intent.
3328 *
3329 * @param fragment The fragment making the call.
3330 * @param intent The intent to start.
3331 * @param requestCode Reply request code. < 0 if reply is not requested.
3332 *
3333 * @throws android.content.ActivityNotFoundException
3334 *
3335 * @see Fragment#startActivity
3336 * @see Fragment#startActivityForResult
3337 */
3338 public void startActivityFromFragment(Fragment fragment, Intent intent,
3339 int requestCode) {
3340 Instrumentation.ActivityResult ar =
3341 mInstrumentation.execStartActivity(
3342 this, mMainThread.getApplicationThread(), mToken, fragment,
3343 intent, requestCode);
3344 if (ar != null) {
3345 mMainThread.sendActivityResult(
3346 mToken, fragment.mWho, requestCode,
3347 ar.getResultCode(), ar.getResultData());
3348 }
3349 }
3350
3351 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003352 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003353 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003354 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003355 * for more information.
3356 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003357 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3358 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3359 int extraFlags)
3360 throws IntentSender.SendIntentException {
3361 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003362 flagsMask, flagsValues, child);
3363 }
3364
3365 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003366 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3367 * or {@link #finish} to specify an explicit transition animation to
3368 * perform next.
3369 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003370 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003371 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003372 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003373 */
3374 public void overridePendingTransition(int enterAnim, int exitAnim) {
3375 try {
3376 ActivityManagerNative.getDefault().overridePendingTransition(
3377 mToken, getPackageName(), enterAnim, exitAnim);
3378 } catch (RemoteException e) {
3379 }
3380 }
3381
3382 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 * Call this to set the result that your activity will return to its
3384 * caller.
3385 *
3386 * @param resultCode The result code to propagate back to the originating
3387 * activity, often RESULT_CANCELED or RESULT_OK
3388 *
3389 * @see #RESULT_CANCELED
3390 * @see #RESULT_OK
3391 * @see #RESULT_FIRST_USER
3392 * @see #setResult(int, Intent)
3393 */
3394 public final void setResult(int resultCode) {
3395 synchronized (this) {
3396 mResultCode = resultCode;
3397 mResultData = null;
3398 }
3399 }
3400
3401 /**
3402 * Call this to set the result that your activity will return to its
3403 * caller.
3404 *
3405 * @param resultCode The result code to propagate back to the originating
3406 * activity, often RESULT_CANCELED or RESULT_OK
3407 * @param data The data to propagate back to the originating activity.
3408 *
3409 * @see #RESULT_CANCELED
3410 * @see #RESULT_OK
3411 * @see #RESULT_FIRST_USER
3412 * @see #setResult(int)
3413 */
3414 public final void setResult(int resultCode, Intent data) {
3415 synchronized (this) {
3416 mResultCode = resultCode;
3417 mResultData = data;
3418 }
3419 }
3420
3421 /**
3422 * Return the name of the package that invoked this activity. This is who
3423 * the data in {@link #setResult setResult()} will be sent to. You can
3424 * use this information to validate that the recipient is allowed to
3425 * receive the data.
3426 *
3427 * <p>Note: if the calling activity is not expecting a result (that is it
3428 * did not use the {@link #startActivityForResult}
3429 * form that includes a request code), then the calling package will be
3430 * null.
3431 *
3432 * @return The package of the activity that will receive your
3433 * reply, or null if none.
3434 */
3435 public String getCallingPackage() {
3436 try {
3437 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3438 } catch (RemoteException e) {
3439 return null;
3440 }
3441 }
3442
3443 /**
3444 * Return the name of the activity that invoked this activity. This is
3445 * who the data in {@link #setResult setResult()} will be sent to. You
3446 * can use this information to validate that the recipient is allowed to
3447 * receive the data.
3448 *
3449 * <p>Note: if the calling activity is not expecting a result (that is it
3450 * did not use the {@link #startActivityForResult}
3451 * form that includes a request code), then the calling package will be
3452 * null.
3453 *
3454 * @return String The full name of the activity that will receive your
3455 * reply, or null if none.
3456 */
3457 public ComponentName getCallingActivity() {
3458 try {
3459 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3460 } catch (RemoteException e) {
3461 return null;
3462 }
3463 }
3464
3465 /**
3466 * Control whether this activity's main window is visible. This is intended
3467 * only for the special case of an activity that is not going to show a
3468 * UI itself, but can't just finish prior to onResume() because it needs
3469 * to wait for a service binding or such. Setting this to false allows
3470 * you to prevent your UI from being shown during that time.
3471 *
3472 * <p>The default value for this is taken from the
3473 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3474 */
3475 public void setVisible(boolean visible) {
3476 if (mVisibleFromClient != visible) {
3477 mVisibleFromClient = visible;
3478 if (mVisibleFromServer) {
3479 if (visible) makeVisible();
3480 else mDecor.setVisibility(View.INVISIBLE);
3481 }
3482 }
3483 }
3484
3485 void makeVisible() {
3486 if (!mWindowAdded) {
3487 ViewManager wm = getWindowManager();
3488 wm.addView(mDecor, getWindow().getAttributes());
3489 mWindowAdded = true;
3490 }
3491 mDecor.setVisibility(View.VISIBLE);
3492 }
3493
3494 /**
3495 * Check to see whether this activity is in the process of finishing,
3496 * either because you called {@link #finish} on it or someone else
3497 * has requested that it finished. This is often used in
3498 * {@link #onPause} to determine whether the activity is simply pausing or
3499 * completely finishing.
3500 *
3501 * @return If the activity is finishing, returns true; else returns false.
3502 *
3503 * @see #finish
3504 */
3505 public boolean isFinishing() {
3506 return mFinished;
3507 }
3508
3509 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05003510 * Check to see whether this activity is in the process of being destroyed in order to be
3511 * recreated with a new configuration. This is often used in
3512 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
3513 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
3514 *
3515 * @return If the activity is being torn down in order to be recreated with a new configuration,
3516 * returns true; else returns false.
3517 */
3518 public boolean isChangingConfigurations() {
3519 return mChangingConfigurations;
3520 }
3521
3522 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08003523 * Cause this Activity to be recreated with a new instance. This results
3524 * in essentially the same flow as when the Activity is created due to
3525 * a configuration change -- the current instance will go through its
3526 * lifecycle to {@link #onDestroy} and a new instance then created after it.
3527 */
3528 public void recreate() {
3529 if (mParent != null) {
3530 throw new IllegalStateException("Can only be called on top-level activity");
3531 }
3532 if (Looper.myLooper() != mMainThread.getLooper()) {
3533 throw new IllegalStateException("Must be called from main thread");
3534 }
3535 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
3536 }
3537
3538 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 * Call this when your activity is done and should be closed. The
3540 * ActivityResult is propagated back to whoever launched you via
3541 * onActivityResult().
3542 */
3543 public void finish() {
3544 if (mParent == null) {
3545 int resultCode;
3546 Intent resultData;
3547 synchronized (this) {
3548 resultCode = mResultCode;
3549 resultData = mResultData;
3550 }
3551 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3552 try {
3553 if (ActivityManagerNative.getDefault()
3554 .finishActivity(mToken, resultCode, resultData)) {
3555 mFinished = true;
3556 }
3557 } catch (RemoteException e) {
3558 // Empty
3559 }
3560 } else {
3561 mParent.finishFromChild(this);
3562 }
3563 }
3564
3565 /**
3566 * This is called when a child activity of this one calls its
3567 * {@link #finish} method. The default implementation simply calls
3568 * finish() on this activity (the parent), finishing the entire group.
3569 *
3570 * @param child The activity making the call.
3571 *
3572 * @see #finish
3573 */
3574 public void finishFromChild(Activity child) {
3575 finish();
3576 }
3577
3578 /**
3579 * Force finish another activity that you had previously started with
3580 * {@link #startActivityForResult}.
3581 *
3582 * @param requestCode The request code of the activity that you had
3583 * given to startActivityForResult(). If there are multiple
3584 * activities started with this request code, they
3585 * will all be finished.
3586 */
3587 public void finishActivity(int requestCode) {
3588 if (mParent == null) {
3589 try {
3590 ActivityManagerNative.getDefault()
3591 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3592 } catch (RemoteException e) {
3593 // Empty
3594 }
3595 } else {
3596 mParent.finishActivityFromChild(this, requestCode);
3597 }
3598 }
3599
3600 /**
3601 * This is called when a child activity of this one calls its
3602 * finishActivity().
3603 *
3604 * @param child The activity making the call.
3605 * @param requestCode Request code that had been used to start the
3606 * activity.
3607 */
3608 public void finishActivityFromChild(Activity child, int requestCode) {
3609 try {
3610 ActivityManagerNative.getDefault()
3611 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3612 } catch (RemoteException e) {
3613 // Empty
3614 }
3615 }
3616
3617 /**
3618 * Called when an activity you launched exits, giving you the requestCode
3619 * you started it with, the resultCode it returned, and any additional
3620 * data from it. The <var>resultCode</var> will be
3621 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3622 * didn't return any result, or crashed during its operation.
3623 *
3624 * <p>You will receive this call immediately before onResume() when your
3625 * activity is re-starting.
3626 *
3627 * @param requestCode The integer request code originally supplied to
3628 * startActivityForResult(), allowing you to identify who this
3629 * result came from.
3630 * @param resultCode The integer result code returned by the child activity
3631 * through its setResult().
3632 * @param data An Intent, which can return result data to the caller
3633 * (various data can be attached to Intent "extras").
3634 *
3635 * @see #startActivityForResult
3636 * @see #createPendingResult
3637 * @see #setResult(int)
3638 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07003639 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641
3642 /**
3643 * Create a new PendingIntent object which you can hand to others
3644 * for them to use to send result data back to your
3645 * {@link #onActivityResult} callback. The created object will be either
3646 * one-shot (becoming invalid after a result is sent back) or multiple
3647 * (allowing any number of results to be sent through it).
3648 *
3649 * @param requestCode Private request code for the sender that will be
3650 * associated with the result data when it is returned. The sender can not
3651 * modify this value, allowing you to identify incoming results.
3652 * @param data Default data to supply in the result, which may be modified
3653 * by the sender.
3654 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3655 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3656 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3657 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3658 * or any of the flags as supported by
3659 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3660 * of the intent that can be supplied when the actual send happens.
3661 *
3662 * @return Returns an existing or new PendingIntent matching the given
3663 * parameters. May return null only if
3664 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3665 * supplied.
3666 *
3667 * @see PendingIntent
3668 */
3669 public PendingIntent createPendingResult(int requestCode, Intent data,
3670 int flags) {
3671 String packageName = getPackageName();
3672 try {
3673 IIntentSender target =
3674 ActivityManagerNative.getDefault().getIntentSender(
3675 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3676 mParent == null ? mToken : mParent.mToken,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003677 mEmbeddedID, requestCode, new Intent[] { data }, null, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 return target != null ? new PendingIntent(target) : null;
3679 } catch (RemoteException e) {
3680 // Empty
3681 }
3682 return null;
3683 }
3684
3685 /**
3686 * Change the desired orientation of this activity. If the activity
3687 * is currently in the foreground or otherwise impacting the screen
3688 * orientation, the screen will immediately be changed (possibly causing
3689 * the activity to be restarted). Otherwise, this will be used the next
3690 * time the activity is visible.
3691 *
3692 * @param requestedOrientation An orientation constant as used in
3693 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3694 */
3695 public void setRequestedOrientation(int requestedOrientation) {
3696 if (mParent == null) {
3697 try {
3698 ActivityManagerNative.getDefault().setRequestedOrientation(
3699 mToken, requestedOrientation);
3700 } catch (RemoteException e) {
3701 // Empty
3702 }
3703 } else {
3704 mParent.setRequestedOrientation(requestedOrientation);
3705 }
3706 }
3707
3708 /**
3709 * Return the current requested orientation of the activity. This will
3710 * either be the orientation requested in its component's manifest, or
3711 * the last requested orientation given to
3712 * {@link #setRequestedOrientation(int)}.
3713 *
3714 * @return Returns an orientation constant as used in
3715 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3716 */
3717 public int getRequestedOrientation() {
3718 if (mParent == null) {
3719 try {
3720 return ActivityManagerNative.getDefault()
3721 .getRequestedOrientation(mToken);
3722 } catch (RemoteException e) {
3723 // Empty
3724 }
3725 } else {
3726 return mParent.getRequestedOrientation();
3727 }
3728 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3729 }
3730
3731 /**
3732 * Return the identifier of the task this activity is in. This identifier
3733 * will remain the same for the lifetime of the activity.
3734 *
3735 * @return Task identifier, an opaque integer.
3736 */
3737 public int getTaskId() {
3738 try {
3739 return ActivityManagerNative.getDefault()
3740 .getTaskForActivity(mToken, false);
3741 } catch (RemoteException e) {
3742 return -1;
3743 }
3744 }
3745
3746 /**
3747 * Return whether this activity is the root of a task. The root is the
3748 * first activity in a task.
3749 *
3750 * @return True if this is the root activity, else false.
3751 */
3752 public boolean isTaskRoot() {
3753 try {
3754 return ActivityManagerNative.getDefault()
3755 .getTaskForActivity(mToken, true) >= 0;
3756 } catch (RemoteException e) {
3757 return false;
3758 }
3759 }
3760
3761 /**
3762 * Move the task containing this activity to the back of the activity
3763 * stack. The activity's order within the task is unchanged.
3764 *
3765 * @param nonRoot If false then this only works if the activity is the root
3766 * of a task; if true it will work for any activity in
3767 * a task.
3768 *
3769 * @return If the task was moved (or it was already at the
3770 * back) true is returned, else false.
3771 */
3772 public boolean moveTaskToBack(boolean nonRoot) {
3773 try {
3774 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3775 mToken, nonRoot);
3776 } catch (RemoteException e) {
3777 // Empty
3778 }
3779 return false;
3780 }
3781
3782 /**
3783 * Returns class name for this activity with the package prefix removed.
3784 * This is the default name used to read and write settings.
3785 *
3786 * @return The local class name.
3787 */
3788 public String getLocalClassName() {
3789 final String pkg = getPackageName();
3790 final String cls = mComponent.getClassName();
3791 int packageLen = pkg.length();
3792 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3793 || cls.charAt(packageLen) != '.') {
3794 return cls;
3795 }
3796 return cls.substring(packageLen+1);
3797 }
3798
3799 /**
3800 * Returns complete component name of this activity.
3801 *
3802 * @return Returns the complete component name for this activity
3803 */
3804 public ComponentName getComponentName()
3805 {
3806 return mComponent;
3807 }
3808
3809 /**
3810 * Retrieve a {@link SharedPreferences} object for accessing preferences
3811 * that are private to this activity. This simply calls the underlying
3812 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3813 * class name as the preferences name.
3814 *
3815 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3816 * operation, {@link #MODE_WORLD_READABLE} and
3817 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3818 *
3819 * @return Returns the single SharedPreferences instance that can be used
3820 * to retrieve and modify the preference values.
3821 */
3822 public SharedPreferences getPreferences(int mode) {
3823 return getSharedPreferences(getLocalClassName(), mode);
3824 }
3825
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003826 private void ensureSearchManager() {
3827 if (mSearchManager != null) {
3828 return;
3829 }
3830
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003831 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003832 }
3833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 @Override
3835 public Object getSystemService(String name) {
3836 if (getBaseContext() == null) {
3837 throw new IllegalStateException(
3838 "System services not available to Activities before onCreate()");
3839 }
3840
3841 if (WINDOW_SERVICE.equals(name)) {
3842 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003843 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003844 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003845 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 }
3847 return super.getSystemService(name);
3848 }
3849
3850 /**
3851 * Change the title associated with this activity. If this is a
3852 * top-level activity, the title for its window will change. If it
3853 * is an embedded activity, the parent can do whatever it wants
3854 * with it.
3855 */
3856 public void setTitle(CharSequence title) {
3857 mTitle = title;
3858 onTitleChanged(title, mTitleColor);
3859
3860 if (mParent != null) {
3861 mParent.onChildTitleChanged(this, title);
3862 }
3863 }
3864
3865 /**
3866 * Change the title associated with this activity. If this is a
3867 * top-level activity, the title for its window will change. If it
3868 * is an embedded activity, the parent can do whatever it wants
3869 * with it.
3870 */
3871 public void setTitle(int titleId) {
3872 setTitle(getText(titleId));
3873 }
3874
3875 public void setTitleColor(int textColor) {
3876 mTitleColor = textColor;
3877 onTitleChanged(mTitle, textColor);
3878 }
3879
3880 public final CharSequence getTitle() {
3881 return mTitle;
3882 }
3883
3884 public final int getTitleColor() {
3885 return mTitleColor;
3886 }
3887
3888 protected void onTitleChanged(CharSequence title, int color) {
3889 if (mTitleReady) {
3890 final Window win = getWindow();
3891 if (win != null) {
3892 win.setTitle(title);
3893 if (color != 0) {
3894 win.setTitleColor(color);
3895 }
3896 }
3897 }
3898 }
3899
3900 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3901 }
3902
3903 /**
3904 * Sets the visibility of the progress bar in the title.
3905 * <p>
3906 * In order for the progress bar to be shown, the feature must be requested
3907 * via {@link #requestWindowFeature(int)}.
3908 *
3909 * @param visible Whether to show the progress bars in the title.
3910 */
3911 public final void setProgressBarVisibility(boolean visible) {
3912 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3913 Window.PROGRESS_VISIBILITY_OFF);
3914 }
3915
3916 /**
3917 * Sets the visibility of the indeterminate progress bar in the title.
3918 * <p>
3919 * In order for the progress bar to be shown, the feature must be requested
3920 * via {@link #requestWindowFeature(int)}.
3921 *
3922 * @param visible Whether to show the progress bars in the title.
3923 */
3924 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3925 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3926 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3927 }
3928
3929 /**
3930 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3931 * is always indeterminate).
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 indeterminate Whether the horizontal progress bar should be indeterminate.
3937 */
3938 public final void setProgressBarIndeterminate(boolean indeterminate) {
3939 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3940 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3941 }
3942
3943 /**
3944 * Sets the progress for the progress bars in the title.
3945 * <p>
3946 * In order for the progress bar to be shown, the feature must be requested
3947 * via {@link #requestWindowFeature(int)}.
3948 *
3949 * @param progress The progress for the progress bar. Valid ranges are from
3950 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3951 * bar will be completely filled and will fade out.
3952 */
3953 public final void setProgress(int progress) {
3954 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3955 }
3956
3957 /**
3958 * Sets the secondary progress for the progress bar in the title. This
3959 * progress is drawn between the primary progress (set via
3960 * {@link #setProgress(int)} and the background. It can be ideal for media
3961 * scenarios such as showing the buffering progress while the default
3962 * progress shows the play progress.
3963 * <p>
3964 * In order for the progress bar to be shown, the feature must be requested
3965 * via {@link #requestWindowFeature(int)}.
3966 *
3967 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3968 * 0 to 10000 (both inclusive).
3969 */
3970 public final void setSecondaryProgress(int secondaryProgress) {
3971 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3972 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3973 }
3974
3975 /**
3976 * Suggests an audio stream whose volume should be changed by the hardware
3977 * volume controls.
3978 * <p>
3979 * The suggested audio stream will be tied to the window of this Activity.
3980 * If the Activity is switched, the stream set here is no longer the
3981 * suggested stream. The client does not need to save and restore the old
3982 * suggested stream value in onPause and onResume.
3983 *
3984 * @param streamType The type of the audio stream whose volume should be
3985 * changed by the hardware volume controls. It is not guaranteed that
3986 * the hardware volume controls will always change this stream's
3987 * volume (for example, if a call is in progress, its stream's volume
3988 * may be changed instead). To reset back to the default, use
3989 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3990 */
3991 public final void setVolumeControlStream(int streamType) {
3992 getWindow().setVolumeControlStream(streamType);
3993 }
3994
3995 /**
3996 * Gets the suggested audio stream whose volume should be changed by the
3997 * harwdare volume controls.
3998 *
3999 * @return The suggested audio stream type whose volume should be changed by
4000 * the hardware volume controls.
4001 * @see #setVolumeControlStream(int)
4002 */
4003 public final int getVolumeControlStream() {
4004 return getWindow().getVolumeControlStream();
4005 }
4006
4007 /**
4008 * Runs the specified action on the UI thread. If the current thread is the UI
4009 * thread, then the action is executed immediately. If the current thread is
4010 * not the UI thread, the action is posted to the event queue of the UI thread.
4011 *
4012 * @param action the action to run on the UI thread
4013 */
4014 public final void runOnUiThread(Runnable action) {
4015 if (Thread.currentThread() != mUiThread) {
4016 mHandler.post(action);
4017 } else {
4018 action.run();
4019 }
4020 }
4021
4022 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004023 * Standard implementation of
4024 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
4025 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004026 * This implementation does nothing and is for
4027 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
4028 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
4029 *
4030 * @see android.view.LayoutInflater#createView
4031 * @see android.view.Window#getLayoutInflater
4032 */
4033 public View onCreateView(String name, Context context, AttributeSet attrs) {
4034 return null;
4035 }
4036
4037 /**
4038 * Standard implementation of
4039 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
4040 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004041 * This implementation handles <fragment> tags to embed fragments inside
4042 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 *
4044 * @see android.view.LayoutInflater#createView
4045 * @see android.view.Window#getLayoutInflater
4046 */
Dianne Hackborn625ac272010-09-17 18:29:22 -07004047 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004048 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07004049 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004050 }
4051
Dianne Hackborndef15372010-08-15 12:43:52 -07004052 String fname = attrs.getAttributeValue(null, "class");
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004053 TypedArray a =
4054 context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.Fragment);
Dianne Hackborndef15372010-08-15 12:43:52 -07004055 if (fname == null) {
4056 fname = a.getString(com.android.internal.R.styleable.Fragment_name);
4057 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004058 int id = a.getResourceId(com.android.internal.R.styleable.Fragment_id, View.NO_ID);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004059 String tag = a.getString(com.android.internal.R.styleable.Fragment_tag);
4060 a.recycle();
4061
Dianne Hackborn625ac272010-09-17 18:29:22 -07004062 int containerId = parent != null ? parent.getId() : 0;
4063 if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004064 throw new IllegalArgumentException(attrs.getPositionDescription()
Dianne Hackborn625ac272010-09-17 18:29:22 -07004065 + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004066 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004067
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004068 // If we restored from a previous state, we may already have
4069 // instantiated this fragment from the state and should use
4070 // that instance instead of making a new one.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004071 Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
4072 if (fragment == null && tag != null) {
4073 fragment = mFragments.findFragmentByTag(tag);
4074 }
4075 if (fragment == null && containerId != View.NO_ID) {
4076 fragment = mFragments.findFragmentById(containerId);
4077 }
4078
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004079 if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
4080 + Integer.toHexString(id) + " fname=" + fname
4081 + " existing=" + fragment);
4082 if (fragment == null) {
4083 fragment = Fragment.instantiate(this, fname);
4084 fragment.mFromLayout = true;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004085 fragment.mFragmentId = id != 0 ? id : containerId;
4086 fragment.mContainerId = containerId;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004087 fragment.mTag = tag;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004088 fragment.mInLayout = true;
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004089 fragment.mImmediateActivity = this;
Dianne Hackborn3e449ce2010-09-11 20:52:31 -07004090 fragment.mFragmentManager = mFragments;
Dianne Hackborn625ac272010-09-17 18:29:22 -07004091 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4092 mFragments.addFragment(fragment, true);
4093
4094 } else if (fragment.mInLayout) {
4095 // A fragment already exists and it is not one we restored from
4096 // previous state.
4097 throw new IllegalArgumentException(attrs.getPositionDescription()
4098 + ": Duplicate id 0x" + Integer.toHexString(id)
4099 + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
4100 + " with another fragment for " + fname);
4101 } else {
4102 // This fragment was retained from a previous instance; get it
4103 // going now.
4104 fragment.mInLayout = true;
4105 fragment.mImmediateActivity = this;
Dianne Hackborndef15372010-08-15 12:43:52 -07004106 // If this fragment is newly instantiated (either right now, or
4107 // from last saved state), then give it the attributes to
4108 // initialize itself.
4109 if (!fragment.mRetaining) {
4110 fragment.onInflate(attrs, fragment.mSavedFragmentState);
4111 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004112 mFragments.moveToState(fragment);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07004113 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004114
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004115 if (fragment.mView == null) {
4116 throw new IllegalStateException("Fragment " + fname
4117 + " did not create a view.");
4118 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07004119 if (id != 0) {
4120 fragment.mView.setId(id);
4121 }
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07004122 if (fragment.mView.getTag() == null) {
4123 fragment.mView.setTag(tag);
4124 }
4125 return fragment.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
Daniel Sandler69a48172010-06-23 16:29:36 -04004128 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07004129 * Print the Activity's state into the given stream. This gets invoked if
Dianne Hackborn30d71892010-12-11 10:37:55 -08004130 * you run "adb shell dumpsys activity <activity_component_name>".
Dianne Hackborn625ac272010-09-17 18:29:22 -07004131 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08004132 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07004133 * @param fd The raw file descriptor that the dump is being sent to.
4134 * @param writer The PrintWriter to which you should dump your state. This will be
4135 * closed for you after you return.
4136 * @param args additional arguments to the dump request.
4137 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08004138 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4139 writer.print(prefix); writer.print("Local Activity ");
4140 writer.print(Integer.toHexString(System.identityHashCode(this)));
4141 writer.println(" State:");
4142 String innerPrefix = prefix + " ";
4143 writer.print(innerPrefix); writer.print("mResumed=");
4144 writer.print(mResumed); writer.print(" mStopped=");
4145 writer.print(mStopped); writer.print(" mFinished=");
4146 writer.println(mFinished);
4147 writer.print(innerPrefix); writer.print("mLoadersStarted=");
4148 writer.println(mLoadersStarted);
4149 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
4150 writer.println(mChangingConfigurations);
4151 writer.print(innerPrefix); writer.print("mCurrentConfig=");
4152 writer.println(mCurrentConfig);
4153 if (mLoaderManager != null) {
4154 writer.print(prefix); writer.print("Loader Manager ");
4155 writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
4156 writer.println(":");
4157 mLoaderManager.dump(prefix + " ", fd, writer, args);
4158 }
4159 mFragments.dump(prefix, fd, writer, args);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004160 }
4161
4162 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04004163 * Bit indicating that this activity is "immersive" and should not be
4164 * interrupted by notifications if possible.
4165 *
4166 * This value is initially set by the manifest property
4167 * <code>android:immersive</code> but may be changed at runtime by
4168 * {@link #setImmersive}.
4169 *
4170 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004171 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004172 */
4173 public boolean isImmersive() {
4174 try {
4175 return ActivityManagerNative.getDefault().isImmersive(mToken);
4176 } catch (RemoteException e) {
4177 return false;
4178 }
4179 }
4180
4181 /**
4182 * Adjust the current immersive mode setting.
4183 *
4184 * Note that changing this value will have no effect on the activity's
4185 * {@link android.content.pm.ActivityInfo} structure; that is, if
4186 * <code>android:immersive</code> is set to <code>true</code>
4187 * in the application's manifest entry for this activity, the {@link
4188 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
4189 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
4190 * FLAG_IMMERSIVE} bit set.
4191 *
4192 * @see #isImmersive
4193 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
Dianne Hackborn02486b12010-08-26 14:18:37 -07004194 * @hide
Daniel Sandler69a48172010-06-23 16:29:36 -04004195 */
4196 public void setImmersive(boolean i) {
4197 try {
4198 ActivityManagerNative.getDefault().setImmersive(mToken, i);
4199 } catch (RemoteException e) {
4200 // pass
4201 }
4202 }
4203
Adam Powell6e346362010-07-23 10:18:23 -07004204 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08004205 * Start an action mode.
Adam Powell6e346362010-07-23 10:18:23 -07004206 *
4207 * @param callback Callback that will manage lifecycle events for this context mode
4208 * @return The ContextMode that was started, or null if it was canceled
4209 *
4210 * @see ActionMode
4211 */
Adam Powell5d279772010-07-27 16:34:07 -07004212 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07004213 return mWindow.getDecorView().startActionMode(callback);
4214 }
4215
Adam Powelldebf3be2010-11-15 18:58:48 -08004216 /**
4217 * Give the Activity a chance to control the UI for an action mode requested
4218 * by the system.
4219 *
4220 * <p>Note: If you are looking for a notification callback that an action mode
4221 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
4222 *
4223 * @param callback The callback that should control the new action mode
4224 * @return The new action mode, or <code>null</code> if the activity does not want to
4225 * provide special handling for this action mode. (It will be handled by the system.)
4226 */
4227 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Adam Powell42c0fe82010-08-10 16:36:56 -07004228 initActionBar();
Adam Powell6e346362010-07-23 10:18:23 -07004229 if (mActionBar != null) {
Adam Powell5d279772010-07-27 16:34:07 -07004230 return mActionBar.startActionMode(callback);
Adam Powell6e346362010-07-23 10:18:23 -07004231 }
4232 return null;
4233 }
4234
Adam Powelldebf3be2010-11-15 18:58:48 -08004235 /**
4236 * Notifies the Activity that an action mode has been started.
4237 * Activity subclasses overriding this method should call the superclass implementation.
4238 *
4239 * @param mode The new action mode.
4240 */
4241 public void onActionModeStarted(ActionMode mode) {
4242 }
4243
4244 /**
4245 * Notifies the activity that an action mode has finished.
4246 * Activity subclasses overriding this method should call the superclass implementation.
4247 *
4248 * @param mode The action mode that just finished.
4249 */
4250 public void onActionModeFinished(ActionMode mode) {
4251 }
4252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 // ------------------ Internal API ------------------
4254
4255 final void setParent(Activity parent) {
4256 mParent = parent;
4257 }
4258
4259 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
4260 Application application, Intent intent, ActivityInfo info, CharSequence title,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004261 Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004263 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004264 lastNonConfigurationInstances, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 }
4266
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004267 final void attach(Context context, ActivityThread aThread,
4268 Instrumentation instr, IBinder token, int ident,
4269 Application application, Intent intent, ActivityInfo info,
4270 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004271 NonConfigurationInstances lastNonConfigurationInstances,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004272 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 attachBaseContext(context);
4274
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004275 mFragments.attachActivity(this);
4276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 mWindow = PolicyManager.makeNewWindow(this);
4278 mWindow.setCallback(this);
Dianne Hackborn625ac272010-09-17 18:29:22 -07004279 mWindow.getLayoutInflater().setFactory2(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
4281 mWindow.setSoftInputMode(info.softInputMode);
4282 }
4283 mUiThread = Thread.currentThread();
Romain Guy529b60a2010-08-03 18:05:47 -07004284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 mMainThread = aThread;
4286 mInstrumentation = instr;
4287 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004288 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 mApplication = application;
4290 mIntent = intent;
4291 mComponent = intent.getComponent();
4292 mActivityInfo = info;
4293 mTitle = title;
4294 mParent = parent;
4295 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004296 mLastNonConfigurationInstances = lastNonConfigurationInstances;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297
Romain Guy529b60a2010-08-03 18:05:47 -07004298 mWindow.setWindowManager(null, mToken, mComponent.flattenToString(),
4299 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 if (mParent != null) {
4301 mWindow.setContainer(mParent.getWindow());
4302 }
4303 mWindowManager = mWindow.getWindowManager();
4304 mCurrentConfig = config;
4305 }
4306
4307 final IBinder getActivityToken() {
4308 return mParent != null ? mParent.getActivityToken() : mToken;
4309 }
4310
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004311 final void performCreate(Bundle icicle) {
4312 onCreate(icicle);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08004313 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
4314 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07004315 mFragments.dispatchActivityCreated();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004316 }
4317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 final void performStart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004319 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07004321 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 mInstrumentation.callActivityOnStart(this);
4323 if (!mCalled) {
4324 throw new SuperNotCalledException(
4325 "Activity " + mComponent.toShortString() +
4326 " did not call through to super.onStart()");
4327 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004328 mFragments.dispatchStart();
Dianne Hackborn2707d602010-07-09 18:01:20 -07004329 if (mAllLoaderManagers != null) {
4330 for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
4331 mAllLoaderManagers.valueAt(i).finishRetain();
4332 }
4333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335
4336 final void performRestart() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004337 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07004338
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004339 synchronized (mManagedCursors) {
4340 final int N = mManagedCursors.size();
4341 for (int i=0; i<N; i++) {
4342 ManagedCursor mc = mManagedCursors.get(i);
4343 if (mc.mReleased || mc.mUpdated) {
Vasu Noria7dd5ea2010-08-04 11:57:51 -07004344 if (!mc.mCursor.requery()) {
4345 throw new IllegalStateException(
4346 "trying to requery an already closed cursor");
4347 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004348 mc.mReleased = false;
4349 mc.mUpdated = false;
4350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352 }
4353
4354 if (mStopped) {
4355 mStopped = false;
4356 mCalled = false;
4357 mInstrumentation.callActivityOnRestart(this);
4358 if (!mCalled) {
4359 throw new SuperNotCalledException(
4360 "Activity " + mComponent.toShortString() +
4361 " did not call through to super.onRestart()");
4362 }
4363 performStart();
4364 }
4365 }
4366
4367 final void performResume() {
4368 performRestart();
4369
Dianne Hackborn445646c2010-06-25 15:52:59 -07004370 mFragments.execPendingActions();
4371
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07004372 mLastNonConfigurationInstances = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373
4374 // First call onResume() -before- setting mResumed, so we don't
4375 // send out any status bar / menu notifications the client makes.
4376 mCalled = false;
4377 mInstrumentation.callActivityOnResume(this);
4378 if (!mCalled) {
4379 throw new SuperNotCalledException(
4380 "Activity " + mComponent.toShortString() +
4381 " did not call through to super.onResume()");
4382 }
4383
4384 // Now really resume, and install the current status bar and menu.
4385 mResumed = true;
4386 mCalled = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004387
4388 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07004389 mFragments.execPendingActions();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 onPostResume();
4392 if (!mCalled) {
4393 throw new SuperNotCalledException(
4394 "Activity " + mComponent.toShortString() +
4395 " did not call through to super.onPostResume()");
4396 }
4397 }
4398
4399 final void performPause() {
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004400 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004401 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 onPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07004403 if (!mCalled && getApplicationInfo().targetSdkVersion
4404 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
4405 throw new SuperNotCalledException(
4406 "Activity " + mComponent.toShortString() +
4407 " did not call through to super.onPause()");
4408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 }
4410
4411 final void performUserLeaving() {
4412 onUserInteraction();
4413 onUserLeaveHint();
4414 }
4415
4416 final void performStop() {
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004417 if (mLoadersStarted) {
4418 mLoadersStarted = false;
Dianne Hackborn2707d602010-07-09 18:01:20 -07004419 if (mLoaderManager != null) {
4420 if (!mChangingConfigurations) {
4421 mLoaderManager.doStop();
4422 } else {
4423 mLoaderManager.doRetain();
4424 }
4425 }
4426 }
4427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 if (!mStopped) {
4429 if (mWindow != null) {
4430 mWindow.closeAllPanels();
4431 }
4432
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004433 mFragments.dispatchStop();
4434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 mCalled = false;
4436 mInstrumentation.callActivityOnStop(this);
4437 if (!mCalled) {
4438 throw new SuperNotCalledException(
4439 "Activity " + mComponent.toShortString() +
4440 " did not call through to super.onStop()");
4441 }
4442
Makoto Onuki2f6a0182010-02-22 13:26:59 -08004443 synchronized (mManagedCursors) {
4444 final int N = mManagedCursors.size();
4445 for (int i=0; i<N; i++) {
4446 ManagedCursor mc = mManagedCursors.get(i);
4447 if (!mc.mReleased) {
4448 mc.mCursor.deactivate();
4449 mc.mReleased = true;
4450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 }
4452 }
4453
4454 mStopped = true;
4455 }
4456 mResumed = false;
4457 }
4458
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004459 final void performDestroy() {
Dianne Hackborn291905e2010-08-17 15:17:15 -07004460 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004461 mFragments.dispatchDestroy();
4462 onDestroy();
Dianne Hackborn5e0d5952010-08-05 13:45:35 -07004463 if (mLoaderManager != null) {
4464 mLoaderManager.doDestroy();
4465 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07004466 }
4467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 final boolean isResumed() {
4469 return mResumed;
4470 }
4471
4472 void dispatchActivityResult(String who, int requestCode,
4473 int resultCode, Intent data) {
4474 if (Config.LOGV) Log.v(
4475 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
4476 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07004477 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 if (who == null) {
4479 onActivityResult(requestCode, resultCode, data);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07004480 } else {
4481 Fragment frag = mFragments.findFragmentByWho(who);
4482 if (frag != null) {
4483 frag.onActivityResult(requestCode, resultCode, data);
4484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487}