blob: b38aedae96b2ed8e28be2e9d3c2a5501d99ef410 [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
svetoslavganov75986cf2009-05-14 22:28:01 -070019import com.android.internal.policy.PolicyManager;
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.ComponentCallbacks;
22import android.content.ComponentName;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070026import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070027import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.SharedPreferences;
29import android.content.pm.ActivityInfo;
30import android.content.res.Configuration;
31import android.content.res.Resources;
32import android.database.Cursor;
33import android.graphics.Bitmap;
34import android.graphics.Canvas;
35import android.graphics.drawable.Drawable;
36import android.media.AudioManager;
37import android.net.Uri;
Dianne Hackborn8d374262009-09-14 21:21:52 -070038import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Handler;
41import android.os.IBinder;
Amith Yamasanie9ce3f02010-01-25 09:15:50 -080042import android.os.Looper;
svetoslavganov75986cf2009-05-14 22:28:01 -070043import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.text.Selection;
45import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070046import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.text.method.TextKeyListener;
48import android.util.AttributeSet;
49import android.util.Config;
50import android.util.EventLog;
51import android.util.Log;
52import android.util.SparseArray;
53import android.view.ContextMenu;
54import android.view.ContextThemeWrapper;
55import android.view.KeyEvent;
56import android.view.LayoutInflater;
57import android.view.Menu;
58import android.view.MenuInflater;
59import android.view.MenuItem;
60import android.view.MotionEvent;
61import android.view.View;
62import android.view.ViewGroup;
63import android.view.ViewManager;
64import android.view.Window;
65import android.view.WindowManager;
66import android.view.ContextMenu.ContextMenuInfo;
67import android.view.View.OnCreateContextMenuListener;
svetoslavganov75986cf2009-05-14 22:28:01 -070068import android.view.ViewGroup.LayoutParams;
69import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.widget.AdapterView;
71
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
73import java.util.HashMap;
74
75/**
76 * An activity is a single, focused thing that the user can do. Almost all
77 * activities interact with the user, so the Activity class takes care of
78 * creating a window for you in which you can place your UI with
79 * {@link #setContentView}. While activities are often presented to the user
80 * as full-screen windows, they can also be used in other ways: as floating
81 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
82 * or embedded inside of another activity (using {@link ActivityGroup}).
83 *
84 * There are two methods almost all subclasses of Activity will implement:
85 *
86 * <ul>
87 * <li> {@link #onCreate} is where you initialize your activity. Most
88 * importantly, here you will usually call {@link #setContentView(int)}
89 * with a layout resource defining your UI, and using {@link #findViewById}
90 * to retrieve the widgets in that UI that you need to interact with
91 * programmatically.
92 *
93 * <li> {@link #onPause} is where you deal with the user leaving your
94 * activity. Most importantly, any changes made by the user should at this
95 * point be committed (usually to the
96 * {@link android.content.ContentProvider} holding the data).
97 * </ul>
98 *
99 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
100 * activity classes must have a corresponding
101 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
102 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
103 *
104 * <p>The Activity class is an important part of an application's overall lifecycle,
105 * and the way activities are launched and put together is a fundamental
106 * part of the platform's application model. For a detailed perspective on the structure of
107 * Android applications and lifecycles, please read the <em>Dev Guide</em> document on
108 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
109 *
110 * <p>Topics covered here:
111 * <ol>
112 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
113 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
114 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
115 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
116 * <li><a href="#Permissions">Permissions</a>
117 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
118 * </ol>
119 *
120 * <a name="ActivityLifecycle"></a>
121 * <h3>Activity Lifecycle</h3>
122 *
123 * <p>Activities in the system are managed as an <em>activity stack</em>.
124 * When a new activity is started, it is placed on the top of the stack
125 * and becomes the running activity -- the previous activity always remains
126 * below it in the stack, and will not come to the foreground again until
127 * the new activity exits.</p>
128 *
129 * <p>An activity has essentially four states:</p>
130 * <ul>
131 * <li> If an activity in the foreground of the screen (at the top of
132 * the stack),
133 * it is <em>active</em> or <em>running</em>. </li>
134 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
135 * or transparent activity has focus on top of your activity), it
136 * is <em>paused</em>. A paused activity is completely alive (it
137 * maintains all state and member information and remains attached to
138 * the window manager), but can be killed by the system in extreme
139 * low memory situations.
140 * <li>If an activity is completely obscured by another activity,
141 * it is <em>stopped</em>. It still retains all state and member information,
142 * however, it is no longer visible to the user so its window is hidden
143 * and it will often be killed by the system when memory is needed
144 * elsewhere.</li>
145 * <li>If an activity is paused or stopped, the system can drop the activity
146 * from memory by either asking it to finish, or simply killing its
147 * process. When it is displayed again to the user, it must be
148 * completely restarted and restored to its previous state.</li>
149 * </ul>
150 *
151 * <p>The following diagram shows the important state paths of an Activity.
152 * The square rectangles represent callback methods you can implement to
153 * perform operations when the Activity moves between states. The colored
154 * ovals are major states the Activity can be in.</p>
155 *
156 * <p><img src="../../../images/activity_lifecycle.png"
157 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
158 *
159 * <p>There are three key loops you may be interested in monitoring within your
160 * activity:
161 *
162 * <ul>
163 * <li>The <b>entire lifetime</b> of an activity happens between the first call
164 * to {@link android.app.Activity#onCreate} through to a single final call
165 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
166 * of "global" state in onCreate(), and release all remaining resources in
167 * onDestroy(). For example, if it has a thread running in the background
168 * to download data from the network, it may create that thread in onCreate()
169 * and then stop the thread in onDestroy().
170 *
171 * <li>The <b>visible lifetime</b> of an activity happens between a call to
172 * {@link android.app.Activity#onStart} until a corresponding call to
173 * {@link android.app.Activity#onStop}. During this time the user can see the
174 * activity on-screen, though it may not be in the foreground and interacting
175 * with the user. Between these two methods you can maintain resources that
176 * are needed to show the activity to the user. For example, you can register
177 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
178 * that impact your UI, and unregister it in onStop() when the user an no
179 * longer see what you are displaying. The onStart() and onStop() methods
180 * can be called multiple times, as the activity becomes visible and hidden
181 * to the user.
182 *
183 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
184 * {@link android.app.Activity#onResume} until a corresponding call to
185 * {@link android.app.Activity#onPause}. During this time the activity is
186 * in front of all other activities and interacting with the user. An activity
187 * can frequently go between the resumed and paused states -- for example when
188 * the device goes to sleep, when an activity result is delivered, when a new
189 * intent is delivered -- so the code in these methods should be fairly
190 * lightweight.
191 * </ul>
192 *
193 * <p>The entire lifecycle of an activity is defined by the following
194 * Activity methods. All of these are hooks that you can override
195 * to do appropriate work when the activity changes state. All
196 * activities will implement {@link android.app.Activity#onCreate}
197 * to do their initial setup; many will also implement
198 * {@link android.app.Activity#onPause} to commit changes to data and
199 * otherwise prepare to stop interacting with the user. You should always
200 * call up to your superclass when implementing these methods.</p>
201 *
202 * </p>
203 * <pre class="prettyprint">
204 * public class Activity extends ApplicationContext {
205 * protected void onCreate(Bundle savedInstanceState);
206 *
207 * protected void onStart();
208 *
209 * protected void onRestart();
210 *
211 * protected void onResume();
212 *
213 * protected void onPause();
214 *
215 * protected void onStop();
216 *
217 * protected void onDestroy();
218 * }
219 * </pre>
220 *
221 * <p>In general the movement through an activity's lifecycle looks like
222 * this:</p>
223 *
224 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
225 * <colgroup align="left" span="3" />
226 * <colgroup align="left" />
227 * <colgroup align="center" />
228 * <colgroup align="center" />
229 *
230 * <thead>
231 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
232 * </thead>
233 *
234 * <tbody>
235 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th>
236 * <td>Called when the activity is first created.
237 * This is where you should do all of your normal static set up:
238 * create views, bind data to lists, etc. This method also
239 * provides you with a Bundle containing the activity's previously
240 * frozen state, if there was one.
241 * <p>Always followed by <code>onStart()</code>.</td>
242 * <td align="center">No</td>
243 * <td align="center"><code>onStart()</code></td>
244 * </tr>
245 *
246 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
247 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th>
248 * <td>Called after your activity has been stopped, prior to it being
249 * started again.
250 * <p>Always followed by <code>onStart()</code></td>
251 * <td align="center">No</td>
252 * <td align="center"><code>onStart()</code></td>
253 * </tr>
254 *
255 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th>
256 * <td>Called when the activity is becoming visible to the user.
257 * <p>Followed by <code>onResume()</code> if the activity comes
258 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
259 * <td align="center">No</td>
260 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
261 * </tr>
262 *
263 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
264 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th>
265 * <td>Called when the activity will start
266 * interacting with the user. At this point your activity is at
267 * the top of the activity stack, with user input going to it.
268 * <p>Always followed by <code>onPause()</code>.</td>
269 * <td align="center">No</td>
270 * <td align="center"><code>onPause()</code></td>
271 * </tr>
272 *
273 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th>
274 * <td>Called when the system is about to start resuming a previous
275 * activity. This is typically used to commit unsaved changes to
276 * persistent data, stop animations and other things that may be consuming
277 * CPU, etc. Implementations of this method must be very quick because
278 * the next activity will not be resumed until this method returns.
279 * <p>Followed by either <code>onResume()</code> if the activity
280 * returns back to the front, or <code>onStop()</code> if it becomes
281 * invisible to the user.</td>
282 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
283 * <td align="center"><code>onResume()</code> or<br>
284 * <code>onStop()</code></td>
285 * </tr>
286 *
287 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th>
288 * <td>Called when the activity is no longer visible to the user, because
289 * another activity has been resumed and is covering this one. This
290 * may happen either because a new activity is being started, an existing
291 * one is being brought in front of this one, or this one is being
292 * destroyed.
293 * <p>Followed by either <code>onRestart()</code> if
294 * this activity is coming back to interact with the user, or
295 * <code>onDestroy()</code> if this activity is going away.</td>
296 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
297 * <td align="center"><code>onRestart()</code> or<br>
298 * <code>onDestroy()</code></td>
299 * </tr>
300 *
301 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th>
302 * <td>The final call you receive before your
303 * activity is destroyed. This can happen either because the
304 * activity is finishing (someone called {@link Activity#finish} on
305 * it, or because the system is temporarily destroying this
306 * instance of the activity to save space. You can distinguish
307 * between these two scenarios with the {@link
308 * Activity#isFinishing} method.</td>
309 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
310 * <td align="center"><em>nothing</em></td>
311 * </tr>
312 * </tbody>
313 * </table>
314 *
315 * <p>Note the "Killable" column in the above table -- for those methods that
316 * are marked as being killable, after that method returns the process hosting the
317 * activity may killed by the system <em>at any time</em> without another line
318 * of its code being executed. Because of this, you should use the
319 * {@link #onPause} method to write any persistent data (such as user edits)
320 * to storage. In addition, the method
321 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
322 * in such a background state, allowing you to save away any dynamic instance
323 * state in your activity into the given Bundle, to be later received in
324 * {@link #onCreate} if the activity needs to be re-created.
325 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
326 * section for more information on how the lifecycle of a process is tied
327 * to the activities it is hosting. Note that it is important to save
328 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
329 * because the later is not part of the lifecycle callbacks, so will not
330 * be called in every situation as described in its documentation.</p>
331 *
332 * <p>For those methods that are not marked as being killable, the activity's
333 * process will not be killed by the system starting from the time the method
334 * is called and continuing after it returns. Thus an activity is in the killable
335 * state, for example, between after <code>onPause()</code> to the start of
336 * <code>onResume()</code>.</p>
337 *
338 * <a name="ConfigurationChanges"></a>
339 * <h3>Configuration Changes</h3>
340 *
341 * <p>If the configuration of the device (as defined by the
342 * {@link Configuration Resources.Configuration} class) changes,
343 * then anything displaying a user interface will need to update to match that
344 * configuration. Because Activity is the primary mechanism for interacting
345 * with the user, it includes special support for handling configuration
346 * changes.</p>
347 *
348 * <p>Unless you specify otherwise, a configuration change (such as a change
349 * in screen orientation, language, input devices, etc) will cause your
350 * current activity to be <em>destroyed</em>, going through the normal activity
351 * lifecycle process of {@link #onPause},
352 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
353 * had been in the foreground or visible to the user, once {@link #onDestroy} is
354 * called in that instance then a new instance of the activity will be
355 * created, with whatever savedInstanceState the previous instance had generated
356 * from {@link #onSaveInstanceState}.</p>
357 *
358 * <p>This is done because any application resource,
359 * including layout files, can change based on any configuration value. Thus
360 * the only safe way to handle a configuration change is to re-retrieve all
361 * resources, including layouts, drawables, and strings. Because activities
362 * must already know how to save their state and re-create themselves from
363 * that state, this is a convenient way to have an activity restart itself
364 * with a new configuration.</p>
365 *
366 * <p>In some special cases, you may want to bypass restarting of your
367 * activity based on one or more types of configuration changes. This is
368 * done with the {@link android.R.attr#configChanges android:configChanges}
369 * attribute in its manifest. For any types of configuration changes you say
370 * that you handle there, you will receive a call to your current activity's
371 * {@link #onConfigurationChanged} method instead of being restarted. If
372 * a configuration change involves any that you do not handle, however, the
373 * activity will still be restarted and {@link #onConfigurationChanged}
374 * will not be called.</p>
375 *
376 * <a name="StartingActivities"></a>
377 * <h3>Starting Activities and Getting Results</h3>
378 *
379 * <p>The {@link android.app.Activity#startActivity}
380 * method is used to start a
381 * new activity, which will be placed at the top of the activity stack. It
382 * takes a single argument, an {@link android.content.Intent Intent},
383 * which describes the activity
384 * to be executed.</p>
385 *
386 * <p>Sometimes you want to get a result back from an activity when it
387 * ends. For example, you may start an activity that lets the user pick
388 * a person in a list of contacts; when it ends, it returns the person
389 * that was selected. To do this, you call the
390 * {@link android.app.Activity#startActivityForResult(Intent, int)}
391 * version with a second integer parameter identifying the call. The result
392 * will come back through your {@link android.app.Activity#onActivityResult}
393 * method.</p>
394 *
395 * <p>When an activity exits, it can call
396 * {@link android.app.Activity#setResult(int)}
397 * to return data back to its parent. It must always supply a result code,
398 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
399 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
400 * return back an Intent containing any additional data it wants. All of this
401 * information appears back on the
402 * parent's <code>Activity.onActivityResult()</code>, along with the integer
403 * identifier it originally supplied.</p>
404 *
405 * <p>If a child activity fails for any reason (such as crashing), the parent
406 * activity will receive a result with the code RESULT_CANCELED.</p>
407 *
408 * <pre class="prettyprint">
409 * public class MyActivity extends Activity {
410 * ...
411 *
412 * static final int PICK_CONTACT_REQUEST = 0;
413 *
414 * protected boolean onKeyDown(int keyCode, KeyEvent event) {
415 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
416 * // When the user center presses, let them pick a contact.
417 * startActivityForResult(
418 * new Intent(Intent.ACTION_PICK,
419 * new Uri("content://contacts")),
420 * PICK_CONTACT_REQUEST);
421 * return true;
422 * }
423 * return false;
424 * }
425 *
426 * protected void onActivityResult(int requestCode, int resultCode,
427 * Intent data) {
428 * if (requestCode == PICK_CONTACT_REQUEST) {
429 * if (resultCode == RESULT_OK) {
430 * // A contact was picked. Here we will just display it
431 * // to the user.
432 * startActivity(new Intent(Intent.ACTION_VIEW, data));
433 * }
434 * }
435 * }
436 * }
437 * </pre>
438 *
439 * <a name="SavingPersistentState"></a>
440 * <h3>Saving Persistent State</h3>
441 *
442 * <p>There are generally two kinds of persistent state than an activity
443 * will deal with: shared document-like data (typically stored in a SQLite
444 * database using a {@linkplain android.content.ContentProvider content provider})
445 * and internal state such as user preferences.</p>
446 *
447 * <p>For content provider data, we suggest that activities use a
448 * "edit in place" user model. That is, any edits a user makes are effectively
449 * made immediately without requiring an additional confirmation step.
450 * Supporting this model is generally a simple matter of following two rules:</p>
451 *
452 * <ul>
453 * <li> <p>When creating a new document, the backing database entry or file for
454 * it is created immediately. For example, if the user chooses to write
455 * a new e-mail, a new entry for that e-mail is created as soon as they
456 * start entering data, so that if they go to any other activity after
457 * that point this e-mail will now appear in the list of drafts.</p>
458 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
459 * commit to the backing content provider or file any changes the user
460 * has made. This ensures that those changes will be seen by any other
461 * activity that is about to run. You will probably want to commit
462 * your data even more aggressively at key times during your
463 * activity's lifecycle: for example before starting a new
464 * activity, before finishing your own activity, when the user
465 * switches between input fields, etc.</p>
466 * </ul>
467 *
468 * <p>This model is designed to prevent data loss when a user is navigating
469 * between activities, and allows the system to safely kill an activity (because
470 * system resources are needed somewhere else) at any time after it has been
471 * paused. Note this implies
472 * that the user pressing BACK from your activity does <em>not</em>
473 * mean "cancel" -- it means to leave the activity with its current contents
474 * saved away. Cancelling edits in an activity must be provided through
475 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
476 *
477 * <p>See the {@linkplain android.content.ContentProvider content package} for
478 * more information about content providers. These are a key aspect of how
479 * different activities invoke and propagate data between themselves.</p>
480 *
481 * <p>The Activity class also provides an API for managing internal persistent state
482 * associated with an activity. This can be used, for example, to remember
483 * the user's preferred initial display in a calendar (day view or week view)
484 * or the user's default home page in a web browser.</p>
485 *
486 * <p>Activity persistent state is managed
487 * with the method {@link #getPreferences},
488 * allowing you to retrieve and
489 * modify a set of name/value pairs associated with the activity. To use
490 * preferences that are shared across multiple application components
491 * (activities, receivers, services, providers), you can use the underlying
492 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
493 * to retrieve a preferences
494 * object stored under a specific name.
495 * (Note that it is not possible to share settings data across application
496 * packages -- for that you will need a content provider.)</p>
497 *
498 * <p>Here is an excerpt from a calendar activity that stores the user's
499 * preferred view mode in its persistent settings:</p>
500 *
501 * <pre class="prettyprint">
502 * public class CalendarActivity extends Activity {
503 * ...
504 *
505 * static final int DAY_VIEW_MODE = 0;
506 * static final int WEEK_VIEW_MODE = 1;
507 *
508 * private SharedPreferences mPrefs;
509 * private int mCurViewMode;
510 *
511 * protected void onCreate(Bundle savedInstanceState) {
512 * super.onCreate(savedInstanceState);
513 *
514 * SharedPreferences mPrefs = getSharedPreferences();
515 * mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
516 * }
517 *
518 * protected void onPause() {
519 * super.onPause();
520 *
521 * SharedPreferences.Editor ed = mPrefs.edit();
522 * ed.putInt("view_mode", mCurViewMode);
523 * ed.commit();
524 * }
525 * }
526 * </pre>
527 *
528 * <a name="Permissions"></a>
529 * <h3>Permissions</h3>
530 *
531 * <p>The ability to start a particular Activity can be enforced when it is
532 * declared in its
533 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
534 * tag. By doing so, other applications will need to declare a corresponding
535 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
536 * element in their own manifest to be able to start that activity.
537 *
538 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
539 * document for more information on permissions and security in general.
540 *
541 * <a name="ProcessLifecycle"></a>
542 * <h3>Process Lifecycle</h3>
543 *
544 * <p>The Android system attempts to keep application process around for as
545 * long as possible, but eventually will need to remove old processes when
546 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
547 * Lifecycle</a>, the decision about which process to remove is intimately
548 * tied to the state of the user's interaction with it. In general, there
549 * are four states a process can be in based on the activities running in it,
550 * listed here in order of importance. The system will kill less important
551 * processes (the last ones) before it resorts to killing more important
552 * processes (the first ones).
553 *
554 * <ol>
555 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
556 * that the user is currently interacting with) is considered the most important.
557 * Its process will only be killed as a last resort, if it uses more memory
558 * than is available on the device. Generally at this point the device has
559 * reached a memory paging state, so this is required in order to keep the user
560 * interface responsive.
561 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
562 * but not in the foreground, such as one sitting behind a foreground dialog)
563 * is considered extremely important and will not be killed unless that is
564 * required to keep the foreground activity running.
565 * <li> <p>A <b>background activity</b> (an activity that is not visible to
566 * the user and has been paused) is no longer critical, so the system may
567 * safely kill its process to reclaim memory for other foreground or
568 * visible processes. If its process needs to be killed, when the user navigates
569 * back to the activity (making it visible on the screen again), its
570 * {@link #onCreate} method will be called with the savedInstanceState it had previously
571 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
572 * state as the user last left it.
573 * <li> <p>An <b>empty process</b> is one hosting no activities or other
574 * application components (such as {@link Service} or
575 * {@link android.content.BroadcastReceiver} classes). These are killed very
576 * quickly by the system as memory becomes low. For this reason, any
577 * background operation you do outside of an activity must be executed in the
578 * context of an activity BroadcastReceiver or Service to ensure that the system
579 * knows it needs to keep your process around.
580 * </ol>
581 *
582 * <p>Sometimes an Activity may need to do a long-running operation that exists
583 * independently of the activity lifecycle itself. An example may be a camera
584 * application that allows you to upload a picture to a web site. The upload
585 * may take a long time, and the application should allow the user to leave
586 * the application will it is executing. To accomplish this, your Activity
587 * should start a {@link Service} in which the upload takes place. This allows
588 * the system to properly prioritize your process (considering it to be more
589 * important than other non-visible applications) for the duration of the
590 * upload, independent of whether the original activity is paused, stopped,
591 * or finished.
592 */
593public class Activity extends ContextThemeWrapper
594 implements LayoutInflater.Factory,
595 Window.Callback, KeyEvent.Callback,
596 OnCreateContextMenuListener, ComponentCallbacks {
597 private static final String TAG = "Activity";
598
599 /** Standard activity result: operation canceled. */
600 public static final int RESULT_CANCELED = 0;
601 /** Standard activity result: operation succeeded. */
602 public static final int RESULT_OK = -1;
603 /** Start of user-defined activity results. */
604 public static final int RESULT_FIRST_USER = 1;
605
606 private static long sInstanceCount = 0;
607
608 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
609 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
610 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
611 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800612 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800614 private static class ManagedDialog {
615 Dialog mDialog;
616 Bundle mArgs;
617 }
618 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619
620 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
621 private Instrumentation mInstrumentation;
622 private IBinder mToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700623 private int mIdent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 /*package*/ String mEmbeddedID;
625 private Application mApplication;
Christopher Tateb70f3df2009-04-07 16:07:59 -0700626 /*package*/ Intent mIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 private ComponentName mComponent;
628 /*package*/ ActivityInfo mActivityInfo;
629 /*package*/ ActivityThread mMainThread;
630 /*package*/ Object mLastNonConfigurationInstance;
631 /*package*/ HashMap<String,Object> mLastNonConfigurationChildInstances;
632 Activity mParent;
633 boolean mCalled;
634 private boolean mResumed;
635 private boolean mStopped;
636 boolean mFinished;
637 boolean mStartedActivity;
638 /*package*/ int mConfigChangeFlags;
639 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100640 private SearchManager mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641
642 private Window mWindow;
643
644 private WindowManager mWindowManager;
645 /*package*/ View mDecor = null;
646 /*package*/ boolean mWindowAdded = false;
647 /*package*/ boolean mVisibleFromServer = false;
648 /*package*/ boolean mVisibleFromClient = true;
649
650 private CharSequence mTitle;
651 private int mTitleColor = 0;
652
653 private static final class ManagedCursor {
654 ManagedCursor(Cursor cursor) {
655 mCursor = cursor;
656 mReleased = false;
657 mUpdated = false;
658 }
659
660 private final Cursor mCursor;
661 private boolean mReleased;
662 private boolean mUpdated;
663 }
664 private final ArrayList<ManagedCursor> mManagedCursors =
665 new ArrayList<ManagedCursor>();
666
667 // protected by synchronized (this)
668 int mResultCode = RESULT_CANCELED;
669 Intent mResultData = null;
670
671 private boolean mTitleReady = false;
672
673 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
674 private SpannableStringBuilder mDefaultKeySsb = null;
675
676 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
677
678 private Thread mUiThread;
679 private final Handler mHandler = new Handler();
680
681 public Activity() {
682 ++sInstanceCount;
683 }
684
685
686 @Override
687 protected void finalize() throws Throwable {
688 super.finalize();
689 --sInstanceCount;
690 }
691
692 public static long getInstanceCount() {
693 return sInstanceCount;
694 }
695
696 /** Return the intent that started this activity. */
697 public Intent getIntent() {
698 return mIntent;
699 }
700
701 /**
702 * Change the intent returned by {@link #getIntent}. This holds a
703 * reference to the given intent; it does not copy it. Often used in
704 * conjunction with {@link #onNewIntent}.
705 *
706 * @param newIntent The new Intent object to return from getIntent
707 *
708 * @see #getIntent
709 * @see #onNewIntent
710 */
711 public void setIntent(Intent newIntent) {
712 mIntent = newIntent;
713 }
714
715 /** Return the application that owns this activity. */
716 public final Application getApplication() {
717 return mApplication;
718 }
719
720 /** Is this activity embedded inside of another activity? */
721 public final boolean isChild() {
722 return mParent != null;
723 }
724
725 /** Return the parent activity if this view is an embedded child. */
726 public final Activity getParent() {
727 return mParent;
728 }
729
730 /** Retrieve the window manager for showing custom windows. */
731 public WindowManager getWindowManager() {
732 return mWindowManager;
733 }
734
735 /**
736 * Retrieve the current {@link android.view.Window} for the activity.
737 * This can be used to directly access parts of the Window API that
738 * are not available through Activity/Screen.
739 *
740 * @return Window The current window, or null if the activity is not
741 * visual.
742 */
743 public Window getWindow() {
744 return mWindow;
745 }
746
747 /**
748 * Calls {@link android.view.Window#getCurrentFocus} on the
749 * Window of this Activity to return the currently focused view.
750 *
751 * @return View The current View with focus or null.
752 *
753 * @see #getWindow
754 * @see android.view.Window#getCurrentFocus
755 */
756 public View getCurrentFocus() {
757 return mWindow != null ? mWindow.getCurrentFocus() : null;
758 }
759
760 @Override
761 public int getWallpaperDesiredMinimumWidth() {
762 int width = super.getWallpaperDesiredMinimumWidth();
763 return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
764 }
765
766 @Override
767 public int getWallpaperDesiredMinimumHeight() {
768 int height = super.getWallpaperDesiredMinimumHeight();
769 return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
770 }
771
772 /**
773 * Called when the activity is starting. This is where most initialization
774 * should go: calling {@link #setContentView(int)} to inflate the
775 * activity's UI, using {@link #findViewById} to programmatically interact
776 * with widgets in the UI, calling
777 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
778 * cursors for data being displayed, etc.
779 *
780 * <p>You can call {@link #finish} from within this function, in
781 * which case onDestroy() will be immediately called without any of the rest
782 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
783 * {@link #onPause}, etc) executing.
784 *
785 * <p><em>Derived classes must call through to the super class's
786 * implementation of this method. If they do not, an exception will be
787 * thrown.</em></p>
788 *
789 * @param savedInstanceState If the activity is being re-initialized after
790 * previously being shut down then this Bundle contains the data it most
791 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
792 *
793 * @see #onStart
794 * @see #onSaveInstanceState
795 * @see #onRestoreInstanceState
796 * @see #onPostCreate
797 */
798 protected void onCreate(Bundle savedInstanceState) {
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700799 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
800 com.android.internal.R.styleable.Window_windowNoDisplay, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 mCalled = true;
802 }
803
804 /**
805 * The hook for {@link ActivityThread} to restore the state of this activity.
806 *
807 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
808 * {@link #restoreManagedDialogs(android.os.Bundle)}.
809 *
810 * @param savedInstanceState contains the saved state
811 */
812 final void performRestoreInstanceState(Bundle savedInstanceState) {
813 onRestoreInstanceState(savedInstanceState);
814 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816
817 /**
818 * This method is called after {@link #onStart} when the activity is
819 * being re-initialized from a previously saved state, given here in
820 * <var>state</var>. Most implementations will simply use {@link #onCreate}
821 * to restore their state, but it is sometimes convenient to do it here
822 * after all of the initialization has been done or to allow subclasses to
823 * decide whether to use your default implementation. The default
824 * implementation of this method performs a restore of any view state that
825 * had previously been frozen by {@link #onSaveInstanceState}.
826 *
827 * <p>This method is called between {@link #onStart} and
828 * {@link #onPostCreate}.
829 *
830 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
831 *
832 * @see #onCreate
833 * @see #onPostCreate
834 * @see #onResume
835 * @see #onSaveInstanceState
836 */
837 protected void onRestoreInstanceState(Bundle savedInstanceState) {
838 if (mWindow != null) {
839 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
840 if (windowState != null) {
841 mWindow.restoreHierarchyState(windowState);
842 }
843 }
844 }
845
846 /**
847 * Restore the state of any saved managed dialogs.
848 *
849 * @param savedInstanceState The bundle to restore from.
850 */
851 private void restoreManagedDialogs(Bundle savedInstanceState) {
852 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
853 if (b == null) {
854 return;
855 }
856
857 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
858 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800859 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 for (int i = 0; i < numDialogs; i++) {
861 final Integer dialogId = ids[i];
862 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
863 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -0700864 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
865 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800866 final ManagedDialog md = new ManagedDialog();
867 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
868 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
869 if (md.mDialog != null) {
870 mManagedDialogs.put(dialogId, md);
871 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
872 md.mDialog.onRestoreInstanceState(dialogState);
873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
875 }
876 }
877
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800878 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
879 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -0700880 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800881 return null;
Romain Guy764d5332009-06-17 16:52:22 -0700882 }
Romain Guy6de4aed2009-07-08 10:54:45 -0700883 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -0700884 return dialog;
885 }
886
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800887 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 return SAVED_DIALOG_KEY_PREFIX + key;
889 }
890
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800891 private static String savedDialogArgsKeyFor(int key) {
892 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894
895 /**
896 * Called when activity start-up is complete (after {@link #onStart}
897 * and {@link #onRestoreInstanceState} have been called). Applications will
898 * generally not implement this method; it is intended for system
899 * classes to do final initialization after application code has run.
900 *
901 * <p><em>Derived classes must call through to the super class's
902 * implementation of this method. If they do not, an exception will be
903 * thrown.</em></p>
904 *
905 * @param savedInstanceState If the activity is being re-initialized after
906 * previously being shut down then this Bundle contains the data it most
907 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
908 * @see #onCreate
909 */
910 protected void onPostCreate(Bundle savedInstanceState) {
911 if (!isChild()) {
912 mTitleReady = true;
913 onTitleChanged(getTitle(), getTitleColor());
914 }
915 mCalled = true;
916 }
917
918 /**
919 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
920 * the activity had been stopped, but is now again being displayed to the
921 * user. It will be followed by {@link #onResume}.
922 *
923 * <p><em>Derived classes must call through to the super class's
924 * implementation of this method. If they do not, an exception will be
925 * thrown.</em></p>
926 *
927 * @see #onCreate
928 * @see #onStop
929 * @see #onResume
930 */
931 protected void onStart() {
932 mCalled = true;
933 }
934
935 /**
936 * Called after {@link #onStop} when the current activity is being
937 * re-displayed to the user (the user has navigated back to it). It will
938 * be followed by {@link #onStart} and then {@link #onResume}.
939 *
940 * <p>For activities that are using raw {@link Cursor} objects (instead of
941 * creating them through
942 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
943 * this is usually the place
944 * where the cursor should be requeried (because you had deactivated it in
945 * {@link #onStop}.
946 *
947 * <p><em>Derived classes must call through to the super class's
948 * implementation of this method. If they do not, an exception will be
949 * thrown.</em></p>
950 *
951 * @see #onStop
952 * @see #onStart
953 * @see #onResume
954 */
955 protected void onRestart() {
956 mCalled = true;
957 }
958
959 /**
960 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
961 * {@link #onPause}, for your activity to start interacting with the user.
962 * This is a good place to begin animations, open exclusive-access devices
963 * (such as the camera), etc.
964 *
965 * <p>Keep in mind that onResume is not the best indicator that your activity
966 * is visible to the user; a system window such as the keyguard may be in
967 * front. Use {@link #onWindowFocusChanged} to know for certain that your
968 * activity is visible to the user (for example, to resume a game).
969 *
970 * <p><em>Derived classes must call through to the super class's
971 * implementation of this method. If they do not, an exception will be
972 * thrown.</em></p>
973 *
974 * @see #onRestoreInstanceState
975 * @see #onRestart
976 * @see #onPostResume
977 * @see #onPause
978 */
979 protected void onResume() {
980 mCalled = true;
981 }
982
983 /**
984 * Called when activity resume is complete (after {@link #onResume} has
985 * been called). Applications will generally not implement this method;
986 * it is intended for system classes to do final setup after application
987 * resume code has run.
988 *
989 * <p><em>Derived classes must call through to the super class's
990 * implementation of this method. If they do not, an exception will be
991 * thrown.</em></p>
992 *
993 * @see #onResume
994 */
995 protected void onPostResume() {
996 final Window win = getWindow();
997 if (win != null) win.makeActive();
998 mCalled = true;
999 }
1000
1001 /**
1002 * This is called for activities that set launchMode to "singleTop" in
1003 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1004 * flag when calling {@link #startActivity}. In either case, when the
1005 * activity is re-launched while at the top of the activity stack instead
1006 * of a new instance of the activity being started, onNewIntent() will be
1007 * called on the existing instance with the Intent that was used to
1008 * re-launch it.
1009 *
1010 * <p>An activity will always be paused before receiving a new intent, so
1011 * you can count on {@link #onResume} being called after this method.
1012 *
1013 * <p>Note that {@link #getIntent} still returns the original Intent. You
1014 * can use {@link #setIntent} to update it to this new Intent.
1015 *
1016 * @param intent The new intent that was started for the activity.
1017 *
1018 * @see #getIntent
1019 * @see #setIntent
1020 * @see #onResume
1021 */
1022 protected void onNewIntent(Intent intent) {
1023 }
1024
1025 /**
1026 * The hook for {@link ActivityThread} to save the state of this activity.
1027 *
1028 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1029 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1030 *
1031 * @param outState The bundle to save the state to.
1032 */
1033 final void performSaveInstanceState(Bundle outState) {
1034 onSaveInstanceState(outState);
1035 saveManagedDialogs(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037
1038 /**
1039 * Called to retrieve per-instance state from an activity before being killed
1040 * so that the state can be restored in {@link #onCreate} or
1041 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1042 * will be passed to both).
1043 *
1044 * <p>This method is called before an activity may be killed so that when it
1045 * comes back some time in the future it can restore its state. For example,
1046 * if activity B is launched in front of activity A, and at some point activity
1047 * A is killed to reclaim resources, activity A will have a chance to save the
1048 * current state of its user interface via this method so that when the user
1049 * returns to activity A, the state of the user interface can be restored
1050 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1051 *
1052 * <p>Do not confuse this method with activity lifecycle callbacks such as
1053 * {@link #onPause}, which is always called when an activity is being placed
1054 * in the background or on its way to destruction, or {@link #onStop} which
1055 * is called before destruction. One example of when {@link #onPause} and
1056 * {@link #onStop} is called and not this method is when a user navigates back
1057 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1058 * on B because that particular instance will never be restored, so the
1059 * system avoids calling it. An example when {@link #onPause} is called and
1060 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1061 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1062 * killed during the lifetime of B since the state of the user interface of
1063 * A will stay intact.
1064 *
1065 * <p>The default implementation takes care of most of the UI per-instance
1066 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1067 * view in the hierarchy that has an id, and by saving the id of the currently
1068 * focused view (all of which is restored by the default implementation of
1069 * {@link #onRestoreInstanceState}). If you override this method to save additional
1070 * information not captured by each individual view, you will likely want to
1071 * call through to the default implementation, otherwise be prepared to save
1072 * all of the state of each view yourself.
1073 *
1074 * <p>If called, this method will occur before {@link #onStop}. There are
1075 * no guarantees about whether it will occur before or after {@link #onPause}.
1076 *
1077 * @param outState Bundle in which to place your saved state.
1078 *
1079 * @see #onCreate
1080 * @see #onRestoreInstanceState
1081 * @see #onPause
1082 */
1083 protected void onSaveInstanceState(Bundle outState) {
1084 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1085 }
1086
1087 /**
1088 * Save the state of any managed dialogs.
1089 *
1090 * @param outState place to store the saved state.
1091 */
1092 private void saveManagedDialogs(Bundle outState) {
1093 if (mManagedDialogs == null) {
1094 return;
1095 }
1096
1097 final int numDialogs = mManagedDialogs.size();
1098 if (numDialogs == 0) {
1099 return;
1100 }
1101
1102 Bundle dialogState = new Bundle();
1103
1104 int[] ids = new int[mManagedDialogs.size()];
1105
1106 // save each dialog's bundle, gather the ids
1107 for (int i = 0; i < numDialogs; i++) {
1108 final int key = mManagedDialogs.keyAt(i);
1109 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001110 final ManagedDialog md = mManagedDialogs.valueAt(i);
1111 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1112 if (md.mArgs != null) {
1113 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
1117 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1118 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1119 }
1120
1121
1122 /**
1123 * Called as part of the activity lifecycle when an activity is going into
1124 * the background, but has not (yet) been killed. The counterpart to
1125 * {@link #onResume}.
1126 *
1127 * <p>When activity B is launched in front of activity A, this callback will
1128 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1129 * so be sure to not do anything lengthy here.
1130 *
1131 * <p>This callback is mostly used for saving any persistent state the
1132 * activity is editing, to present a "edit in place" model to the user and
1133 * making sure nothing is lost if there are not enough resources to start
1134 * the new activity without first killing this one. This is also a good
1135 * place to do things like stop animations and other things that consume a
1136 * noticeable mount of CPU in order to make the switch to the next activity
1137 * as fast as possible, or to close resources that are exclusive access
1138 * such as the camera.
1139 *
1140 * <p>In situations where the system needs more memory it may kill paused
1141 * processes to reclaim resources. Because of this, you should be sure
1142 * that all of your state is saved by the time you return from
1143 * this function. In general {@link #onSaveInstanceState} is used to save
1144 * per-instance state in the activity and this method is used to store
1145 * global persistent data (in content providers, files, etc.)
1146 *
1147 * <p>After receiving this call you will usually receive a following call
1148 * to {@link #onStop} (after the next activity has been resumed and
1149 * displayed), however in some cases there will be a direct call back to
1150 * {@link #onResume} without going through the stopped state.
1151 *
1152 * <p><em>Derived classes must call through to the super class's
1153 * implementation of this method. If they do not, an exception will be
1154 * thrown.</em></p>
1155 *
1156 * @see #onResume
1157 * @see #onSaveInstanceState
1158 * @see #onStop
1159 */
1160 protected void onPause() {
1161 mCalled = true;
1162 }
1163
1164 /**
1165 * Called as part of the activity lifecycle when an activity is about to go
1166 * into the background as the result of user choice. For example, when the
1167 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1168 * when an incoming phone call causes the in-call Activity to be automatically
1169 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1170 * the activity being interrupted. In cases when it is invoked, this method
1171 * is called right before the activity's {@link #onPause} callback.
1172 *
1173 * <p>This callback and {@link #onUserInteraction} are intended to help
1174 * activities manage status bar notifications intelligently; specifically,
1175 * for helping activities determine the proper time to cancel a notfication.
1176 *
1177 * @see #onUserInteraction()
1178 */
1179 protected void onUserLeaveHint() {
1180 }
1181
1182 /**
1183 * Generate a new thumbnail for this activity. This method is called before
1184 * pausing the activity, and should draw into <var>outBitmap</var> the
1185 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1186 * can use the given <var>canvas</var>, which is configured to draw into the
1187 * bitmap, for rendering if desired.
1188 *
1189 * <p>The default implementation renders the Screen's current view
1190 * hierarchy into the canvas to generate a thumbnail.
1191 *
1192 * <p>If you return false, the bitmap will be filled with a default
1193 * thumbnail.
1194 *
1195 * @param outBitmap The bitmap to contain the thumbnail.
1196 * @param canvas Can be used to render into the bitmap.
1197 *
1198 * @return Return true if you have drawn into the bitmap; otherwise after
1199 * you return it will be filled with a default thumbnail.
1200 *
1201 * @see #onCreateDescription
1202 * @see #onSaveInstanceState
1203 * @see #onPause
1204 */
1205 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1206 final View view = mDecor;
1207 if (view == null) {
1208 return false;
1209 }
1210
1211 final int vw = view.getWidth();
1212 final int vh = view.getHeight();
1213 final int dw = outBitmap.getWidth();
1214 final int dh = outBitmap.getHeight();
1215
1216 canvas.save();
1217 canvas.scale(((float)dw)/vw, ((float)dh)/vh);
1218 view.draw(canvas);
1219 canvas.restore();
1220
1221 return true;
1222 }
1223
1224 /**
1225 * Generate a new description for this activity. This method is called
1226 * before pausing the activity and can, if desired, return some textual
1227 * description of its current state to be displayed to the user.
1228 *
1229 * <p>The default implementation returns null, which will cause you to
1230 * inherit the description from the previous activity. If all activities
1231 * return null, generally the label of the top activity will be used as the
1232 * description.
1233 *
1234 * @return A description of what the user is doing. It should be short and
1235 * sweet (only a few words).
1236 *
1237 * @see #onCreateThumbnail
1238 * @see #onSaveInstanceState
1239 * @see #onPause
1240 */
1241 public CharSequence onCreateDescription() {
1242 return null;
1243 }
1244
1245 /**
1246 * Called when you are no longer visible to the user. You will next
1247 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1248 * depending on later user activity.
1249 *
1250 * <p>Note that this method may never be called, in low memory situations
1251 * where the system does not have enough memory to keep your activity's
1252 * process running after its {@link #onPause} method is called.
1253 *
1254 * <p><em>Derived classes must call through to the super class's
1255 * implementation of this method. If they do not, an exception will be
1256 * thrown.</em></p>
1257 *
1258 * @see #onRestart
1259 * @see #onResume
1260 * @see #onSaveInstanceState
1261 * @see #onDestroy
1262 */
1263 protected void onStop() {
1264 mCalled = true;
1265 }
1266
1267 /**
1268 * Perform any final cleanup before an activity is destroyed. This can
1269 * happen either because the activity is finishing (someone called
1270 * {@link #finish} on it, or because the system is temporarily destroying
1271 * this instance of the activity to save space. You can distinguish
1272 * between these two scenarios with the {@link #isFinishing} method.
1273 *
1274 * <p><em>Note: do not count on this method being called as a place for
1275 * saving data! For example, if an activity is editing data in a content
1276 * provider, those edits should be committed in either {@link #onPause} or
1277 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1278 * free resources like threads that are associated with an activity, so
1279 * that a destroyed activity does not leave such things around while the
1280 * rest of its application is still running. There are situations where
1281 * the system will simply kill the activity's hosting process without
1282 * calling this method (or any others) in it, so it should not be used to
1283 * do things that are intended to remain around after the process goes
1284 * away.
1285 *
1286 * <p><em>Derived classes must call through to the super class's
1287 * implementation of this method. If they do not, an exception will be
1288 * thrown.</em></p>
1289 *
1290 * @see #onPause
1291 * @see #onStop
1292 * @see #finish
1293 * @see #isFinishing
1294 */
1295 protected void onDestroy() {
1296 mCalled = true;
1297
1298 // dismiss any dialogs we are managing.
1299 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 final int numDialogs = mManagedDialogs.size();
1301 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001302 final ManagedDialog md = mManagedDialogs.valueAt(i);
1303 if (md.mDialog.isShowing()) {
1304 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001307 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
1310 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001311 synchronized (mManagedCursors) {
1312 int numCursors = mManagedCursors.size();
1313 for (int i = 0; i < numCursors; i++) {
1314 ManagedCursor c = mManagedCursors.get(i);
1315 if (c != null) {
1316 c.mCursor.close();
1317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08001319 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321 }
1322
1323 /**
1324 * Called by the system when the device configuration changes while your
1325 * activity is running. Note that this will <em>only</em> be called if
1326 * you have selected configurations you would like to handle with the
1327 * {@link android.R.attr#configChanges} attribute in your manifest. If
1328 * any configuration change occurs that is not selected to be reported
1329 * by that attribute, then instead of reporting it the system will stop
1330 * and restart the activity (to have it launched with the new
1331 * configuration).
1332 *
1333 * <p>At the time that this function has been called, your Resources
1334 * object will have been updated to return resource values matching the
1335 * new configuration.
1336 *
1337 * @param newConfig The new device configuration.
1338 */
1339 public void onConfigurationChanged(Configuration newConfig) {
1340 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 if (mWindow != null) {
1343 // Pass the configuration changed event to the window
1344 mWindow.onConfigurationChanged(newConfig);
1345 }
1346 }
1347
1348 /**
1349 * If this activity is being destroyed because it can not handle a
1350 * configuration parameter being changed (and thus its
1351 * {@link #onConfigurationChanged(Configuration)} method is
1352 * <em>not</em> being called), then you can use this method to discover
1353 * the set of changes that have occurred while in the process of being
1354 * destroyed. Note that there is no guarantee that these will be
1355 * accurate (other changes could have happened at any time), so you should
1356 * only use this as an optimization hint.
1357 *
1358 * @return Returns a bit field of the configuration parameters that are
1359 * changing, as defined by the {@link android.content.res.Configuration}
1360 * class.
1361 */
1362 public int getChangingConfigurations() {
1363 return mConfigChangeFlags;
1364 }
1365
1366 /**
1367 * Retrieve the non-configuration instance data that was previously
1368 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1369 * be available from the initial {@link #onCreate} and
1370 * {@link #onStart} calls to the new instance, allowing you to extract
1371 * any useful dynamic state from the previous instance.
1372 *
1373 * <p>Note that the data you retrieve here should <em>only</em> be used
1374 * as an optimization for handling configuration changes. You should always
1375 * be able to handle getting a null pointer back, and an activity must
1376 * still be able to restore itself to its previous state (through the
1377 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1378 * function returns null.
1379 *
1380 * @return Returns the object previously returned by
1381 * {@link #onRetainNonConfigurationInstance()}.
1382 */
1383 public Object getLastNonConfigurationInstance() {
1384 return mLastNonConfigurationInstance;
1385 }
1386
1387 /**
1388 * Called by the system, as part of destroying an
1389 * activity due to a configuration change, when it is known that a new
1390 * instance will immediately be created for the new configuration. You
1391 * can return any object you like here, including the activity instance
1392 * itself, which can later be retrieved by calling
1393 * {@link #getLastNonConfigurationInstance()} in the new activity
1394 * instance.
1395 *
1396 * <p>This function is called purely as an optimization, and you must
1397 * not rely on it being called. When it is called, a number of guarantees
1398 * will be made to help optimize configuration switching:
1399 * <ul>
1400 * <li> The function will be called between {@link #onStop} and
1401 * {@link #onDestroy}.
1402 * <li> A new instance of the activity will <em>always</em> be immediately
1403 * created after this one's {@link #onDestroy()} is called.
1404 * <li> The object you return here will <em>always</em> be available from
1405 * the {@link #getLastNonConfigurationInstance()} method of the following
1406 * activity instance as described there.
1407 * </ul>
1408 *
1409 * <p>These guarantees are designed so that an activity can use this API
1410 * to propagate extensive state from the old to new activity instance, from
1411 * loaded bitmaps, to network connections, to evenly actively running
1412 * threads. Note that you should <em>not</em> propagate any data that
1413 * may change based on the configuration, including any data loaded from
1414 * resources such as strings, layouts, or drawables.
1415 *
1416 * @return Return any Object holding the desired state to propagate to the
1417 * next activity instance.
1418 */
1419 public Object onRetainNonConfigurationInstance() {
1420 return null;
1421 }
1422
1423 /**
1424 * Retrieve the non-configuration instance data that was previously
1425 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1426 * be available from the initial {@link #onCreate} and
1427 * {@link #onStart} calls to the new instance, allowing you to extract
1428 * any useful dynamic state from the previous instance.
1429 *
1430 * <p>Note that the data you retrieve here should <em>only</em> be used
1431 * as an optimization for handling configuration changes. You should always
1432 * be able to handle getting a null pointer back, and an activity must
1433 * still be able to restore itself to its previous state (through the
1434 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1435 * function returns null.
1436 *
1437 * @return Returns the object previously returned by
1438 * {@link #onRetainNonConfigurationChildInstances()}
1439 */
1440 HashMap<String,Object> getLastNonConfigurationChildInstances() {
1441 return mLastNonConfigurationChildInstances;
1442 }
1443
1444 /**
1445 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1446 * it should return either a mapping from child activity id strings to arbitrary objects,
1447 * or null. This method is intended to be used by Activity framework subclasses that control a
1448 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1449 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1450 */
1451 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1452 return null;
1453 }
1454
1455 public void onLowMemory() {
1456 mCalled = true;
1457 }
1458
1459 /**
1460 * Wrapper around
1461 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1462 * that gives the resulting {@link Cursor} to call
1463 * {@link #startManagingCursor} so that the activity will manage its
1464 * lifecycle for you.
1465 *
1466 * @param uri The URI of the content provider to query.
1467 * @param projection List of columns to return.
1468 * @param selection SQL WHERE clause.
1469 * @param sortOrder SQL ORDER BY clause.
1470 *
1471 * @return The Cursor that was returned by query().
1472 *
1473 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1474 * @see #startManagingCursor
1475 * @hide
1476 */
1477 public final Cursor managedQuery(Uri uri,
1478 String[] projection,
1479 String selection,
1480 String sortOrder)
1481 {
1482 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1483 if (c != null) {
1484 startManagingCursor(c);
1485 }
1486 return c;
1487 }
1488
1489 /**
1490 * Wrapper around
1491 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1492 * that gives the resulting {@link Cursor} to call
1493 * {@link #startManagingCursor} so that the activity will manage its
1494 * lifecycle for you.
1495 *
1496 * @param uri The URI of the content provider to query.
1497 * @param projection List of columns to return.
1498 * @param selection SQL WHERE clause.
1499 * @param selectionArgs The arguments to selection, if any ?s are pesent
1500 * @param sortOrder SQL ORDER BY clause.
1501 *
1502 * @return The Cursor that was returned by query().
1503 *
1504 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1505 * @see #startManagingCursor
1506 */
1507 public final Cursor managedQuery(Uri uri,
1508 String[] projection,
1509 String selection,
1510 String[] selectionArgs,
1511 String sortOrder)
1512 {
1513 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1514 if (c != null) {
1515 startManagingCursor(c);
1516 }
1517 return c;
1518 }
1519
1520 /**
1521 * Wrapper around {@link Cursor#commitUpdates()} that takes care of noting
1522 * that the Cursor needs to be requeried. You can call this method in
1523 * {@link #onPause} or {@link #onStop} to have the system call
1524 * {@link Cursor#requery} for you if the activity is later resumed. This
1525 * allows you to avoid determing when to do the requery yourself (which is
1526 * required for the Cursor to see any data changes that were committed with
1527 * it).
1528 *
1529 * @param c The Cursor whose changes are to be committed.
1530 *
1531 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1532 * @see #startManagingCursor
1533 * @see Cursor#commitUpdates()
1534 * @see Cursor#requery
1535 * @hide
1536 */
1537 @Deprecated
1538 public void managedCommitUpdates(Cursor c) {
1539 synchronized (mManagedCursors) {
1540 final int N = mManagedCursors.size();
1541 for (int i=0; i<N; i++) {
1542 ManagedCursor mc = mManagedCursors.get(i);
1543 if (mc.mCursor == c) {
1544 c.commitUpdates();
1545 mc.mUpdated = true;
1546 return;
1547 }
1548 }
1549 throw new RuntimeException(
1550 "Cursor " + c + " is not currently managed");
1551 }
1552 }
1553
1554 /**
1555 * This method allows the activity to take care of managing the given
1556 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1557 * That is, when the activity is stopped it will automatically call
1558 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1559 * it will call {@link Cursor#requery} for you. When the activity is
1560 * destroyed, all managed Cursors will be closed automatically.
1561 *
1562 * @param c The Cursor to be managed.
1563 *
1564 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1565 * @see #stopManagingCursor
1566 */
1567 public void startManagingCursor(Cursor c) {
1568 synchronized (mManagedCursors) {
1569 mManagedCursors.add(new ManagedCursor(c));
1570 }
1571 }
1572
1573 /**
1574 * Given a Cursor that was previously given to
1575 * {@link #startManagingCursor}, stop the activity's management of that
1576 * cursor.
1577 *
1578 * @param c The Cursor that was being managed.
1579 *
1580 * @see #startManagingCursor
1581 */
1582 public void stopManagingCursor(Cursor c) {
1583 synchronized (mManagedCursors) {
1584 final int N = mManagedCursors.size();
1585 for (int i=0; i<N; i++) {
1586 ManagedCursor mc = mManagedCursors.get(i);
1587 if (mc.mCursor == c) {
1588 mManagedCursors.remove(i);
1589 break;
1590 }
1591 }
1592 }
1593 }
1594
1595 /**
1596 * Control whether this activity is required to be persistent. By default
1597 * activities are not persistent; setting this to true will prevent the
1598 * system from stopping this activity or its process when running low on
1599 * resources.
1600 *
1601 * <p><em>You should avoid using this method</em>, it has severe negative
1602 * consequences on how well the system can manage its resources. A better
1603 * approach is to implement an application service that you control with
1604 * {@link Context#startService} and {@link Context#stopService}.
1605 *
1606 * @param isPersistent Control whether the current activity must be
1607 * persistent, true if so, false for the normal
1608 * behavior.
1609 */
1610 public void setPersistent(boolean isPersistent) {
1611 if (mParent == null) {
1612 try {
1613 ActivityManagerNative.getDefault()
1614 .setPersistent(mToken, isPersistent);
1615 } catch (RemoteException e) {
1616 // Empty
1617 }
1618 } else {
1619 throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1620 }
1621 }
1622
1623 /**
1624 * Finds a view that was identified by the id attribute from the XML that
1625 * was processed in {@link #onCreate}.
1626 *
1627 * @return The view if found or null otherwise.
1628 */
1629 public View findViewById(int id) {
1630 return getWindow().findViewById(id);
1631 }
1632
1633 /**
1634 * Set the activity content from a layout resource. The resource will be
1635 * inflated, adding all top-level views to the activity.
1636 *
1637 * @param layoutResID Resource ID to be inflated.
1638 */
1639 public void setContentView(int layoutResID) {
1640 getWindow().setContentView(layoutResID);
1641 }
1642
1643 /**
1644 * Set the activity content to an explicit view. This view is placed
1645 * directly into the activity's view hierarchy. It can itself be a complex
1646 * view hierarhcy.
1647 *
1648 * @param view The desired content to display.
1649 */
1650 public void setContentView(View view) {
1651 getWindow().setContentView(view);
1652 }
1653
1654 /**
1655 * Set the activity content to an explicit view. This view is placed
1656 * directly into the activity's view hierarchy. It can itself be a complex
1657 * view hierarhcy.
1658 *
1659 * @param view The desired content to display.
1660 * @param params Layout parameters for the view.
1661 */
1662 public void setContentView(View view, ViewGroup.LayoutParams params) {
1663 getWindow().setContentView(view, params);
1664 }
1665
1666 /**
1667 * Add an additional content view to the activity. Added after any existing
1668 * ones in the activity -- existing views are NOT removed.
1669 *
1670 * @param view The desired content to display.
1671 * @param params Layout parameters for the view.
1672 */
1673 public void addContentView(View view, ViewGroup.LayoutParams params) {
1674 getWindow().addContentView(view, params);
1675 }
1676
1677 /**
1678 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1679 * keys.
1680 *
1681 * @see #setDefaultKeyMode
1682 */
1683 static public final int DEFAULT_KEYS_DISABLE = 0;
1684 /**
1685 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1686 * key handling.
1687 *
1688 * @see #setDefaultKeyMode
1689 */
1690 static public final int DEFAULT_KEYS_DIALER = 1;
1691 /**
1692 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1693 * default key handling.
1694 *
1695 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1696 *
1697 * @see #setDefaultKeyMode
1698 */
1699 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1700 /**
1701 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1702 * will start an application-defined search. (If the application or activity does not
1703 * actually define a search, the the keys will be ignored.)
1704 *
1705 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1706 *
1707 * @see #setDefaultKeyMode
1708 */
1709 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1710
1711 /**
1712 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1713 * will start a global search (typically web search, but some platforms may define alternate
1714 * methods for global search)
1715 *
1716 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1717 *
1718 * @see #setDefaultKeyMode
1719 */
1720 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1721
1722 /**
1723 * Select the default key handling for this activity. This controls what
1724 * will happen to key events that are not otherwise handled. The default
1725 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1726 * floor. Other modes allow you to launch the dialer
1727 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1728 * menu without requiring the menu key be held down
1729 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1730 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1731 *
1732 * <p>Note that the mode selected here does not impact the default
1733 * handling of system keys, such as the "back" and "menu" keys, and your
1734 * activity and its views always get a first chance to receive and handle
1735 * all application keys.
1736 *
1737 * @param mode The desired default key mode constant.
1738 *
1739 * @see #DEFAULT_KEYS_DISABLE
1740 * @see #DEFAULT_KEYS_DIALER
1741 * @see #DEFAULT_KEYS_SHORTCUT
1742 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1743 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1744 * @see #onKeyDown
1745 */
1746 public final void setDefaultKeyMode(int mode) {
1747 mDefaultKeyMode = mode;
1748
1749 // Some modes use a SpannableStringBuilder to track & dispatch input events
1750 // This list must remain in sync with the switch in onKeyDown()
1751 switch (mode) {
1752 case DEFAULT_KEYS_DISABLE:
1753 case DEFAULT_KEYS_SHORTCUT:
1754 mDefaultKeySsb = null; // not used in these modes
1755 break;
1756 case DEFAULT_KEYS_DIALER:
1757 case DEFAULT_KEYS_SEARCH_LOCAL:
1758 case DEFAULT_KEYS_SEARCH_GLOBAL:
1759 mDefaultKeySsb = new SpannableStringBuilder();
1760 Selection.setSelection(mDefaultKeySsb,0);
1761 break;
1762 default:
1763 throw new IllegalArgumentException();
1764 }
1765 }
1766
1767 /**
1768 * Called when a key was pressed down and not handled by any of the views
1769 * inside of the activity. So, for example, key presses while the cursor
1770 * is inside a TextView will not trigger the event (unless it is a navigation
1771 * to another object) because TextView handles its own key presses.
1772 *
1773 * <p>If the focused view didn't want this event, this method is called.
1774 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001775 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1776 * by calling {@link #onBackPressed()}, though the behavior varies based
1777 * on the application compatibility mode: for
1778 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1779 * it will set up the dispatch to call {@link #onKeyUp} where the action
1780 * will be performed; for earlier applications, it will perform the
1781 * action immediately in on-down, as those versions of the platform
1782 * behaved.
1783 *
1784 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001785 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 *
1787 * @return Return <code>true</code> to prevent this event from being propagated
1788 * further, or <code>false</code> to indicate that you have not handled
1789 * this event and it should continue to be propagated.
1790 * @see #onKeyUp
1791 * @see android.view.KeyEvent
1792 */
1793 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001794 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001795 if (getApplicationInfo().targetSdkVersion
1796 >= Build.VERSION_CODES.ECLAIR) {
1797 event.startTracking();
1798 } else {
1799 onBackPressed();
1800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 return true;
1802 }
1803
1804 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1805 return false;
1806 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001807 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1808 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1809 return true;
1810 }
1811 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 } else {
1813 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1814 boolean clearSpannable = false;
1815 boolean handled;
1816 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1817 clearSpannable = true;
1818 handled = false;
1819 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001820 handled = TextKeyListener.getInstance().onKeyDown(
1821 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (handled && mDefaultKeySsb.length() > 0) {
1823 // something useable has been typed - dispatch it now.
1824
1825 final String str = mDefaultKeySsb.toString();
1826 clearSpannable = true;
1827
1828 switch (mDefaultKeyMode) {
1829 case DEFAULT_KEYS_DIALER:
1830 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1831 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1832 startActivity(intent);
1833 break;
1834 case DEFAULT_KEYS_SEARCH_LOCAL:
1835 startSearch(str, false, null, false);
1836 break;
1837 case DEFAULT_KEYS_SEARCH_GLOBAL:
1838 startSearch(str, false, null, true);
1839 break;
1840 }
1841 }
1842 }
1843 if (clearSpannable) {
1844 mDefaultKeySsb.clear();
1845 mDefaultKeySsb.clearSpans();
1846 Selection.setSelection(mDefaultKeySsb,0);
1847 }
1848 return handled;
1849 }
1850 }
1851
1852 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001853 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
1854 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
1855 * the event).
1856 */
1857 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1858 return false;
1859 }
1860
1861 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 * Called when a key was released and not handled by any of the views
1863 * inside of the activity. So, for example, key presses while the cursor
1864 * is inside a TextView will not trigger the event (unless it is a navigation
1865 * to another object) because TextView handles its own key presses.
1866 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001867 * <p>The default implementation handles KEYCODE_BACK to stop the activity
1868 * and go back.
1869 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 * @return Return <code>true</code> to prevent this event from being propagated
1871 * further, or <code>false</code> to indicate that you have not handled
1872 * this event and it should continue to be propagated.
1873 * @see #onKeyDown
1874 * @see KeyEvent
1875 */
1876 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001877 if (getApplicationInfo().targetSdkVersion
1878 >= Build.VERSION_CODES.ECLAIR) {
1879 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
1880 && !event.isCanceled()) {
1881 onBackPressed();
1882 return true;
1883 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 return false;
1886 }
1887
1888 /**
1889 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
1890 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
1891 * the event).
1892 */
1893 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
1894 return false;
1895 }
1896
1897 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001898 * Called when the activity has detected the user's press of the back
1899 * key. The default implementation simply finishes the current activity,
1900 * but you can override this to do whatever you want.
1901 */
1902 public void onBackPressed() {
1903 finish();
1904 }
1905
1906 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 * Called when a touch screen event was not handled by any of the views
1908 * under it. This is most useful to process touch events that happen
1909 * outside of your window bounds, where there is no view to receive it.
1910 *
1911 * @param event The touch screen event being processed.
1912 *
1913 * @return Return true if you have consumed the event, false if you haven't.
1914 * The default implementation always returns false.
1915 */
1916 public boolean onTouchEvent(MotionEvent event) {
1917 return false;
1918 }
1919
1920 /**
1921 * Called when the trackball was moved and not handled by any of the
1922 * views inside of the activity. So, for example, if the trackball moves
1923 * while focus is on a button, you will receive a call here because
1924 * buttons do not normally do anything with trackball events. The call
1925 * here happens <em>before</em> trackball movements are converted to
1926 * DPAD key events, which then get sent back to the view hierarchy, and
1927 * will be processed at the point for things like focus navigation.
1928 *
1929 * @param event The trackball event being processed.
1930 *
1931 * @return Return true if you have consumed the event, false if you haven't.
1932 * The default implementation always returns false.
1933 */
1934 public boolean onTrackballEvent(MotionEvent event) {
1935 return false;
1936 }
1937
1938 /**
1939 * Called whenever a key, touch, or trackball event is dispatched to the
1940 * activity. Implement this method if you wish to know that the user has
1941 * interacted with the device in some way while your activity is running.
1942 * This callback and {@link #onUserLeaveHint} are intended to help
1943 * activities manage status bar notifications intelligently; specifically,
1944 * for helping activities determine the proper time to cancel a notfication.
1945 *
1946 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
1947 * be accompanied by calls to {@link #onUserInteraction}. This
1948 * ensures that your activity will be told of relevant user activity such
1949 * as pulling down the notification pane and touching an item there.
1950 *
1951 * <p>Note that this callback will be invoked for the touch down action
1952 * that begins a touch gesture, but may not be invoked for the touch-moved
1953 * and touch-up actions that follow.
1954 *
1955 * @see #onUserLeaveHint()
1956 */
1957 public void onUserInteraction() {
1958 }
1959
1960 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
1961 // Update window manager if: we have a view, that view is
1962 // attached to its parent (which will be a RootView), and
1963 // this activity is not embedded.
1964 if (mParent == null) {
1965 View decor = mDecor;
1966 if (decor != null && decor.getParent() != null) {
1967 getWindowManager().updateViewLayout(decor, params);
1968 }
1969 }
1970 }
1971
1972 public void onContentChanged() {
1973 }
1974
1975 /**
1976 * Called when the current {@link Window} of the activity gains or loses
1977 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001978 * to the user. The default implementation clears the key tracking
1979 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001981 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 * is managed independently of activity lifecycles. As such, while focus
1983 * changes will generally have some relation to lifecycle changes (an
1984 * activity that is stopped will not generally get window focus), you
1985 * should not rely on any particular order between the callbacks here and
1986 * those in the other lifecycle methods such as {@link #onResume}.
1987 *
1988 * <p>As a general rule, however, a resumed activity will have window
1989 * focus... unless it has displayed other dialogs or popups that take
1990 * input focus, in which case the activity itself will not have focus
1991 * when the other windows have it. Likewise, the system may display
1992 * system-level windows (such as the status bar notification panel or
1993 * a system alert) which will temporarily take window input focus without
1994 * pausing the foreground activity.
1995 *
1996 * @param hasFocus Whether the window of this activity has focus.
1997 *
1998 * @see #hasWindowFocus()
1999 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002000 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 */
2002 public void onWindowFocusChanged(boolean hasFocus) {
2003 }
2004
2005 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002006 * Called when the main window associated with the activity has been
2007 * attached to the window manager.
2008 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2009 * for more information.
2010 * @see View#onAttachedToWindow
2011 */
2012 public void onAttachedToWindow() {
2013 }
2014
2015 /**
2016 * Called when the main window associated with the activity has been
2017 * detached from the window manager.
2018 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2019 * for more information.
2020 * @see View#onDetachedFromWindow
2021 */
2022 public void onDetachedFromWindow() {
2023 }
2024
2025 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 * Returns true if this activity's <em>main</em> window currently has window focus.
2027 * Note that this is not the same as the view itself having focus.
2028 *
2029 * @return True if this activity's main window currently has window focus.
2030 *
2031 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2032 */
2033 public boolean hasWindowFocus() {
2034 Window w = getWindow();
2035 if (w != null) {
2036 View d = w.getDecorView();
2037 if (d != null) {
2038 return d.hasWindowFocus();
2039 }
2040 }
2041 return false;
2042 }
2043
2044 /**
2045 * Called to process key events. You can override this to intercept all
2046 * key events before they are dispatched to the window. Be sure to call
2047 * this implementation for key events that should be handled normally.
2048 *
2049 * @param event The key event.
2050 *
2051 * @return boolean Return true if this event was consumed.
2052 */
2053 public boolean dispatchKeyEvent(KeyEvent event) {
2054 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002055 Window win = getWindow();
2056 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 return true;
2058 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002059 View decor = mDecor;
2060 if (decor == null) decor = win.getDecorView();
2061 return event.dispatch(this, decor != null
2062 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064
2065 /**
2066 * Called to process touch screen events. You can override this to
2067 * intercept all touch screen events before they are dispatched to the
2068 * window. Be sure to call this implementation for touch screen events
2069 * that should be handled normally.
2070 *
2071 * @param ev The touch screen event.
2072 *
2073 * @return boolean Return true if this event was consumed.
2074 */
2075 public boolean dispatchTouchEvent(MotionEvent ev) {
2076 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2077 onUserInteraction();
2078 }
2079 if (getWindow().superDispatchTouchEvent(ev)) {
2080 return true;
2081 }
2082 return onTouchEvent(ev);
2083 }
2084
2085 /**
2086 * Called to process trackball events. You can override this to
2087 * intercept all trackball events before they are dispatched to the
2088 * window. Be sure to call this implementation for trackball events
2089 * that should be handled normally.
2090 *
2091 * @param ev The trackball event.
2092 *
2093 * @return boolean Return true if this event was consumed.
2094 */
2095 public boolean dispatchTrackballEvent(MotionEvent ev) {
2096 onUserInteraction();
2097 if (getWindow().superDispatchTrackballEvent(ev)) {
2098 return true;
2099 }
2100 return onTrackballEvent(ev);
2101 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002102
2103 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2104 event.setClassName(getClass().getName());
2105 event.setPackageName(getPackageName());
2106
2107 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002108 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2109 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002110 event.setFullScreen(isFullScreen);
2111
2112 CharSequence title = getTitle();
2113 if (!TextUtils.isEmpty(title)) {
2114 event.getText().add(title);
2115 }
2116
2117 return true;
2118 }
2119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 /**
2121 * Default implementation of
2122 * {@link android.view.Window.Callback#onCreatePanelView}
2123 * for activities. This
2124 * simply returns null so that all panel sub-windows will have the default
2125 * menu behavior.
2126 */
2127 public View onCreatePanelView(int featureId) {
2128 return null;
2129 }
2130
2131 /**
2132 * Default implementation of
2133 * {@link android.view.Window.Callback#onCreatePanelMenu}
2134 * for activities. This calls through to the new
2135 * {@link #onCreateOptionsMenu} method for the
2136 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2137 * so that subclasses of Activity don't need to deal with feature codes.
2138 */
2139 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2140 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2141 return onCreateOptionsMenu(menu);
2142 }
2143 return false;
2144 }
2145
2146 /**
2147 * Default implementation of
2148 * {@link android.view.Window.Callback#onPreparePanel}
2149 * for activities. This
2150 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2151 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2152 * panel, so that subclasses of
2153 * Activity don't need to deal with feature codes.
2154 */
2155 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2156 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2157 boolean goforit = onPrepareOptionsMenu(menu);
2158 return goforit && menu.hasVisibleItems();
2159 }
2160 return true;
2161 }
2162
2163 /**
2164 * {@inheritDoc}
2165 *
2166 * @return The default implementation returns true.
2167 */
2168 public boolean onMenuOpened(int featureId, Menu menu) {
2169 return true;
2170 }
2171
2172 /**
2173 * Default implementation of
2174 * {@link android.view.Window.Callback#onMenuItemSelected}
2175 * for activities. This calls through to the new
2176 * {@link #onOptionsItemSelected} method for the
2177 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2178 * panel, so that subclasses of
2179 * Activity don't need to deal with feature codes.
2180 */
2181 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2182 switch (featureId) {
2183 case Window.FEATURE_OPTIONS_PANEL:
2184 // Put event logging here so it gets called even if subclass
2185 // doesn't call through to superclass's implmeentation of each
2186 // of these methods below
2187 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
2188 return onOptionsItemSelected(item);
2189
2190 case Window.FEATURE_CONTEXT_MENU:
2191 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
2192 return onContextItemSelected(item);
2193
2194 default:
2195 return false;
2196 }
2197 }
2198
2199 /**
2200 * Default implementation of
2201 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2202 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2203 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2204 * so that subclasses of Activity don't need to deal with feature codes.
2205 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2206 * {@link #onContextMenuClosed(Menu)} will be called.
2207 */
2208 public void onPanelClosed(int featureId, Menu menu) {
2209 switch (featureId) {
2210 case Window.FEATURE_OPTIONS_PANEL:
2211 onOptionsMenuClosed(menu);
2212 break;
2213
2214 case Window.FEATURE_CONTEXT_MENU:
2215 onContextMenuClosed(menu);
2216 break;
2217 }
2218 }
2219
2220 /**
2221 * Initialize the contents of the Activity's standard options menu. You
2222 * should place your menu items in to <var>menu</var>.
2223 *
2224 * <p>This is only called once, the first time the options menu is
2225 * displayed. To update the menu every time it is displayed, see
2226 * {@link #onPrepareOptionsMenu}.
2227 *
2228 * <p>The default implementation populates the menu with standard system
2229 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2230 * they will be correctly ordered with application-defined menu items.
2231 * Deriving classes should always call through to the base implementation.
2232 *
2233 * <p>You can safely hold on to <var>menu</var> (and any items created
2234 * from it), making modifications to it as desired, until the next
2235 * time onCreateOptionsMenu() is called.
2236 *
2237 * <p>When you add items to the menu, you can implement the Activity's
2238 * {@link #onOptionsItemSelected} method to handle them there.
2239 *
2240 * @param menu The options menu in which you place your items.
2241 *
2242 * @return You must return true for the menu to be displayed;
2243 * if you return false it will not be shown.
2244 *
2245 * @see #onPrepareOptionsMenu
2246 * @see #onOptionsItemSelected
2247 */
2248 public boolean onCreateOptionsMenu(Menu menu) {
2249 if (mParent != null) {
2250 return mParent.onCreateOptionsMenu(menu);
2251 }
2252 return true;
2253 }
2254
2255 /**
2256 * Prepare the Screen's standard options menu to be displayed. This is
2257 * called right before the menu is shown, every time it is shown. You can
2258 * use this method to efficiently enable/disable items or otherwise
2259 * dynamically modify the contents.
2260 *
2261 * <p>The default implementation updates the system menu items based on the
2262 * activity's state. Deriving classes should always call through to the
2263 * base class implementation.
2264 *
2265 * @param menu The options menu as last shown or first initialized by
2266 * onCreateOptionsMenu().
2267 *
2268 * @return You must return true for the menu to be displayed;
2269 * if you return false it will not be shown.
2270 *
2271 * @see #onCreateOptionsMenu
2272 */
2273 public boolean onPrepareOptionsMenu(Menu menu) {
2274 if (mParent != null) {
2275 return mParent.onPrepareOptionsMenu(menu);
2276 }
2277 return true;
2278 }
2279
2280 /**
2281 * This hook is called whenever an item in your options menu is selected.
2282 * The default implementation simply returns false to have the normal
2283 * processing happen (calling the item's Runnable or sending a message to
2284 * its Handler as appropriate). You can use this method for any items
2285 * for which you would like to do processing without those other
2286 * facilities.
2287 *
2288 * <p>Derived classes should call through to the base class for it to
2289 * perform the default menu handling.
2290 *
2291 * @param item The menu item that was selected.
2292 *
2293 * @return boolean Return false to allow normal menu processing to
2294 * proceed, true to consume it here.
2295 *
2296 * @see #onCreateOptionsMenu
2297 */
2298 public boolean onOptionsItemSelected(MenuItem item) {
2299 if (mParent != null) {
2300 return mParent.onOptionsItemSelected(item);
2301 }
2302 return false;
2303 }
2304
2305 /**
2306 * This hook is called whenever the options menu is being closed (either by the user canceling
2307 * the menu with the back/menu button, or when an item is selected).
2308 *
2309 * @param menu The options menu as last shown or first initialized by
2310 * onCreateOptionsMenu().
2311 */
2312 public void onOptionsMenuClosed(Menu menu) {
2313 if (mParent != null) {
2314 mParent.onOptionsMenuClosed(menu);
2315 }
2316 }
2317
2318 /**
2319 * Programmatically opens the options menu. If the options menu is already
2320 * open, this method does nothing.
2321 */
2322 public void openOptionsMenu() {
2323 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2324 }
2325
2326 /**
2327 * Progammatically closes the options menu. If the options menu is already
2328 * closed, this method does nothing.
2329 */
2330 public void closeOptionsMenu() {
2331 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2332 }
2333
2334 /**
2335 * Called when a context menu for the {@code view} is about to be shown.
2336 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2337 * time the context menu is about to be shown and should be populated for
2338 * the view (or item inside the view for {@link AdapterView} subclasses,
2339 * this can be found in the {@code menuInfo})).
2340 * <p>
2341 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2342 * item has been selected.
2343 * <p>
2344 * It is not safe to hold onto the context menu after this method returns.
2345 * {@inheritDoc}
2346 */
2347 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2348 }
2349
2350 /**
2351 * Registers a context menu to be shown for the given view (multiple views
2352 * can show the context menu). This method will set the
2353 * {@link OnCreateContextMenuListener} on the view to this activity, so
2354 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2355 * called when it is time to show the context menu.
2356 *
2357 * @see #unregisterForContextMenu(View)
2358 * @param view The view that should show a context menu.
2359 */
2360 public void registerForContextMenu(View view) {
2361 view.setOnCreateContextMenuListener(this);
2362 }
2363
2364 /**
2365 * Prevents a context menu to be shown for the given view. This method will remove the
2366 * {@link OnCreateContextMenuListener} on the view.
2367 *
2368 * @see #registerForContextMenu(View)
2369 * @param view The view that should stop showing a context menu.
2370 */
2371 public void unregisterForContextMenu(View view) {
2372 view.setOnCreateContextMenuListener(null);
2373 }
2374
2375 /**
2376 * Programmatically opens the context menu for a particular {@code view}.
2377 * The {@code view} should have been added via
2378 * {@link #registerForContextMenu(View)}.
2379 *
2380 * @param view The view to show the context menu for.
2381 */
2382 public void openContextMenu(View view) {
2383 view.showContextMenu();
2384 }
2385
2386 /**
2387 * Programmatically closes the most recently opened context menu, if showing.
2388 */
2389 public void closeContextMenu() {
2390 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2391 }
2392
2393 /**
2394 * This hook is called whenever an item in a context menu is selected. The
2395 * default implementation simply returns false to have the normal processing
2396 * happen (calling the item's Runnable or sending a message to its Handler
2397 * as appropriate). You can use this method for any items for which you
2398 * would like to do processing without those other facilities.
2399 * <p>
2400 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2401 * View that added this menu item.
2402 * <p>
2403 * Derived classes should call through to the base class for it to perform
2404 * the default menu handling.
2405 *
2406 * @param item The context menu item that was selected.
2407 * @return boolean Return false to allow normal context menu processing to
2408 * proceed, true to consume it here.
2409 */
2410 public boolean onContextItemSelected(MenuItem item) {
2411 if (mParent != null) {
2412 return mParent.onContextItemSelected(item);
2413 }
2414 return false;
2415 }
2416
2417 /**
2418 * This hook is called whenever the context menu is being closed (either by
2419 * the user canceling the menu with the back/menu button, or when an item is
2420 * selected).
2421 *
2422 * @param menu The context menu that is being closed.
2423 */
2424 public void onContextMenuClosed(Menu menu) {
2425 if (mParent != null) {
2426 mParent.onContextMenuClosed(menu);
2427 }
2428 }
2429
2430 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002431 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002433 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 protected Dialog onCreateDialog(int id) {
2435 return null;
2436 }
2437
2438 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002439 * Callback for creating dialogs that are managed (saved and restored) for you
2440 * by the activity. The default implementation calls through to
2441 * {@link #onCreateDialog(int)} for compatibility.
2442 *
2443 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2444 * this method the first time, and hang onto it thereafter. Any dialog
2445 * that is created by this method will automatically be saved and restored
2446 * for you, including whether it is showing.
2447 *
2448 * <p>If you would like the activity to manage saving and restoring dialogs
2449 * for you, you should override this method and handle any ids that are
2450 * passed to {@link #showDialog}.
2451 *
2452 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2453 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2454 *
2455 * @param id The id of the dialog.
2456 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2457 * @return The dialog. If you return null, the dialog will not be created.
2458 *
2459 * @see #onPrepareDialog(int, Dialog, Bundle)
2460 * @see #showDialog(int, Bundle)
2461 * @see #dismissDialog(int)
2462 * @see #removeDialog(int)
2463 */
2464 protected Dialog onCreateDialog(int id, Bundle args) {
2465 return onCreateDialog(id);
2466 }
2467
2468 /**
2469 * @deprecated Old no-arguments version of
2470 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2471 */
2472 @Deprecated
2473 protected void onPrepareDialog(int id, Dialog dialog) {
2474 dialog.setOwnerActivity(this);
2475 }
2476
2477 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002479 * shown. The default implementation calls through to
2480 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2481 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 * <p>
2483 * Override this if you need to update a managed dialog based on the state
2484 * of the application each time it is shown. For example, a time picker
2485 * dialog might want to be updated with the current time. You should call
2486 * through to the superclass's implementation. The default implementation
2487 * will set this Activity as the owner activity on the Dialog.
2488 *
2489 * @param id The id of the managed dialog.
2490 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002491 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2492 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 * @see #showDialog(int)
2494 * @see #dismissDialog(int)
2495 * @see #removeDialog(int)
2496 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002497 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2498 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500
2501 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002502 * Simple version of {@link #showDialog(int, Bundle)} that does not
2503 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2504 * with null arguments.
2505 */
2506 public final void showDialog(int id) {
2507 showDialog(id, null);
2508 }
2509
2510 /**
2511 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 * will be made with the same id the first time this is called for a given
2513 * id. From thereafter, the dialog will be automatically saved and restored.
2514 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002515 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 * be made to provide an opportunity to do any timely preparation.
2517 *
2518 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002519 * @param args Arguments to pass through to the dialog. These will be saved
2520 * and restored for you. Note that if the dialog is already created,
2521 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2522 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08002523 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002524 * @return Returns true if the Dialog was created; false is returned if
2525 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2526 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002527 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002528 * @see #onCreateDialog(int, Bundle)
2529 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 * @see #dismissDialog(int)
2531 * @see #removeDialog(int)
2532 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002533 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002535 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002537 ManagedDialog md = mManagedDialogs.get(id);
2538 if (md == null) {
2539 md = new ManagedDialog();
2540 md.mDialog = createDialog(id, null, args);
2541 if (md.mDialog == null) {
2542 return false;
2543 }
2544 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
2546
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002547 md.mArgs = args;
2548 onPrepareDialog(id, md.mDialog, args);
2549 md.mDialog.show();
2550 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 }
2552
2553 /**
2554 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2555 *
2556 * @param id The id of the managed dialog.
2557 *
2558 * @throws IllegalArgumentException if the id was not previously shown via
2559 * {@link #showDialog(int)}.
2560 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002561 * @see #onCreateDialog(int, Bundle)
2562 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 * @see #showDialog(int)
2564 * @see #removeDialog(int)
2565 */
2566 public final void dismissDialog(int id) {
2567 if (mManagedDialogs == null) {
2568 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002570
2571 final ManagedDialog md = mManagedDialogs.get(id);
2572 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 throw missingDialog(id);
2574 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002575 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
2577
2578 /**
2579 * Creates an exception to throw if a user passed in a dialog id that is
2580 * unexpected.
2581 */
2582 private IllegalArgumentException missingDialog(int id) {
2583 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2584 + "shown via Activity#showDialog");
2585 }
2586
2587 /**
2588 * Removes any internal references to a dialog managed by this Activity.
2589 * If the dialog is showing, it will dismiss it as part of the clean up.
2590 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002591 * <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 -08002592 * want to avoid the overhead of saving and restoring it in the future.
2593 *
2594 * @param id The id of the managed dialog.
2595 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002596 * @see #onCreateDialog(int, Bundle)
2597 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 * @see #showDialog(int)
2599 * @see #dismissDialog(int)
2600 */
2601 public final void removeDialog(int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 if (mManagedDialogs == null) {
2603 return;
2604 }
2605
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002606 final ManagedDialog md = mManagedDialogs.get(id);
2607 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 return;
2609 }
2610
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002611 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 mManagedDialogs.remove(id);
2613 }
2614
2615 /**
2616 * This hook is called when the user signals the desire to start a search.
2617 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002618 * <p>You can use this function as a simple way to launch the search UI, in response to a
2619 * menu item, search button, or other widgets within your activity. Unless overidden,
2620 * calling this function is the same as calling
2621 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2622 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 *
2624 * <p>You can override this function to force global search, e.g. in response to a dedicated
2625 * search key, or to block search entirely (by simply returning false).
2626 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002627 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2628 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 *
2630 * @see android.app.SearchManager
2631 */
2632 public boolean onSearchRequested() {
2633 startSearch(null, false, null, false);
2634 return true;
2635 }
2636
2637 /**
2638 * This hook is called to launch the search UI.
2639 *
2640 * <p>It is typically called from onSearchRequested(), either directly from
2641 * Activity.onSearchRequested() or from an overridden version in any given
2642 * Activity. If your goal is simply to activate search, it is preferred to call
2643 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2644 * is to inject specific data such as context data, it is preferred to <i>override</i>
2645 * onSearchRequested(), so that any callers to it will benefit from the override.
2646 *
2647 * @param initialQuery Any non-null non-empty string will be inserted as
2648 * pre-entered text in the search query box.
2649 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2650 * any further typing will replace it. This is useful for cases where an entire pre-formed
2651 * query is being inserted. If false, the selection point will be placed at the end of the
2652 * inserted query. This is useful when the inserted query is text that the user entered,
2653 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2654 * if initialQuery is a non-empty string.</i>
2655 * @param appSearchData An application can insert application-specific
2656 * context here, in order to improve quality or specificity of its own
2657 * searches. This data will be returned with SEARCH intent(s). Null if
2658 * no extra data is required.
2659 * @param globalSearch If false, this will only launch the search that has been specifically
2660 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002661 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2663 *
2664 * @see android.app.SearchManager
2665 * @see #onSearchRequested
2666 */
2667 public void startSearch(String initialQuery, boolean selectInitialQuery,
2668 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002669 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002670 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 appSearchData, globalSearch);
2672 }
2673
2674 /**
krosaend2d60142009-08-17 08:56:48 -07002675 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2676 * the search dialog. Made available for testing purposes.
2677 *
2678 * @param query The query to trigger. If empty, the request will be ignored.
2679 * @param appSearchData An application can insert application-specific
2680 * context here, in order to improve quality or specificity of its own
2681 * searches. This data will be returned with SEARCH intent(s). Null if
2682 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002683 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002684 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002685 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002686 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002687 }
2688
2689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 * Request that key events come to this activity. Use this if your
2691 * activity has no views with focus, but the activity still wants
2692 * a chance to process key events.
2693 *
2694 * @see android.view.Window#takeKeyEvents
2695 */
2696 public void takeKeyEvents(boolean get) {
2697 getWindow().takeKeyEvents(get);
2698 }
2699
2700 /**
2701 * Enable extended window features. This is a convenience for calling
2702 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2703 *
2704 * @param featureId The desired feature as defined in
2705 * {@link android.view.Window}.
2706 * @return Returns true if the requested feature is supported and now
2707 * enabled.
2708 *
2709 * @see android.view.Window#requestFeature
2710 */
2711 public final boolean requestWindowFeature(int featureId) {
2712 return getWindow().requestFeature(featureId);
2713 }
2714
2715 /**
2716 * Convenience for calling
2717 * {@link android.view.Window#setFeatureDrawableResource}.
2718 */
2719 public final void setFeatureDrawableResource(int featureId, int resId) {
2720 getWindow().setFeatureDrawableResource(featureId, resId);
2721 }
2722
2723 /**
2724 * Convenience for calling
2725 * {@link android.view.Window#setFeatureDrawableUri}.
2726 */
2727 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2728 getWindow().setFeatureDrawableUri(featureId, uri);
2729 }
2730
2731 /**
2732 * Convenience for calling
2733 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2734 */
2735 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2736 getWindow().setFeatureDrawable(featureId, drawable);
2737 }
2738
2739 /**
2740 * Convenience for calling
2741 * {@link android.view.Window#setFeatureDrawableAlpha}.
2742 */
2743 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2744 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2745 }
2746
2747 /**
2748 * Convenience for calling
2749 * {@link android.view.Window#getLayoutInflater}.
2750 */
2751 public LayoutInflater getLayoutInflater() {
2752 return getWindow().getLayoutInflater();
2753 }
2754
2755 /**
2756 * Returns a {@link MenuInflater} with this context.
2757 */
2758 public MenuInflater getMenuInflater() {
2759 return new MenuInflater(this);
2760 }
2761
2762 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002763 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2764 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 if (mParent == null) {
2766 super.onApplyThemeResource(theme, resid, first);
2767 } else {
2768 try {
2769 theme.setTo(mParent.getTheme());
2770 } catch (Exception e) {
2771 // Empty
2772 }
2773 theme.applyStyle(resid, false);
2774 }
2775 }
2776
2777 /**
2778 * Launch an activity for which you would like a result when it finished.
2779 * When this activity exits, your
2780 * onActivityResult() method will be called with the given requestCode.
2781 * Using a negative requestCode is the same as calling
2782 * {@link #startActivity} (the activity is not launched as a sub-activity).
2783 *
2784 * <p>Note that this method should only be used with Intent protocols
2785 * that are defined to return a result. In other protocols (such as
2786 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
2787 * not get the result when you expect. For example, if the activity you
2788 * are launching uses the singleTask launch mode, it will not run in your
2789 * task and thus you will immediately receive a cancel result.
2790 *
2791 * <p>As a special case, if you call startActivityForResult() with a requestCode
2792 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
2793 * activity, then your window will not be displayed until a result is
2794 * returned back from the started activity. This is to avoid visible
2795 * flickering when redirecting to another activity.
2796 *
2797 * <p>This method throws {@link android.content.ActivityNotFoundException}
2798 * if there was no Activity found to run the given Intent.
2799 *
2800 * @param intent The intent to start.
2801 * @param requestCode If >= 0, this code will be returned in
2802 * onActivityResult() when the activity exits.
2803 *
2804 * @throws android.content.ActivityNotFoundException
2805 *
2806 * @see #startActivity
2807 */
2808 public void startActivityForResult(Intent intent, int requestCode) {
2809 if (mParent == null) {
2810 Instrumentation.ActivityResult ar =
2811 mInstrumentation.execStartActivity(
2812 this, mMainThread.getApplicationThread(), mToken, this,
2813 intent, requestCode);
2814 if (ar != null) {
2815 mMainThread.sendActivityResult(
2816 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
2817 ar.getResultData());
2818 }
2819 if (requestCode >= 0) {
2820 // If this start is requesting a result, we can avoid making
2821 // the activity visible until the result is received. Setting
2822 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2823 // activity hidden during this time, to avoid flickering.
2824 // This can only be done when a result is requested because
2825 // that guarantees we will get information back when the
2826 // activity is finished, no matter what happens to it.
2827 mStartedActivity = true;
2828 }
2829 } else {
2830 mParent.startActivityFromChild(this, intent, requestCode);
2831 }
2832 }
2833
2834 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002835 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002836 * to use a IntentSender to describe the activity to be started. If
2837 * the IntentSender is for an activity, that activity will be started
2838 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
2839 * here; otherwise, its associated action will be executed (such as
2840 * sending a broadcast) as if you had called
2841 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002842 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002843 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002844 * @param requestCode If >= 0, this code will be returned in
2845 * onActivityResult() when the activity exits.
2846 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002847 * intent parameter to {@link IntentSender#sendIntent}.
2848 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002849 * would like to change.
2850 * @param flagsValues Desired values for any bits set in
2851 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002852 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002853 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002854 public void startIntentSenderForResult(IntentSender intent, int requestCode,
2855 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2856 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002857 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002858 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002859 flagsMask, flagsValues, this);
2860 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002861 mParent.startIntentSenderFromChild(this, intent, requestCode,
2862 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002863 }
2864 }
2865
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002866 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002867 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002868 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002869 try {
2870 String resolvedType = null;
2871 if (fillInIntent != null) {
2872 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
2873 }
2874 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002875 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002876 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
2877 requestCode, flagsMask, flagsValues);
2878 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002879 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002880 }
2881 Instrumentation.checkStartActivityResult(result, null);
2882 } catch (RemoteException e) {
2883 }
2884 if (requestCode >= 0) {
2885 // If this start is requesting a result, we can avoid making
2886 // the activity visible until the result is received. Setting
2887 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2888 // activity hidden during this time, to avoid flickering.
2889 // This can only be done when a result is requested because
2890 // that guarantees we will get information back when the
2891 // activity is finished, no matter what happens to it.
2892 mStartedActivity = true;
2893 }
2894 }
2895
2896 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 * Launch a new activity. You will not receive any information about when
2898 * the activity exits. This implementation overrides the base version,
2899 * providing information about
2900 * the activity performing the launch. Because of this additional
2901 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
2902 * required; if not specified, the new activity will be added to the
2903 * task of the caller.
2904 *
2905 * <p>This method throws {@link android.content.ActivityNotFoundException}
2906 * if there was no Activity found to run the given Intent.
2907 *
2908 * @param intent The intent to start.
2909 *
2910 * @throws android.content.ActivityNotFoundException
2911 *
2912 * @see #startActivityForResult
2913 */
2914 @Override
2915 public void startActivity(Intent intent) {
2916 startActivityForResult(intent, -1);
2917 }
2918
2919 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002920 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002921 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07002922 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002923 * for more information.
2924 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002925 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002926 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002927 * intent parameter to {@link IntentSender#sendIntent}.
2928 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002929 * would like to change.
2930 * @param flagsValues Desired values for any bits set in
2931 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002932 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002933 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002934 public void startIntentSender(IntentSender intent,
2935 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2936 throws IntentSender.SendIntentException {
2937 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
2938 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002939 }
2940
2941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 * A special variation to launch an activity only if a new activity
2943 * instance is needed to handle the given Intent. In other words, this is
2944 * just like {@link #startActivityForResult(Intent, int)} except: if you are
2945 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
2946 * singleTask or singleTop
2947 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
2948 * and the activity
2949 * that handles <var>intent</var> is the same as your currently running
2950 * activity, then a new instance is not needed. In this case, instead of
2951 * the normal behavior of calling {@link #onNewIntent} this function will
2952 * return and you can handle the Intent yourself.
2953 *
2954 * <p>This function can only be called from a top-level activity; if it is
2955 * called from a child activity, a runtime exception will be thrown.
2956 *
2957 * @param intent The intent to start.
2958 * @param requestCode If >= 0, this code will be returned in
2959 * onActivityResult() when the activity exits, as described in
2960 * {@link #startActivityForResult}.
2961 *
2962 * @return If a new activity was launched then true is returned; otherwise
2963 * false is returned and you must handle the Intent yourself.
2964 *
2965 * @see #startActivity
2966 * @see #startActivityForResult
2967 */
2968 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
2969 if (mParent == null) {
2970 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
2971 try {
2972 result = ActivityManagerNative.getDefault()
2973 .startActivity(mMainThread.getApplicationThread(),
2974 intent, intent.resolveTypeIfNeeded(
2975 getContentResolver()),
2976 null, 0,
2977 mToken, mEmbeddedID, requestCode, true, false);
2978 } catch (RemoteException e) {
2979 // Empty
2980 }
2981
2982 Instrumentation.checkStartActivityResult(result, intent);
2983
2984 if (requestCode >= 0) {
2985 // If this start is requesting a result, we can avoid making
2986 // the activity visible until the result is received. Setting
2987 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2988 // activity hidden during this time, to avoid flickering.
2989 // This can only be done when a result is requested because
2990 // that guarantees we will get information back when the
2991 // activity is finished, no matter what happens to it.
2992 mStartedActivity = true;
2993 }
2994 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
2995 }
2996
2997 throw new UnsupportedOperationException(
2998 "startActivityIfNeeded can only be called from a top-level activity");
2999 }
3000
3001 /**
3002 * Special version of starting an activity, for use when you are replacing
3003 * other activity components. You can use this to hand the Intent off
3004 * to the next Activity that can handle it. You typically call this in
3005 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3006 *
3007 * @param intent The intent to dispatch to the next activity. For
3008 * correct behavior, this must be the same as the Intent that started
3009 * your own activity; the only changes you can make are to the extras
3010 * inside of it.
3011 *
3012 * @return Returns a boolean indicating whether there was another Activity
3013 * to start: true if there was a next activity to start, false if there
3014 * wasn't. In general, if true is returned you will then want to call
3015 * finish() on yourself.
3016 */
3017 public boolean startNextMatchingActivity(Intent intent) {
3018 if (mParent == null) {
3019 try {
3020 return ActivityManagerNative.getDefault()
3021 .startNextMatchingActivity(mToken, intent);
3022 } catch (RemoteException e) {
3023 // Empty
3024 }
3025 return false;
3026 }
3027
3028 throw new UnsupportedOperationException(
3029 "startNextMatchingActivity can only be called from a top-level activity");
3030 }
3031
3032 /**
3033 * This is called when a child activity of this one calls its
3034 * {@link #startActivity} or {@link #startActivityForResult} method.
3035 *
3036 * <p>This method throws {@link android.content.ActivityNotFoundException}
3037 * if there was no Activity found to run the given Intent.
3038 *
3039 * @param child The activity making the call.
3040 * @param intent The intent to start.
3041 * @param requestCode Reply request code. < 0 if reply is not requested.
3042 *
3043 * @throws android.content.ActivityNotFoundException
3044 *
3045 * @see #startActivity
3046 * @see #startActivityForResult
3047 */
3048 public void startActivityFromChild(Activity child, Intent intent,
3049 int requestCode) {
3050 Instrumentation.ActivityResult ar =
3051 mInstrumentation.execStartActivity(
3052 this, mMainThread.getApplicationThread(), mToken, child,
3053 intent, requestCode);
3054 if (ar != null) {
3055 mMainThread.sendActivityResult(
3056 mToken, child.mEmbeddedID, requestCode,
3057 ar.getResultCode(), ar.getResultData());
3058 }
3059 }
3060
3061 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003062 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003063 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003064 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003065 * for more information.
3066 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003067 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3068 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3069 int extraFlags)
3070 throws IntentSender.SendIntentException {
3071 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003072 flagsMask, flagsValues, child);
3073 }
3074
3075 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003076 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3077 * or {@link #finish} to specify an explicit transition animation to
3078 * perform next.
3079 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003080 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003081 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003082 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003083 */
3084 public void overridePendingTransition(int enterAnim, int exitAnim) {
3085 try {
3086 ActivityManagerNative.getDefault().overridePendingTransition(
3087 mToken, getPackageName(), enterAnim, exitAnim);
3088 } catch (RemoteException e) {
3089 }
3090 }
3091
3092 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 * Call this to set the result that your activity will return to its
3094 * caller.
3095 *
3096 * @param resultCode The result code to propagate back to the originating
3097 * activity, often RESULT_CANCELED or RESULT_OK
3098 *
3099 * @see #RESULT_CANCELED
3100 * @see #RESULT_OK
3101 * @see #RESULT_FIRST_USER
3102 * @see #setResult(int, Intent)
3103 */
3104 public final void setResult(int resultCode) {
3105 synchronized (this) {
3106 mResultCode = resultCode;
3107 mResultData = null;
3108 }
3109 }
3110
3111 /**
3112 * Call this to set the result that your activity will return to its
3113 * caller.
3114 *
3115 * @param resultCode The result code to propagate back to the originating
3116 * activity, often RESULT_CANCELED or RESULT_OK
3117 * @param data The data to propagate back to the originating activity.
3118 *
3119 * @see #RESULT_CANCELED
3120 * @see #RESULT_OK
3121 * @see #RESULT_FIRST_USER
3122 * @see #setResult(int)
3123 */
3124 public final void setResult(int resultCode, Intent data) {
3125 synchronized (this) {
3126 mResultCode = resultCode;
3127 mResultData = data;
3128 }
3129 }
3130
3131 /**
3132 * Return the name of the package that invoked this activity. This is who
3133 * the data in {@link #setResult setResult()} will be sent to. You can
3134 * use this information to validate that the recipient is allowed to
3135 * receive the data.
3136 *
3137 * <p>Note: if the calling activity is not expecting a result (that is it
3138 * did not use the {@link #startActivityForResult}
3139 * form that includes a request code), then the calling package will be
3140 * null.
3141 *
3142 * @return The package of the activity that will receive your
3143 * reply, or null if none.
3144 */
3145 public String getCallingPackage() {
3146 try {
3147 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3148 } catch (RemoteException e) {
3149 return null;
3150 }
3151 }
3152
3153 /**
3154 * Return the name of the activity that invoked this activity. This is
3155 * who the data in {@link #setResult setResult()} will be sent to. You
3156 * can use this information to validate that the recipient is allowed to
3157 * receive the data.
3158 *
3159 * <p>Note: if the calling activity is not expecting a result (that is it
3160 * did not use the {@link #startActivityForResult}
3161 * form that includes a request code), then the calling package will be
3162 * null.
3163 *
3164 * @return String The full name of the activity that will receive your
3165 * reply, or null if none.
3166 */
3167 public ComponentName getCallingActivity() {
3168 try {
3169 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3170 } catch (RemoteException e) {
3171 return null;
3172 }
3173 }
3174
3175 /**
3176 * Control whether this activity's main window is visible. This is intended
3177 * only for the special case of an activity that is not going to show a
3178 * UI itself, but can't just finish prior to onResume() because it needs
3179 * to wait for a service binding or such. Setting this to false allows
3180 * you to prevent your UI from being shown during that time.
3181 *
3182 * <p>The default value for this is taken from the
3183 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3184 */
3185 public void setVisible(boolean visible) {
3186 if (mVisibleFromClient != visible) {
3187 mVisibleFromClient = visible;
3188 if (mVisibleFromServer) {
3189 if (visible) makeVisible();
3190 else mDecor.setVisibility(View.INVISIBLE);
3191 }
3192 }
3193 }
3194
3195 void makeVisible() {
3196 if (!mWindowAdded) {
3197 ViewManager wm = getWindowManager();
3198 wm.addView(mDecor, getWindow().getAttributes());
3199 mWindowAdded = true;
3200 }
3201 mDecor.setVisibility(View.VISIBLE);
3202 }
3203
3204 /**
3205 * Check to see whether this activity is in the process of finishing,
3206 * either because you called {@link #finish} on it or someone else
3207 * has requested that it finished. This is often used in
3208 * {@link #onPause} to determine whether the activity is simply pausing or
3209 * completely finishing.
3210 *
3211 * @return If the activity is finishing, returns true; else returns false.
3212 *
3213 * @see #finish
3214 */
3215 public boolean isFinishing() {
3216 return mFinished;
3217 }
3218
3219 /**
3220 * Call this when your activity is done and should be closed. The
3221 * ActivityResult is propagated back to whoever launched you via
3222 * onActivityResult().
3223 */
3224 public void finish() {
3225 if (mParent == null) {
3226 int resultCode;
3227 Intent resultData;
3228 synchronized (this) {
3229 resultCode = mResultCode;
3230 resultData = mResultData;
3231 }
3232 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3233 try {
3234 if (ActivityManagerNative.getDefault()
3235 .finishActivity(mToken, resultCode, resultData)) {
3236 mFinished = true;
3237 }
3238 } catch (RemoteException e) {
3239 // Empty
3240 }
3241 } else {
3242 mParent.finishFromChild(this);
3243 }
3244 }
3245
3246 /**
3247 * This is called when a child activity of this one calls its
3248 * {@link #finish} method. The default implementation simply calls
3249 * finish() on this activity (the parent), finishing the entire group.
3250 *
3251 * @param child The activity making the call.
3252 *
3253 * @see #finish
3254 */
3255 public void finishFromChild(Activity child) {
3256 finish();
3257 }
3258
3259 /**
3260 * Force finish another activity that you had previously started with
3261 * {@link #startActivityForResult}.
3262 *
3263 * @param requestCode The request code of the activity that you had
3264 * given to startActivityForResult(). If there are multiple
3265 * activities started with this request code, they
3266 * will all be finished.
3267 */
3268 public void finishActivity(int requestCode) {
3269 if (mParent == null) {
3270 try {
3271 ActivityManagerNative.getDefault()
3272 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3273 } catch (RemoteException e) {
3274 // Empty
3275 }
3276 } else {
3277 mParent.finishActivityFromChild(this, requestCode);
3278 }
3279 }
3280
3281 /**
3282 * This is called when a child activity of this one calls its
3283 * finishActivity().
3284 *
3285 * @param child The activity making the call.
3286 * @param requestCode Request code that had been used to start the
3287 * activity.
3288 */
3289 public void finishActivityFromChild(Activity child, int requestCode) {
3290 try {
3291 ActivityManagerNative.getDefault()
3292 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3293 } catch (RemoteException e) {
3294 // Empty
3295 }
3296 }
3297
3298 /**
3299 * Called when an activity you launched exits, giving you the requestCode
3300 * you started it with, the resultCode it returned, and any additional
3301 * data from it. The <var>resultCode</var> will be
3302 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3303 * didn't return any result, or crashed during its operation.
3304 *
3305 * <p>You will receive this call immediately before onResume() when your
3306 * activity is re-starting.
3307 *
3308 * @param requestCode The integer request code originally supplied to
3309 * startActivityForResult(), allowing you to identify who this
3310 * result came from.
3311 * @param resultCode The integer result code returned by the child activity
3312 * through its setResult().
3313 * @param data An Intent, which can return result data to the caller
3314 * (various data can be attached to Intent "extras").
3315 *
3316 * @see #startActivityForResult
3317 * @see #createPendingResult
3318 * @see #setResult(int)
3319 */
3320 protected void onActivityResult(int requestCode, int resultCode,
3321 Intent data) {
3322 }
3323
3324 /**
3325 * Create a new PendingIntent object which you can hand to others
3326 * for them to use to send result data back to your
3327 * {@link #onActivityResult} callback. The created object will be either
3328 * one-shot (becoming invalid after a result is sent back) or multiple
3329 * (allowing any number of results to be sent through it).
3330 *
3331 * @param requestCode Private request code for the sender that will be
3332 * associated with the result data when it is returned. The sender can not
3333 * modify this value, allowing you to identify incoming results.
3334 * @param data Default data to supply in the result, which may be modified
3335 * by the sender.
3336 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3337 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3338 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3339 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3340 * or any of the flags as supported by
3341 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3342 * of the intent that can be supplied when the actual send happens.
3343 *
3344 * @return Returns an existing or new PendingIntent matching the given
3345 * parameters. May return null only if
3346 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3347 * supplied.
3348 *
3349 * @see PendingIntent
3350 */
3351 public PendingIntent createPendingResult(int requestCode, Intent data,
3352 int flags) {
3353 String packageName = getPackageName();
3354 try {
3355 IIntentSender target =
3356 ActivityManagerNative.getDefault().getIntentSender(
3357 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3358 mParent == null ? mToken : mParent.mToken,
3359 mEmbeddedID, requestCode, data, null, flags);
3360 return target != null ? new PendingIntent(target) : null;
3361 } catch (RemoteException e) {
3362 // Empty
3363 }
3364 return null;
3365 }
3366
3367 /**
3368 * Change the desired orientation of this activity. If the activity
3369 * is currently in the foreground or otherwise impacting the screen
3370 * orientation, the screen will immediately be changed (possibly causing
3371 * the activity to be restarted). Otherwise, this will be used the next
3372 * time the activity is visible.
3373 *
3374 * @param requestedOrientation An orientation constant as used in
3375 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3376 */
3377 public void setRequestedOrientation(int requestedOrientation) {
3378 if (mParent == null) {
3379 try {
3380 ActivityManagerNative.getDefault().setRequestedOrientation(
3381 mToken, requestedOrientation);
3382 } catch (RemoteException e) {
3383 // Empty
3384 }
3385 } else {
3386 mParent.setRequestedOrientation(requestedOrientation);
3387 }
3388 }
3389
3390 /**
3391 * Return the current requested orientation of the activity. This will
3392 * either be the orientation requested in its component's manifest, or
3393 * the last requested orientation given to
3394 * {@link #setRequestedOrientation(int)}.
3395 *
3396 * @return Returns an orientation constant as used in
3397 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3398 */
3399 public int getRequestedOrientation() {
3400 if (mParent == null) {
3401 try {
3402 return ActivityManagerNative.getDefault()
3403 .getRequestedOrientation(mToken);
3404 } catch (RemoteException e) {
3405 // Empty
3406 }
3407 } else {
3408 return mParent.getRequestedOrientation();
3409 }
3410 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3411 }
3412
3413 /**
3414 * Return the identifier of the task this activity is in. This identifier
3415 * will remain the same for the lifetime of the activity.
3416 *
3417 * @return Task identifier, an opaque integer.
3418 */
3419 public int getTaskId() {
3420 try {
3421 return ActivityManagerNative.getDefault()
3422 .getTaskForActivity(mToken, false);
3423 } catch (RemoteException e) {
3424 return -1;
3425 }
3426 }
3427
3428 /**
3429 * Return whether this activity is the root of a task. The root is the
3430 * first activity in a task.
3431 *
3432 * @return True if this is the root activity, else false.
3433 */
3434 public boolean isTaskRoot() {
3435 try {
3436 return ActivityManagerNative.getDefault()
3437 .getTaskForActivity(mToken, true) >= 0;
3438 } catch (RemoteException e) {
3439 return false;
3440 }
3441 }
3442
3443 /**
3444 * Move the task containing this activity to the back of the activity
3445 * stack. The activity's order within the task is unchanged.
3446 *
3447 * @param nonRoot If false then this only works if the activity is the root
3448 * of a task; if true it will work for any activity in
3449 * a task.
3450 *
3451 * @return If the task was moved (or it was already at the
3452 * back) true is returned, else false.
3453 */
3454 public boolean moveTaskToBack(boolean nonRoot) {
3455 try {
3456 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3457 mToken, nonRoot);
3458 } catch (RemoteException e) {
3459 // Empty
3460 }
3461 return false;
3462 }
3463
3464 /**
3465 * Returns class name for this activity with the package prefix removed.
3466 * This is the default name used to read and write settings.
3467 *
3468 * @return The local class name.
3469 */
3470 public String getLocalClassName() {
3471 final String pkg = getPackageName();
3472 final String cls = mComponent.getClassName();
3473 int packageLen = pkg.length();
3474 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3475 || cls.charAt(packageLen) != '.') {
3476 return cls;
3477 }
3478 return cls.substring(packageLen+1);
3479 }
3480
3481 /**
3482 * Returns complete component name of this activity.
3483 *
3484 * @return Returns the complete component name for this activity
3485 */
3486 public ComponentName getComponentName()
3487 {
3488 return mComponent;
3489 }
3490
3491 /**
3492 * Retrieve a {@link SharedPreferences} object for accessing preferences
3493 * that are private to this activity. This simply calls the underlying
3494 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3495 * class name as the preferences name.
3496 *
3497 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3498 * operation, {@link #MODE_WORLD_READABLE} and
3499 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3500 *
3501 * @return Returns the single SharedPreferences instance that can be used
3502 * to retrieve and modify the preference values.
3503 */
3504 public SharedPreferences getPreferences(int mode) {
3505 return getSharedPreferences(getLocalClassName(), mode);
3506 }
3507
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003508 private void ensureSearchManager() {
3509 if (mSearchManager != null) {
3510 return;
3511 }
3512
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003513 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003514 }
3515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 @Override
3517 public Object getSystemService(String name) {
3518 if (getBaseContext() == null) {
3519 throw new IllegalStateException(
3520 "System services not available to Activities before onCreate()");
3521 }
3522
3523 if (WINDOW_SERVICE.equals(name)) {
3524 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003525 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003526 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003527 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 }
3529 return super.getSystemService(name);
3530 }
3531
3532 /**
3533 * Change the title associated with this activity. If this is a
3534 * top-level activity, the title for its window will change. If it
3535 * is an embedded activity, the parent can do whatever it wants
3536 * with it.
3537 */
3538 public void setTitle(CharSequence title) {
3539 mTitle = title;
3540 onTitleChanged(title, mTitleColor);
3541
3542 if (mParent != null) {
3543 mParent.onChildTitleChanged(this, title);
3544 }
3545 }
3546
3547 /**
3548 * Change the title associated with this activity. If this is a
3549 * top-level activity, the title for its window will change. If it
3550 * is an embedded activity, the parent can do whatever it wants
3551 * with it.
3552 */
3553 public void setTitle(int titleId) {
3554 setTitle(getText(titleId));
3555 }
3556
3557 public void setTitleColor(int textColor) {
3558 mTitleColor = textColor;
3559 onTitleChanged(mTitle, textColor);
3560 }
3561
3562 public final CharSequence getTitle() {
3563 return mTitle;
3564 }
3565
3566 public final int getTitleColor() {
3567 return mTitleColor;
3568 }
3569
3570 protected void onTitleChanged(CharSequence title, int color) {
3571 if (mTitleReady) {
3572 final Window win = getWindow();
3573 if (win != null) {
3574 win.setTitle(title);
3575 if (color != 0) {
3576 win.setTitleColor(color);
3577 }
3578 }
3579 }
3580 }
3581
3582 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3583 }
3584
3585 /**
3586 * Sets the visibility of the progress bar in the title.
3587 * <p>
3588 * In order for the progress bar to be shown, the feature must be requested
3589 * via {@link #requestWindowFeature(int)}.
3590 *
3591 * @param visible Whether to show the progress bars in the title.
3592 */
3593 public final void setProgressBarVisibility(boolean visible) {
3594 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3595 Window.PROGRESS_VISIBILITY_OFF);
3596 }
3597
3598 /**
3599 * Sets the visibility of the indeterminate progress bar in the title.
3600 * <p>
3601 * In order for the progress bar to be shown, the feature must be requested
3602 * via {@link #requestWindowFeature(int)}.
3603 *
3604 * @param visible Whether to show the progress bars in the title.
3605 */
3606 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3607 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3608 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3609 }
3610
3611 /**
3612 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3613 * is always indeterminate).
3614 * <p>
3615 * In order for the progress bar to be shown, the feature must be requested
3616 * via {@link #requestWindowFeature(int)}.
3617 *
3618 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3619 */
3620 public final void setProgressBarIndeterminate(boolean indeterminate) {
3621 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3622 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3623 }
3624
3625 /**
3626 * Sets the progress for the progress bars in the title.
3627 * <p>
3628 * In order for the progress bar to be shown, the feature must be requested
3629 * via {@link #requestWindowFeature(int)}.
3630 *
3631 * @param progress The progress for the progress bar. Valid ranges are from
3632 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3633 * bar will be completely filled and will fade out.
3634 */
3635 public final void setProgress(int progress) {
3636 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3637 }
3638
3639 /**
3640 * Sets the secondary progress for the progress bar in the title. This
3641 * progress is drawn between the primary progress (set via
3642 * {@link #setProgress(int)} and the background. It can be ideal for media
3643 * scenarios such as showing the buffering progress while the default
3644 * progress shows the play progress.
3645 * <p>
3646 * In order for the progress bar to be shown, the feature must be requested
3647 * via {@link #requestWindowFeature(int)}.
3648 *
3649 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3650 * 0 to 10000 (both inclusive).
3651 */
3652 public final void setSecondaryProgress(int secondaryProgress) {
3653 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3654 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3655 }
3656
3657 /**
3658 * Suggests an audio stream whose volume should be changed by the hardware
3659 * volume controls.
3660 * <p>
3661 * The suggested audio stream will be tied to the window of this Activity.
3662 * If the Activity is switched, the stream set here is no longer the
3663 * suggested stream. The client does not need to save and restore the old
3664 * suggested stream value in onPause and onResume.
3665 *
3666 * @param streamType The type of the audio stream whose volume should be
3667 * changed by the hardware volume controls. It is not guaranteed that
3668 * the hardware volume controls will always change this stream's
3669 * volume (for example, if a call is in progress, its stream's volume
3670 * may be changed instead). To reset back to the default, use
3671 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3672 */
3673 public final void setVolumeControlStream(int streamType) {
3674 getWindow().setVolumeControlStream(streamType);
3675 }
3676
3677 /**
3678 * Gets the suggested audio stream whose volume should be changed by the
3679 * harwdare volume controls.
3680 *
3681 * @return The suggested audio stream type whose volume should be changed by
3682 * the hardware volume controls.
3683 * @see #setVolumeControlStream(int)
3684 */
3685 public final int getVolumeControlStream() {
3686 return getWindow().getVolumeControlStream();
3687 }
3688
3689 /**
3690 * Runs the specified action on the UI thread. If the current thread is the UI
3691 * thread, then the action is executed immediately. If the current thread is
3692 * not the UI thread, the action is posted to the event queue of the UI thread.
3693 *
3694 * @param action the action to run on the UI thread
3695 */
3696 public final void runOnUiThread(Runnable action) {
3697 if (Thread.currentThread() != mUiThread) {
3698 mHandler.post(action);
3699 } else {
3700 action.run();
3701 }
3702 }
3703
3704 /**
3705 * Stub implementation of {@link android.view.LayoutInflater.Factory#onCreateView} used when
3706 * inflating with the LayoutInflater returned by {@link #getSystemService}. This
3707 * implementation simply returns null for all view names.
3708 *
3709 * @see android.view.LayoutInflater#createView
3710 * @see android.view.Window#getLayoutInflater
3711 */
3712 public View onCreateView(String name, Context context, AttributeSet attrs) {
3713 return null;
3714 }
3715
3716 // ------------------ Internal API ------------------
3717
3718 final void setParent(Activity parent) {
3719 mParent = parent;
3720 }
3721
3722 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
3723 Application application, Intent intent, ActivityInfo info, CharSequence title,
3724 Activity parent, String id, Object lastNonConfigurationInstance,
3725 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003726 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 lastNonConfigurationInstance, null, config);
3728 }
3729
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003730 final void attach(Context context, ActivityThread aThread,
3731 Instrumentation instr, IBinder token, int ident,
3732 Application application, Intent intent, ActivityInfo info,
3733 CharSequence title, Activity parent, String id,
3734 Object lastNonConfigurationInstance,
3735 HashMap<String,Object> lastNonConfigurationChildInstances,
3736 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 attachBaseContext(context);
3738
3739 mWindow = PolicyManager.makeNewWindow(this);
3740 mWindow.setCallback(this);
3741 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
3742 mWindow.setSoftInputMode(info.softInputMode);
3743 }
3744 mUiThread = Thread.currentThread();
3745
3746 mMainThread = aThread;
3747 mInstrumentation = instr;
3748 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003749 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 mApplication = application;
3751 mIntent = intent;
3752 mComponent = intent.getComponent();
3753 mActivityInfo = info;
3754 mTitle = title;
3755 mParent = parent;
3756 mEmbeddedID = id;
3757 mLastNonConfigurationInstance = lastNonConfigurationInstance;
3758 mLastNonConfigurationChildInstances = lastNonConfigurationChildInstances;
3759
3760 mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
3761 if (mParent != null) {
3762 mWindow.setContainer(mParent.getWindow());
3763 }
3764 mWindowManager = mWindow.getWindowManager();
3765 mCurrentConfig = config;
3766 }
3767
3768 final IBinder getActivityToken() {
3769 return mParent != null ? mParent.getActivityToken() : mToken;
3770 }
3771
3772 final void performStart() {
3773 mCalled = false;
3774 mInstrumentation.callActivityOnStart(this);
3775 if (!mCalled) {
3776 throw new SuperNotCalledException(
3777 "Activity " + mComponent.toShortString() +
3778 " did not call through to super.onStart()");
3779 }
3780 }
3781
3782 final void performRestart() {
Makoto Onuki2f6a0182010-02-22 13:26:59 -08003783 synchronized (mManagedCursors) {
3784 final int N = mManagedCursors.size();
3785 for (int i=0; i<N; i++) {
3786 ManagedCursor mc = mManagedCursors.get(i);
3787 if (mc.mReleased || mc.mUpdated) {
3788 mc.mCursor.requery();
3789 mc.mReleased = false;
3790 mc.mUpdated = false;
3791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 }
3793 }
3794
3795 if (mStopped) {
3796 mStopped = false;
3797 mCalled = false;
3798 mInstrumentation.callActivityOnRestart(this);
3799 if (!mCalled) {
3800 throw new SuperNotCalledException(
3801 "Activity " + mComponent.toShortString() +
3802 " did not call through to super.onRestart()");
3803 }
3804 performStart();
3805 }
3806 }
3807
3808 final void performResume() {
3809 performRestart();
3810
3811 mLastNonConfigurationInstance = null;
3812
3813 // First call onResume() -before- setting mResumed, so we don't
3814 // send out any status bar / menu notifications the client makes.
3815 mCalled = false;
3816 mInstrumentation.callActivityOnResume(this);
3817 if (!mCalled) {
3818 throw new SuperNotCalledException(
3819 "Activity " + mComponent.toShortString() +
3820 " did not call through to super.onResume()");
3821 }
3822
3823 // Now really resume, and install the current status bar and menu.
3824 mResumed = true;
3825 mCalled = false;
3826 onPostResume();
3827 if (!mCalled) {
3828 throw new SuperNotCalledException(
3829 "Activity " + mComponent.toShortString() +
3830 " did not call through to super.onPostResume()");
3831 }
3832 }
3833
3834 final void performPause() {
3835 onPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
3837
3838 final void performUserLeaving() {
3839 onUserInteraction();
3840 onUserLeaveHint();
3841 }
3842
3843 final void performStop() {
3844 if (!mStopped) {
3845 if (mWindow != null) {
3846 mWindow.closeAllPanels();
3847 }
3848
3849 mCalled = false;
3850 mInstrumentation.callActivityOnStop(this);
3851 if (!mCalled) {
3852 throw new SuperNotCalledException(
3853 "Activity " + mComponent.toShortString() +
3854 " did not call through to super.onStop()");
3855 }
3856
Makoto Onuki2f6a0182010-02-22 13:26:59 -08003857 synchronized (mManagedCursors) {
3858 final int N = mManagedCursors.size();
3859 for (int i=0; i<N; i++) {
3860 ManagedCursor mc = mManagedCursors.get(i);
3861 if (!mc.mReleased) {
3862 mc.mCursor.deactivate();
3863 mc.mReleased = true;
3864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 }
3866 }
3867
3868 mStopped = true;
3869 }
3870 mResumed = false;
3871 }
3872
3873 final boolean isResumed() {
3874 return mResumed;
3875 }
3876
3877 void dispatchActivityResult(String who, int requestCode,
3878 int resultCode, Intent data) {
3879 if (Config.LOGV) Log.v(
3880 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
3881 + ", resCode=" + resultCode + ", data=" + data);
3882 if (who == null) {
3883 onActivityResult(requestCode, resultCode, data);
3884 }
3885 }
3886}