blob: 95142e380ba2301b2e97c22c8ede4ffc769def37 [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.
1311 int numCursors = mManagedCursors.size();
1312 for (int i = 0; i < numCursors; i++) {
1313 ManagedCursor c = mManagedCursors.get(i);
1314 if (c != null) {
1315 c.mCursor.close();
1316 }
1317 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001318 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
1321 /**
1322 * Called by the system when the device configuration changes while your
1323 * activity is running. Note that this will <em>only</em> be called if
1324 * you have selected configurations you would like to handle with the
1325 * {@link android.R.attr#configChanges} attribute in your manifest. If
1326 * any configuration change occurs that is not selected to be reported
1327 * by that attribute, then instead of reporting it the system will stop
1328 * and restart the activity (to have it launched with the new
1329 * configuration).
1330 *
1331 * <p>At the time that this function has been called, your Resources
1332 * object will have been updated to return resource values matching the
1333 * new configuration.
1334 *
1335 * @param newConfig The new device configuration.
1336 */
1337 public void onConfigurationChanged(Configuration newConfig) {
1338 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01001339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 if (mWindow != null) {
1341 // Pass the configuration changed event to the window
1342 mWindow.onConfigurationChanged(newConfig);
1343 }
1344 }
1345
1346 /**
1347 * If this activity is being destroyed because it can not handle a
1348 * configuration parameter being changed (and thus its
1349 * {@link #onConfigurationChanged(Configuration)} method is
1350 * <em>not</em> being called), then you can use this method to discover
1351 * the set of changes that have occurred while in the process of being
1352 * destroyed. Note that there is no guarantee that these will be
1353 * accurate (other changes could have happened at any time), so you should
1354 * only use this as an optimization hint.
1355 *
1356 * @return Returns a bit field of the configuration parameters that are
1357 * changing, as defined by the {@link android.content.res.Configuration}
1358 * class.
1359 */
1360 public int getChangingConfigurations() {
1361 return mConfigChangeFlags;
1362 }
1363
1364 /**
1365 * Retrieve the non-configuration instance data that was previously
1366 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1367 * be available from the initial {@link #onCreate} and
1368 * {@link #onStart} calls to the new instance, allowing you to extract
1369 * any useful dynamic state from the previous instance.
1370 *
1371 * <p>Note that the data you retrieve here should <em>only</em> be used
1372 * as an optimization for handling configuration changes. You should always
1373 * be able to handle getting a null pointer back, and an activity must
1374 * still be able to restore itself to its previous state (through the
1375 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1376 * function returns null.
1377 *
1378 * @return Returns the object previously returned by
1379 * {@link #onRetainNonConfigurationInstance()}.
1380 */
1381 public Object getLastNonConfigurationInstance() {
1382 return mLastNonConfigurationInstance;
1383 }
1384
1385 /**
1386 * Called by the system, as part of destroying an
1387 * activity due to a configuration change, when it is known that a new
1388 * instance will immediately be created for the new configuration. You
1389 * can return any object you like here, including the activity instance
1390 * itself, which can later be retrieved by calling
1391 * {@link #getLastNonConfigurationInstance()} in the new activity
1392 * instance.
1393 *
1394 * <p>This function is called purely as an optimization, and you must
1395 * not rely on it being called. When it is called, a number of guarantees
1396 * will be made to help optimize configuration switching:
1397 * <ul>
1398 * <li> The function will be called between {@link #onStop} and
1399 * {@link #onDestroy}.
1400 * <li> A new instance of the activity will <em>always</em> be immediately
1401 * created after this one's {@link #onDestroy()} is called.
1402 * <li> The object you return here will <em>always</em> be available from
1403 * the {@link #getLastNonConfigurationInstance()} method of the following
1404 * activity instance as described there.
1405 * </ul>
1406 *
1407 * <p>These guarantees are designed so that an activity can use this API
1408 * to propagate extensive state from the old to new activity instance, from
1409 * loaded bitmaps, to network connections, to evenly actively running
1410 * threads. Note that you should <em>not</em> propagate any data that
1411 * may change based on the configuration, including any data loaded from
1412 * resources such as strings, layouts, or drawables.
1413 *
1414 * @return Return any Object holding the desired state to propagate to the
1415 * next activity instance.
1416 */
1417 public Object onRetainNonConfigurationInstance() {
1418 return null;
1419 }
1420
1421 /**
1422 * Retrieve the non-configuration instance data that was previously
1423 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
1424 * be available from the initial {@link #onCreate} and
1425 * {@link #onStart} calls to the new instance, allowing you to extract
1426 * any useful dynamic state from the previous instance.
1427 *
1428 * <p>Note that the data you retrieve here should <em>only</em> be used
1429 * as an optimization for handling configuration changes. You should always
1430 * be able to handle getting a null pointer back, and an activity must
1431 * still be able to restore itself to its previous state (through the
1432 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1433 * function returns null.
1434 *
1435 * @return Returns the object previously returned by
1436 * {@link #onRetainNonConfigurationChildInstances()}
1437 */
1438 HashMap<String,Object> getLastNonConfigurationChildInstances() {
1439 return mLastNonConfigurationChildInstances;
1440 }
1441
1442 /**
1443 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
1444 * it should return either a mapping from child activity id strings to arbitrary objects,
1445 * or null. This method is intended to be used by Activity framework subclasses that control a
1446 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
1447 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
1448 */
1449 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
1450 return null;
1451 }
1452
1453 public void onLowMemory() {
1454 mCalled = true;
1455 }
1456
1457 /**
1458 * Wrapper around
1459 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1460 * that gives the resulting {@link Cursor} to call
1461 * {@link #startManagingCursor} so that the activity will manage its
1462 * lifecycle for you.
1463 *
1464 * @param uri The URI of the content provider to query.
1465 * @param projection List of columns to return.
1466 * @param selection SQL WHERE clause.
1467 * @param sortOrder SQL ORDER BY clause.
1468 *
1469 * @return The Cursor that was returned by query().
1470 *
1471 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1472 * @see #startManagingCursor
1473 * @hide
1474 */
1475 public final Cursor managedQuery(Uri uri,
1476 String[] projection,
1477 String selection,
1478 String sortOrder)
1479 {
1480 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
1481 if (c != null) {
1482 startManagingCursor(c);
1483 }
1484 return c;
1485 }
1486
1487 /**
1488 * Wrapper around
1489 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
1490 * that gives the resulting {@link Cursor} to call
1491 * {@link #startManagingCursor} so that the activity will manage its
1492 * lifecycle for you.
1493 *
1494 * @param uri The URI of the content provider to query.
1495 * @param projection List of columns to return.
1496 * @param selection SQL WHERE clause.
1497 * @param selectionArgs The arguments to selection, if any ?s are pesent
1498 * @param sortOrder SQL ORDER BY clause.
1499 *
1500 * @return The Cursor that was returned by query().
1501 *
1502 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
1503 * @see #startManagingCursor
1504 */
1505 public final Cursor managedQuery(Uri uri,
1506 String[] projection,
1507 String selection,
1508 String[] selectionArgs,
1509 String sortOrder)
1510 {
1511 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
1512 if (c != null) {
1513 startManagingCursor(c);
1514 }
1515 return c;
1516 }
1517
1518 /**
1519 * Wrapper around {@link Cursor#commitUpdates()} that takes care of noting
1520 * that the Cursor needs to be requeried. You can call this method in
1521 * {@link #onPause} or {@link #onStop} to have the system call
1522 * {@link Cursor#requery} for you if the activity is later resumed. This
1523 * allows you to avoid determing when to do the requery yourself (which is
1524 * required for the Cursor to see any data changes that were committed with
1525 * it).
1526 *
1527 * @param c The Cursor whose changes are to be committed.
1528 *
1529 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1530 * @see #startManagingCursor
1531 * @see Cursor#commitUpdates()
1532 * @see Cursor#requery
1533 * @hide
1534 */
1535 @Deprecated
1536 public void managedCommitUpdates(Cursor c) {
1537 synchronized (mManagedCursors) {
1538 final int N = mManagedCursors.size();
1539 for (int i=0; i<N; i++) {
1540 ManagedCursor mc = mManagedCursors.get(i);
1541 if (mc.mCursor == c) {
1542 c.commitUpdates();
1543 mc.mUpdated = true;
1544 return;
1545 }
1546 }
1547 throw new RuntimeException(
1548 "Cursor " + c + " is not currently managed");
1549 }
1550 }
1551
1552 /**
1553 * This method allows the activity to take care of managing the given
1554 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
1555 * That is, when the activity is stopped it will automatically call
1556 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
1557 * it will call {@link Cursor#requery} for you. When the activity is
1558 * destroyed, all managed Cursors will be closed automatically.
1559 *
1560 * @param c The Cursor to be managed.
1561 *
1562 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
1563 * @see #stopManagingCursor
1564 */
1565 public void startManagingCursor(Cursor c) {
1566 synchronized (mManagedCursors) {
1567 mManagedCursors.add(new ManagedCursor(c));
1568 }
1569 }
1570
1571 /**
1572 * Given a Cursor that was previously given to
1573 * {@link #startManagingCursor}, stop the activity's management of that
1574 * cursor.
1575 *
1576 * @param c The Cursor that was being managed.
1577 *
1578 * @see #startManagingCursor
1579 */
1580 public void stopManagingCursor(Cursor c) {
1581 synchronized (mManagedCursors) {
1582 final int N = mManagedCursors.size();
1583 for (int i=0; i<N; i++) {
1584 ManagedCursor mc = mManagedCursors.get(i);
1585 if (mc.mCursor == c) {
1586 mManagedCursors.remove(i);
1587 break;
1588 }
1589 }
1590 }
1591 }
1592
1593 /**
1594 * Control whether this activity is required to be persistent. By default
1595 * activities are not persistent; setting this to true will prevent the
1596 * system from stopping this activity or its process when running low on
1597 * resources.
1598 *
1599 * <p><em>You should avoid using this method</em>, it has severe negative
1600 * consequences on how well the system can manage its resources. A better
1601 * approach is to implement an application service that you control with
1602 * {@link Context#startService} and {@link Context#stopService}.
1603 *
1604 * @param isPersistent Control whether the current activity must be
1605 * persistent, true if so, false for the normal
1606 * behavior.
1607 */
1608 public void setPersistent(boolean isPersistent) {
1609 if (mParent == null) {
1610 try {
1611 ActivityManagerNative.getDefault()
1612 .setPersistent(mToken, isPersistent);
1613 } catch (RemoteException e) {
1614 // Empty
1615 }
1616 } else {
1617 throw new RuntimeException("setPersistent() not yet supported for embedded activities");
1618 }
1619 }
1620
1621 /**
1622 * Finds a view that was identified by the id attribute from the XML that
1623 * was processed in {@link #onCreate}.
1624 *
1625 * @return The view if found or null otherwise.
1626 */
1627 public View findViewById(int id) {
1628 return getWindow().findViewById(id);
1629 }
1630
1631 /**
1632 * Set the activity content from a layout resource. The resource will be
1633 * inflated, adding all top-level views to the activity.
1634 *
1635 * @param layoutResID Resource ID to be inflated.
1636 */
1637 public void setContentView(int layoutResID) {
1638 getWindow().setContentView(layoutResID);
1639 }
1640
1641 /**
1642 * Set the activity content to an explicit view. This view is placed
1643 * directly into the activity's view hierarchy. It can itself be a complex
1644 * view hierarhcy.
1645 *
1646 * @param view The desired content to display.
1647 */
1648 public void setContentView(View view) {
1649 getWindow().setContentView(view);
1650 }
1651
1652 /**
1653 * Set the activity content to an explicit view. This view is placed
1654 * directly into the activity's view hierarchy. It can itself be a complex
1655 * view hierarhcy.
1656 *
1657 * @param view The desired content to display.
1658 * @param params Layout parameters for the view.
1659 */
1660 public void setContentView(View view, ViewGroup.LayoutParams params) {
1661 getWindow().setContentView(view, params);
1662 }
1663
1664 /**
1665 * Add an additional content view to the activity. Added after any existing
1666 * ones in the activity -- existing views are NOT removed.
1667 *
1668 * @param view The desired content to display.
1669 * @param params Layout parameters for the view.
1670 */
1671 public void addContentView(View view, ViewGroup.LayoutParams params) {
1672 getWindow().addContentView(view, params);
1673 }
1674
1675 /**
1676 * Use with {@link #setDefaultKeyMode} to turn off default handling of
1677 * keys.
1678 *
1679 * @see #setDefaultKeyMode
1680 */
1681 static public final int DEFAULT_KEYS_DISABLE = 0;
1682 /**
1683 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
1684 * key handling.
1685 *
1686 * @see #setDefaultKeyMode
1687 */
1688 static public final int DEFAULT_KEYS_DIALER = 1;
1689 /**
1690 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
1691 * default key handling.
1692 *
1693 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
1694 *
1695 * @see #setDefaultKeyMode
1696 */
1697 static public final int DEFAULT_KEYS_SHORTCUT = 2;
1698 /**
1699 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1700 * will start an application-defined search. (If the application or activity does not
1701 * actually define a search, the the keys will be ignored.)
1702 *
1703 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1704 *
1705 * @see #setDefaultKeyMode
1706 */
1707 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
1708
1709 /**
1710 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
1711 * will start a global search (typically web search, but some platforms may define alternate
1712 * methods for global search)
1713 *
1714 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
1715 *
1716 * @see #setDefaultKeyMode
1717 */
1718 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
1719
1720 /**
1721 * Select the default key handling for this activity. This controls what
1722 * will happen to key events that are not otherwise handled. The default
1723 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
1724 * floor. Other modes allow you to launch the dialer
1725 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
1726 * menu without requiring the menu key be held down
1727 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
1728 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
1729 *
1730 * <p>Note that the mode selected here does not impact the default
1731 * handling of system keys, such as the "back" and "menu" keys, and your
1732 * activity and its views always get a first chance to receive and handle
1733 * all application keys.
1734 *
1735 * @param mode The desired default key mode constant.
1736 *
1737 * @see #DEFAULT_KEYS_DISABLE
1738 * @see #DEFAULT_KEYS_DIALER
1739 * @see #DEFAULT_KEYS_SHORTCUT
1740 * @see #DEFAULT_KEYS_SEARCH_LOCAL
1741 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
1742 * @see #onKeyDown
1743 */
1744 public final void setDefaultKeyMode(int mode) {
1745 mDefaultKeyMode = mode;
1746
1747 // Some modes use a SpannableStringBuilder to track & dispatch input events
1748 // This list must remain in sync with the switch in onKeyDown()
1749 switch (mode) {
1750 case DEFAULT_KEYS_DISABLE:
1751 case DEFAULT_KEYS_SHORTCUT:
1752 mDefaultKeySsb = null; // not used in these modes
1753 break;
1754 case DEFAULT_KEYS_DIALER:
1755 case DEFAULT_KEYS_SEARCH_LOCAL:
1756 case DEFAULT_KEYS_SEARCH_GLOBAL:
1757 mDefaultKeySsb = new SpannableStringBuilder();
1758 Selection.setSelection(mDefaultKeySsb,0);
1759 break;
1760 default:
1761 throw new IllegalArgumentException();
1762 }
1763 }
1764
1765 /**
1766 * Called when a key was pressed down and not handled by any of the views
1767 * inside of the activity. So, for example, key presses while the cursor
1768 * is inside a TextView will not trigger the event (unless it is a navigation
1769 * to another object) because TextView handles its own key presses.
1770 *
1771 * <p>If the focused view didn't want this event, this method is called.
1772 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07001773 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
1774 * by calling {@link #onBackPressed()}, though the behavior varies based
1775 * on the application compatibility mode: for
1776 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
1777 * it will set up the dispatch to call {@link #onKeyUp} where the action
1778 * will be performed; for earlier applications, it will perform the
1779 * action immediately in on-down, as those versions of the platform
1780 * behaved.
1781 *
1782 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001783 * if configured with {@link #setDefaultKeyMode}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 *
1785 * @return Return <code>true</code> to prevent this event from being propagated
1786 * further, or <code>false</code> to indicate that you have not handled
1787 * this event and it should continue to be propagated.
1788 * @see #onKeyUp
1789 * @see android.view.KeyEvent
1790 */
1791 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001792 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001793 if (getApplicationInfo().targetSdkVersion
1794 >= Build.VERSION_CODES.ECLAIR) {
1795 event.startTracking();
1796 } else {
1797 onBackPressed();
1798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 return true;
1800 }
1801
1802 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
1803 return false;
1804 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001805 if (getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL,
1806 keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
1807 return true;
1808 }
1809 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 } else {
1811 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
1812 boolean clearSpannable = false;
1813 boolean handled;
1814 if ((event.getRepeatCount() != 0) || event.isSystem()) {
1815 clearSpannable = true;
1816 handled = false;
1817 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001818 handled = TextKeyListener.getInstance().onKeyDown(
1819 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 if (handled && mDefaultKeySsb.length() > 0) {
1821 // something useable has been typed - dispatch it now.
1822
1823 final String str = mDefaultKeySsb.toString();
1824 clearSpannable = true;
1825
1826 switch (mDefaultKeyMode) {
1827 case DEFAULT_KEYS_DIALER:
1828 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
1829 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1830 startActivity(intent);
1831 break;
1832 case DEFAULT_KEYS_SEARCH_LOCAL:
1833 startSearch(str, false, null, false);
1834 break;
1835 case DEFAULT_KEYS_SEARCH_GLOBAL:
1836 startSearch(str, false, null, true);
1837 break;
1838 }
1839 }
1840 }
1841 if (clearSpannable) {
1842 mDefaultKeySsb.clear();
1843 mDefaultKeySsb.clearSpans();
1844 Selection.setSelection(mDefaultKeySsb,0);
1845 }
1846 return handled;
1847 }
1848 }
1849
1850 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001851 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
1852 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
1853 * the event).
1854 */
1855 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1856 return false;
1857 }
1858
1859 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 * Called when a key was released and not handled by any of the views
1861 * inside of the activity. So, for example, key presses while the cursor
1862 * is inside a TextView will not trigger the event (unless it is a navigation
1863 * to another object) because TextView handles its own key presses.
1864 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001865 * <p>The default implementation handles KEYCODE_BACK to stop the activity
1866 * and go back.
1867 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 * @return Return <code>true</code> to prevent this event from being propagated
1869 * further, or <code>false</code> to indicate that you have not handled
1870 * this event and it should continue to be propagated.
1871 * @see #onKeyDown
1872 * @see KeyEvent
1873 */
1874 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07001875 if (getApplicationInfo().targetSdkVersion
1876 >= Build.VERSION_CODES.ECLAIR) {
1877 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
1878 && !event.isCanceled()) {
1879 onBackPressed();
1880 return true;
1881 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 return false;
1884 }
1885
1886 /**
1887 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
1888 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
1889 * the event).
1890 */
1891 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
1892 return false;
1893 }
1894
1895 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001896 * Called when the activity has detected the user's press of the back
1897 * key. The default implementation simply finishes the current activity,
1898 * but you can override this to do whatever you want.
1899 */
1900 public void onBackPressed() {
1901 finish();
1902 }
1903
1904 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 * Called when a touch screen event was not handled by any of the views
1906 * under it. This is most useful to process touch events that happen
1907 * outside of your window bounds, where there is no view to receive it.
1908 *
1909 * @param event The touch screen event being processed.
1910 *
1911 * @return Return true if you have consumed the event, false if you haven't.
1912 * The default implementation always returns false.
1913 */
1914 public boolean onTouchEvent(MotionEvent event) {
1915 return false;
1916 }
1917
1918 /**
1919 * Called when the trackball was moved and not handled by any of the
1920 * views inside of the activity. So, for example, if the trackball moves
1921 * while focus is on a button, you will receive a call here because
1922 * buttons do not normally do anything with trackball events. The call
1923 * here happens <em>before</em> trackball movements are converted to
1924 * DPAD key events, which then get sent back to the view hierarchy, and
1925 * will be processed at the point for things like focus navigation.
1926 *
1927 * @param event The trackball event being processed.
1928 *
1929 * @return Return true if you have consumed the event, false if you haven't.
1930 * The default implementation always returns false.
1931 */
1932 public boolean onTrackballEvent(MotionEvent event) {
1933 return false;
1934 }
1935
1936 /**
1937 * Called whenever a key, touch, or trackball event is dispatched to the
1938 * activity. Implement this method if you wish to know that the user has
1939 * interacted with the device in some way while your activity is running.
1940 * This callback and {@link #onUserLeaveHint} are intended to help
1941 * activities manage status bar notifications intelligently; specifically,
1942 * for helping activities determine the proper time to cancel a notfication.
1943 *
1944 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
1945 * be accompanied by calls to {@link #onUserInteraction}. This
1946 * ensures that your activity will be told of relevant user activity such
1947 * as pulling down the notification pane and touching an item there.
1948 *
1949 * <p>Note that this callback will be invoked for the touch down action
1950 * that begins a touch gesture, but may not be invoked for the touch-moved
1951 * and touch-up actions that follow.
1952 *
1953 * @see #onUserLeaveHint()
1954 */
1955 public void onUserInteraction() {
1956 }
1957
1958 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
1959 // Update window manager if: we have a view, that view is
1960 // attached to its parent (which will be a RootView), and
1961 // this activity is not embedded.
1962 if (mParent == null) {
1963 View decor = mDecor;
1964 if (decor != null && decor.getParent() != null) {
1965 getWindowManager().updateViewLayout(decor, params);
1966 }
1967 }
1968 }
1969
1970 public void onContentChanged() {
1971 }
1972
1973 /**
1974 * Called when the current {@link Window} of the activity gains or loses
1975 * focus. This is the best indicator of whether this activity is visible
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001976 * to the user. The default implementation clears the key tracking
1977 * state, so should always be called.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07001979 * <p>Note that this provides information about global focus state, which
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 * is managed independently of activity lifecycles. As such, while focus
1981 * changes will generally have some relation to lifecycle changes (an
1982 * activity that is stopped will not generally get window focus), you
1983 * should not rely on any particular order between the callbacks here and
1984 * those in the other lifecycle methods such as {@link #onResume}.
1985 *
1986 * <p>As a general rule, however, a resumed activity will have window
1987 * focus... unless it has displayed other dialogs or popups that take
1988 * input focus, in which case the activity itself will not have focus
1989 * when the other windows have it. Likewise, the system may display
1990 * system-level windows (such as the status bar notification panel or
1991 * a system alert) which will temporarily take window input focus without
1992 * pausing the foreground activity.
1993 *
1994 * @param hasFocus Whether the window of this activity has focus.
1995 *
1996 * @see #hasWindowFocus()
1997 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07001998 * @see View#onWindowFocusChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 */
2000 public void onWindowFocusChanged(boolean hasFocus) {
2001 }
2002
2003 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07002004 * Called when the main window associated with the activity has been
2005 * attached to the window manager.
2006 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2007 * for more information.
2008 * @see View#onAttachedToWindow
2009 */
2010 public void onAttachedToWindow() {
2011 }
2012
2013 /**
2014 * Called when the main window associated with the activity has been
2015 * detached from the window manager.
2016 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2017 * for more information.
2018 * @see View#onDetachedFromWindow
2019 */
2020 public void onDetachedFromWindow() {
2021 }
2022
2023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 * Returns true if this activity's <em>main</em> window currently has window focus.
2025 * Note that this is not the same as the view itself having focus.
2026 *
2027 * @return True if this activity's main window currently has window focus.
2028 *
2029 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2030 */
2031 public boolean hasWindowFocus() {
2032 Window w = getWindow();
2033 if (w != null) {
2034 View d = w.getDecorView();
2035 if (d != null) {
2036 return d.hasWindowFocus();
2037 }
2038 }
2039 return false;
2040 }
2041
2042 /**
2043 * Called to process key events. You can override this to intercept all
2044 * key events before they are dispatched to the window. Be sure to call
2045 * this implementation for key events that should be handled normally.
2046 *
2047 * @param event The key event.
2048 *
2049 * @return boolean Return true if this event was consumed.
2050 */
2051 public boolean dispatchKeyEvent(KeyEvent event) {
2052 onUserInteraction();
Dianne Hackborn8d374262009-09-14 21:21:52 -07002053 Window win = getWindow();
2054 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 return true;
2056 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07002057 View decor = mDecor;
2058 if (decor == null) decor = win.getDecorView();
2059 return event.dispatch(this, decor != null
2060 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062
2063 /**
2064 * Called to process touch screen events. You can override this to
2065 * intercept all touch screen events before they are dispatched to the
2066 * window. Be sure to call this implementation for touch screen events
2067 * that should be handled normally.
2068 *
2069 * @param ev The touch screen event.
2070 *
2071 * @return boolean Return true if this event was consumed.
2072 */
2073 public boolean dispatchTouchEvent(MotionEvent ev) {
2074 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
2075 onUserInteraction();
2076 }
2077 if (getWindow().superDispatchTouchEvent(ev)) {
2078 return true;
2079 }
2080 return onTouchEvent(ev);
2081 }
2082
2083 /**
2084 * Called to process trackball events. You can override this to
2085 * intercept all trackball events before they are dispatched to the
2086 * window. Be sure to call this implementation for trackball events
2087 * that should be handled normally.
2088 *
2089 * @param ev The trackball event.
2090 *
2091 * @return boolean Return true if this event was consumed.
2092 */
2093 public boolean dispatchTrackballEvent(MotionEvent ev) {
2094 onUserInteraction();
2095 if (getWindow().superDispatchTrackballEvent(ev)) {
2096 return true;
2097 }
2098 return onTrackballEvent(ev);
2099 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002100
2101 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2102 event.setClassName(getClass().getName());
2103 event.setPackageName(getPackageName());
2104
2105 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08002106 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
2107 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07002108 event.setFullScreen(isFullScreen);
2109
2110 CharSequence title = getTitle();
2111 if (!TextUtils.isEmpty(title)) {
2112 event.getText().add(title);
2113 }
2114
2115 return true;
2116 }
2117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 /**
2119 * Default implementation of
2120 * {@link android.view.Window.Callback#onCreatePanelView}
2121 * for activities. This
2122 * simply returns null so that all panel sub-windows will have the default
2123 * menu behavior.
2124 */
2125 public View onCreatePanelView(int featureId) {
2126 return null;
2127 }
2128
2129 /**
2130 * Default implementation of
2131 * {@link android.view.Window.Callback#onCreatePanelMenu}
2132 * for activities. This calls through to the new
2133 * {@link #onCreateOptionsMenu} method for the
2134 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2135 * so that subclasses of Activity don't need to deal with feature codes.
2136 */
2137 public boolean onCreatePanelMenu(int featureId, Menu menu) {
2138 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
2139 return onCreateOptionsMenu(menu);
2140 }
2141 return false;
2142 }
2143
2144 /**
2145 * Default implementation of
2146 * {@link android.view.Window.Callback#onPreparePanel}
2147 * for activities. This
2148 * calls through to the new {@link #onPrepareOptionsMenu} method for the
2149 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2150 * panel, so that subclasses of
2151 * Activity don't need to deal with feature codes.
2152 */
2153 public boolean onPreparePanel(int featureId, View view, Menu menu) {
2154 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
2155 boolean goforit = onPrepareOptionsMenu(menu);
2156 return goforit && menu.hasVisibleItems();
2157 }
2158 return true;
2159 }
2160
2161 /**
2162 * {@inheritDoc}
2163 *
2164 * @return The default implementation returns true.
2165 */
2166 public boolean onMenuOpened(int featureId, Menu menu) {
2167 return true;
2168 }
2169
2170 /**
2171 * Default implementation of
2172 * {@link android.view.Window.Callback#onMenuItemSelected}
2173 * for activities. This calls through to the new
2174 * {@link #onOptionsItemSelected} method for the
2175 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
2176 * panel, so that subclasses of
2177 * Activity don't need to deal with feature codes.
2178 */
2179 public boolean onMenuItemSelected(int featureId, MenuItem item) {
2180 switch (featureId) {
2181 case Window.FEATURE_OPTIONS_PANEL:
2182 // Put event logging here so it gets called even if subclass
2183 // doesn't call through to superclass's implmeentation of each
2184 // of these methods below
2185 EventLog.writeEvent(50000, 0, item.getTitleCondensed());
2186 return onOptionsItemSelected(item);
2187
2188 case Window.FEATURE_CONTEXT_MENU:
2189 EventLog.writeEvent(50000, 1, item.getTitleCondensed());
2190 return onContextItemSelected(item);
2191
2192 default:
2193 return false;
2194 }
2195 }
2196
2197 /**
2198 * Default implementation of
2199 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
2200 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
2201 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
2202 * so that subclasses of Activity don't need to deal with feature codes.
2203 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
2204 * {@link #onContextMenuClosed(Menu)} will be called.
2205 */
2206 public void onPanelClosed(int featureId, Menu menu) {
2207 switch (featureId) {
2208 case Window.FEATURE_OPTIONS_PANEL:
2209 onOptionsMenuClosed(menu);
2210 break;
2211
2212 case Window.FEATURE_CONTEXT_MENU:
2213 onContextMenuClosed(menu);
2214 break;
2215 }
2216 }
2217
2218 /**
2219 * Initialize the contents of the Activity's standard options menu. You
2220 * should place your menu items in to <var>menu</var>.
2221 *
2222 * <p>This is only called once, the first time the options menu is
2223 * displayed. To update the menu every time it is displayed, see
2224 * {@link #onPrepareOptionsMenu}.
2225 *
2226 * <p>The default implementation populates the menu with standard system
2227 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
2228 * they will be correctly ordered with application-defined menu items.
2229 * Deriving classes should always call through to the base implementation.
2230 *
2231 * <p>You can safely hold on to <var>menu</var> (and any items created
2232 * from it), making modifications to it as desired, until the next
2233 * time onCreateOptionsMenu() is called.
2234 *
2235 * <p>When you add items to the menu, you can implement the Activity's
2236 * {@link #onOptionsItemSelected} method to handle them there.
2237 *
2238 * @param menu The options menu in which you place your items.
2239 *
2240 * @return You must return true for the menu to be displayed;
2241 * if you return false it will not be shown.
2242 *
2243 * @see #onPrepareOptionsMenu
2244 * @see #onOptionsItemSelected
2245 */
2246 public boolean onCreateOptionsMenu(Menu menu) {
2247 if (mParent != null) {
2248 return mParent.onCreateOptionsMenu(menu);
2249 }
2250 return true;
2251 }
2252
2253 /**
2254 * Prepare the Screen's standard options menu to be displayed. This is
2255 * called right before the menu is shown, every time it is shown. You can
2256 * use this method to efficiently enable/disable items or otherwise
2257 * dynamically modify the contents.
2258 *
2259 * <p>The default implementation updates the system menu items based on the
2260 * activity's state. Deriving classes should always call through to the
2261 * base class implementation.
2262 *
2263 * @param menu The options menu as last shown or first initialized by
2264 * onCreateOptionsMenu().
2265 *
2266 * @return You must return true for the menu to be displayed;
2267 * if you return false it will not be shown.
2268 *
2269 * @see #onCreateOptionsMenu
2270 */
2271 public boolean onPrepareOptionsMenu(Menu menu) {
2272 if (mParent != null) {
2273 return mParent.onPrepareOptionsMenu(menu);
2274 }
2275 return true;
2276 }
2277
2278 /**
2279 * This hook is called whenever an item in your options menu is selected.
2280 * The default implementation simply returns false to have the normal
2281 * processing happen (calling the item's Runnable or sending a message to
2282 * its Handler as appropriate). You can use this method for any items
2283 * for which you would like to do processing without those other
2284 * facilities.
2285 *
2286 * <p>Derived classes should call through to the base class for it to
2287 * perform the default menu handling.
2288 *
2289 * @param item The menu item that was selected.
2290 *
2291 * @return boolean Return false to allow normal menu processing to
2292 * proceed, true to consume it here.
2293 *
2294 * @see #onCreateOptionsMenu
2295 */
2296 public boolean onOptionsItemSelected(MenuItem item) {
2297 if (mParent != null) {
2298 return mParent.onOptionsItemSelected(item);
2299 }
2300 return false;
2301 }
2302
2303 /**
2304 * This hook is called whenever the options menu is being closed (either by the user canceling
2305 * the menu with the back/menu button, or when an item is selected).
2306 *
2307 * @param menu The options menu as last shown or first initialized by
2308 * onCreateOptionsMenu().
2309 */
2310 public void onOptionsMenuClosed(Menu menu) {
2311 if (mParent != null) {
2312 mParent.onOptionsMenuClosed(menu);
2313 }
2314 }
2315
2316 /**
2317 * Programmatically opens the options menu. If the options menu is already
2318 * open, this method does nothing.
2319 */
2320 public void openOptionsMenu() {
2321 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
2322 }
2323
2324 /**
2325 * Progammatically closes the options menu. If the options menu is already
2326 * closed, this method does nothing.
2327 */
2328 public void closeOptionsMenu() {
2329 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
2330 }
2331
2332 /**
2333 * Called when a context menu for the {@code view} is about to be shown.
2334 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
2335 * time the context menu is about to be shown and should be populated for
2336 * the view (or item inside the view for {@link AdapterView} subclasses,
2337 * this can be found in the {@code menuInfo})).
2338 * <p>
2339 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
2340 * item has been selected.
2341 * <p>
2342 * It is not safe to hold onto the context menu after this method returns.
2343 * {@inheritDoc}
2344 */
2345 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2346 }
2347
2348 /**
2349 * Registers a context menu to be shown for the given view (multiple views
2350 * can show the context menu). This method will set the
2351 * {@link OnCreateContextMenuListener} on the view to this activity, so
2352 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
2353 * called when it is time to show the context menu.
2354 *
2355 * @see #unregisterForContextMenu(View)
2356 * @param view The view that should show a context menu.
2357 */
2358 public void registerForContextMenu(View view) {
2359 view.setOnCreateContextMenuListener(this);
2360 }
2361
2362 /**
2363 * Prevents a context menu to be shown for the given view. This method will remove the
2364 * {@link OnCreateContextMenuListener} on the view.
2365 *
2366 * @see #registerForContextMenu(View)
2367 * @param view The view that should stop showing a context menu.
2368 */
2369 public void unregisterForContextMenu(View view) {
2370 view.setOnCreateContextMenuListener(null);
2371 }
2372
2373 /**
2374 * Programmatically opens the context menu for a particular {@code view}.
2375 * The {@code view} should have been added via
2376 * {@link #registerForContextMenu(View)}.
2377 *
2378 * @param view The view to show the context menu for.
2379 */
2380 public void openContextMenu(View view) {
2381 view.showContextMenu();
2382 }
2383
2384 /**
2385 * Programmatically closes the most recently opened context menu, if showing.
2386 */
2387 public void closeContextMenu() {
2388 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
2389 }
2390
2391 /**
2392 * This hook is called whenever an item in a context menu is selected. The
2393 * default implementation simply returns false to have the normal processing
2394 * happen (calling the item's Runnable or sending a message to its Handler
2395 * as appropriate). You can use this method for any items for which you
2396 * would like to do processing without those other facilities.
2397 * <p>
2398 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
2399 * View that added this menu item.
2400 * <p>
2401 * Derived classes should call through to the base class for it to perform
2402 * the default menu handling.
2403 *
2404 * @param item The context menu item that was selected.
2405 * @return boolean Return false to allow normal context menu processing to
2406 * proceed, true to consume it here.
2407 */
2408 public boolean onContextItemSelected(MenuItem item) {
2409 if (mParent != null) {
2410 return mParent.onContextItemSelected(item);
2411 }
2412 return false;
2413 }
2414
2415 /**
2416 * This hook is called whenever the context menu is being closed (either by
2417 * the user canceling the menu with the back/menu button, or when an item is
2418 * selected).
2419 *
2420 * @param menu The context menu that is being closed.
2421 */
2422 public void onContextMenuClosed(Menu menu) {
2423 if (mParent != null) {
2424 mParent.onContextMenuClosed(menu);
2425 }
2426 }
2427
2428 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002429 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002431 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 protected Dialog onCreateDialog(int id) {
2433 return null;
2434 }
2435
2436 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002437 * Callback for creating dialogs that are managed (saved and restored) for you
2438 * by the activity. The default implementation calls through to
2439 * {@link #onCreateDialog(int)} for compatibility.
2440 *
2441 * <p>If you use {@link #showDialog(int)}, the activity will call through to
2442 * this method the first time, and hang onto it thereafter. Any dialog
2443 * that is created by this method will automatically be saved and restored
2444 * for you, including whether it is showing.
2445 *
2446 * <p>If you would like the activity to manage saving and restoring dialogs
2447 * for you, you should override this method and handle any ids that are
2448 * passed to {@link #showDialog}.
2449 *
2450 * <p>If you would like an opportunity to prepare your dialog before it is shown,
2451 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
2452 *
2453 * @param id The id of the dialog.
2454 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2455 * @return The dialog. If you return null, the dialog will not be created.
2456 *
2457 * @see #onPrepareDialog(int, Dialog, Bundle)
2458 * @see #showDialog(int, Bundle)
2459 * @see #dismissDialog(int)
2460 * @see #removeDialog(int)
2461 */
2462 protected Dialog onCreateDialog(int id, Bundle args) {
2463 return onCreateDialog(id);
2464 }
2465
2466 /**
2467 * @deprecated Old no-arguments version of
2468 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
2469 */
2470 @Deprecated
2471 protected void onPrepareDialog(int id, Dialog dialog) {
2472 dialog.setOwnerActivity(this);
2473 }
2474
2475 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002477 * shown. The default implementation calls through to
2478 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
2479 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 * <p>
2481 * Override this if you need to update a managed dialog based on the state
2482 * of the application each time it is shown. For example, a time picker
2483 * dialog might want to be updated with the current time. You should call
2484 * through to the superclass's implementation. The default implementation
2485 * will set this Activity as the owner activity on the Dialog.
2486 *
2487 * @param id The id of the managed dialog.
2488 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002489 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
2490 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 * @see #showDialog(int)
2492 * @see #dismissDialog(int)
2493 * @see #removeDialog(int)
2494 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002495 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
2496 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 }
2498
2499 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002500 * Simple version of {@link #showDialog(int, Bundle)} that does not
2501 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
2502 * with null arguments.
2503 */
2504 public final void showDialog(int id) {
2505 showDialog(id, null);
2506 }
2507
2508 /**
2509 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 * will be made with the same id the first time this is called for a given
2511 * id. From thereafter, the dialog will be automatically saved and restored.
2512 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002513 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 * be made to provide an opportunity to do any timely preparation.
2515 *
2516 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002517 * @param args Arguments to pass through to the dialog. These will be saved
2518 * and restored for you. Note that if the dialog is already created,
2519 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
2520 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
2521 * If you need to rebuild the dialog, call {@link #removeDialog(int)}Êfirst.
2522 * @return Returns true if the Dialog was created; false is returned if
2523 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
2524 *
Joe Onorato37296dc2009-07-31 17:58:55 -07002525 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002526 * @see #onCreateDialog(int, Bundle)
2527 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 * @see #dismissDialog(int)
2529 * @see #removeDialog(int)
2530 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002531 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002533 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002535 ManagedDialog md = mManagedDialogs.get(id);
2536 if (md == null) {
2537 md = new ManagedDialog();
2538 md.mDialog = createDialog(id, null, args);
2539 if (md.mDialog == null) {
2540 return false;
2541 }
2542 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
2544
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002545 md.mArgs = args;
2546 onPrepareDialog(id, md.mDialog, args);
2547 md.mDialog.show();
2548 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550
2551 /**
2552 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
2553 *
2554 * @param id The id of the managed dialog.
2555 *
2556 * @throws IllegalArgumentException if the id was not previously shown via
2557 * {@link #showDialog(int)}.
2558 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002559 * @see #onCreateDialog(int, Bundle)
2560 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 * @see #showDialog(int)
2562 * @see #removeDialog(int)
2563 */
2564 public final void dismissDialog(int id) {
2565 if (mManagedDialogs == null) {
2566 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002568
2569 final ManagedDialog md = mManagedDialogs.get(id);
2570 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 throw missingDialog(id);
2572 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002573 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575
2576 /**
2577 * Creates an exception to throw if a user passed in a dialog id that is
2578 * unexpected.
2579 */
2580 private IllegalArgumentException missingDialog(int id) {
2581 return new IllegalArgumentException("no dialog with id " + id + " was ever "
2582 + "shown via Activity#showDialog");
2583 }
2584
2585 /**
2586 * Removes any internal references to a dialog managed by this Activity.
2587 * If the dialog is showing, it will dismiss it as part of the clean up.
2588 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002589 * <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 -08002590 * want to avoid the overhead of saving and restoring it in the future.
2591 *
2592 * @param id The id of the managed dialog.
2593 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002594 * @see #onCreateDialog(int, Bundle)
2595 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 * @see #showDialog(int)
2597 * @see #dismissDialog(int)
2598 */
2599 public final void removeDialog(int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (mManagedDialogs == null) {
2601 return;
2602 }
2603
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002604 final ManagedDialog md = mManagedDialogs.get(id);
2605 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 return;
2607 }
2608
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002609 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 mManagedDialogs.remove(id);
2611 }
2612
2613 /**
2614 * This hook is called when the user signals the desire to start a search.
2615 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002616 * <p>You can use this function as a simple way to launch the search UI, in response to a
2617 * menu item, search button, or other widgets within your activity. Unless overidden,
2618 * calling this function is the same as calling
2619 * {@link #startSearch startSearch(null, false, null, false)}, which launches
2620 * search for the current activity as specified in its manifest, see {@link SearchManager}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 *
2622 * <p>You can override this function to force global search, e.g. in response to a dedicated
2623 * search key, or to block search entirely (by simply returning false).
2624 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01002625 * @return Returns {@code true} if search launched, and {@code false} if activity blocks it.
2626 * The default implementation always returns {@code true}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 *
2628 * @see android.app.SearchManager
2629 */
2630 public boolean onSearchRequested() {
2631 startSearch(null, false, null, false);
2632 return true;
2633 }
2634
2635 /**
2636 * This hook is called to launch the search UI.
2637 *
2638 * <p>It is typically called from onSearchRequested(), either directly from
2639 * Activity.onSearchRequested() or from an overridden version in any given
2640 * Activity. If your goal is simply to activate search, it is preferred to call
2641 * onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal
2642 * is to inject specific data such as context data, it is preferred to <i>override</i>
2643 * onSearchRequested(), so that any callers to it will benefit from the override.
2644 *
2645 * @param initialQuery Any non-null non-empty string will be inserted as
2646 * pre-entered text in the search query box.
2647 * @param selectInitialQuery If true, the intial query will be preselected, which means that
2648 * any further typing will replace it. This is useful for cases where an entire pre-formed
2649 * query is being inserted. If false, the selection point will be placed at the end of the
2650 * inserted query. This is useful when the inserted query is text that the user entered,
2651 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
2652 * if initialQuery is a non-empty string.</i>
2653 * @param appSearchData An application can insert application-specific
2654 * context here, in order to improve quality or specificity of its own
2655 * searches. This data will be returned with SEARCH intent(s). Null if
2656 * no extra data is required.
2657 * @param globalSearch If false, this will only launch the search that has been specifically
2658 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07002659 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 * If true, this will always launch a platform-global (e.g. web-based) search instead.
2661 *
2662 * @see android.app.SearchManager
2663 * @see #onSearchRequested
2664 */
2665 public void startSearch(String initialQuery, boolean selectInitialQuery,
2666 Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002667 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01002668 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 appSearchData, globalSearch);
2670 }
2671
2672 /**
krosaend2d60142009-08-17 08:56:48 -07002673 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
2674 * the search dialog. Made available for testing purposes.
2675 *
2676 * @param query The query to trigger. If empty, the request will be ignored.
2677 * @param appSearchData An application can insert application-specific
2678 * context here, in order to improve quality or specificity of its own
2679 * searches. This data will be returned with SEARCH intent(s). Null if
2680 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07002681 */
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002682 public void triggerSearch(String query, Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07002683 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01002684 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07002685 }
2686
2687 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 * Request that key events come to this activity. Use this if your
2689 * activity has no views with focus, but the activity still wants
2690 * a chance to process key events.
2691 *
2692 * @see android.view.Window#takeKeyEvents
2693 */
2694 public void takeKeyEvents(boolean get) {
2695 getWindow().takeKeyEvents(get);
2696 }
2697
2698 /**
2699 * Enable extended window features. This is a convenience for calling
2700 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
2701 *
2702 * @param featureId The desired feature as defined in
2703 * {@link android.view.Window}.
2704 * @return Returns true if the requested feature is supported and now
2705 * enabled.
2706 *
2707 * @see android.view.Window#requestFeature
2708 */
2709 public final boolean requestWindowFeature(int featureId) {
2710 return getWindow().requestFeature(featureId);
2711 }
2712
2713 /**
2714 * Convenience for calling
2715 * {@link android.view.Window#setFeatureDrawableResource}.
2716 */
2717 public final void setFeatureDrawableResource(int featureId, int resId) {
2718 getWindow().setFeatureDrawableResource(featureId, resId);
2719 }
2720
2721 /**
2722 * Convenience for calling
2723 * {@link android.view.Window#setFeatureDrawableUri}.
2724 */
2725 public final void setFeatureDrawableUri(int featureId, Uri uri) {
2726 getWindow().setFeatureDrawableUri(featureId, uri);
2727 }
2728
2729 /**
2730 * Convenience for calling
2731 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
2732 */
2733 public final void setFeatureDrawable(int featureId, Drawable drawable) {
2734 getWindow().setFeatureDrawable(featureId, drawable);
2735 }
2736
2737 /**
2738 * Convenience for calling
2739 * {@link android.view.Window#setFeatureDrawableAlpha}.
2740 */
2741 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
2742 getWindow().setFeatureDrawableAlpha(featureId, alpha);
2743 }
2744
2745 /**
2746 * Convenience for calling
2747 * {@link android.view.Window#getLayoutInflater}.
2748 */
2749 public LayoutInflater getLayoutInflater() {
2750 return getWindow().getLayoutInflater();
2751 }
2752
2753 /**
2754 * Returns a {@link MenuInflater} with this context.
2755 */
2756 public MenuInflater getMenuInflater() {
2757 return new MenuInflater(this);
2758 }
2759
2760 @Override
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002761 protected void onApplyThemeResource(Resources.Theme theme, int resid,
2762 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 if (mParent == null) {
2764 super.onApplyThemeResource(theme, resid, first);
2765 } else {
2766 try {
2767 theme.setTo(mParent.getTheme());
2768 } catch (Exception e) {
2769 // Empty
2770 }
2771 theme.applyStyle(resid, false);
2772 }
2773 }
2774
2775 /**
2776 * Launch an activity for which you would like a result when it finished.
2777 * When this activity exits, your
2778 * onActivityResult() method will be called with the given requestCode.
2779 * Using a negative requestCode is the same as calling
2780 * {@link #startActivity} (the activity is not launched as a sub-activity).
2781 *
2782 * <p>Note that this method should only be used with Intent protocols
2783 * that are defined to return a result. In other protocols (such as
2784 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
2785 * not get the result when you expect. For example, if the activity you
2786 * are launching uses the singleTask launch mode, it will not run in your
2787 * task and thus you will immediately receive a cancel result.
2788 *
2789 * <p>As a special case, if you call startActivityForResult() with a requestCode
2790 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
2791 * activity, then your window will not be displayed until a result is
2792 * returned back from the started activity. This is to avoid visible
2793 * flickering when redirecting to another activity.
2794 *
2795 * <p>This method throws {@link android.content.ActivityNotFoundException}
2796 * if there was no Activity found to run the given Intent.
2797 *
2798 * @param intent The intent to start.
2799 * @param requestCode If >= 0, this code will be returned in
2800 * onActivityResult() when the activity exits.
2801 *
2802 * @throws android.content.ActivityNotFoundException
2803 *
2804 * @see #startActivity
2805 */
2806 public void startActivityForResult(Intent intent, int requestCode) {
2807 if (mParent == null) {
2808 Instrumentation.ActivityResult ar =
2809 mInstrumentation.execStartActivity(
2810 this, mMainThread.getApplicationThread(), mToken, this,
2811 intent, requestCode);
2812 if (ar != null) {
2813 mMainThread.sendActivityResult(
2814 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
2815 ar.getResultData());
2816 }
2817 if (requestCode >= 0) {
2818 // If this start is requesting a result, we can avoid making
2819 // the activity visible until the result is received. Setting
2820 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2821 // activity hidden during this time, to avoid flickering.
2822 // This can only be done when a result is requested because
2823 // that guarantees we will get information back when the
2824 // activity is finished, no matter what happens to it.
2825 mStartedActivity = true;
2826 }
2827 } else {
2828 mParent.startActivityFromChild(this, intent, requestCode);
2829 }
2830 }
2831
2832 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002833 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002834 * to use a IntentSender to describe the activity to be started. If
2835 * the IntentSender is for an activity, that activity will be started
2836 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
2837 * here; otherwise, its associated action will be executed (such as
2838 * sending a broadcast) as if you had called
2839 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002840 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002841 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002842 * @param requestCode If >= 0, this code will be returned in
2843 * onActivityResult() when the activity exits.
2844 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002845 * intent parameter to {@link IntentSender#sendIntent}.
2846 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002847 * would like to change.
2848 * @param flagsValues Desired values for any bits set in
2849 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002850 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002851 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002852 public void startIntentSenderForResult(IntentSender intent, int requestCode,
2853 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2854 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002855 if (mParent == null) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002856 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002857 flagsMask, flagsValues, this);
2858 } else {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002859 mParent.startIntentSenderFromChild(this, intent, requestCode,
2860 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002861 }
2862 }
2863
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002864 private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002865 Intent fillInIntent, int flagsMask, int flagsValues, Activity activity)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002866 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002867 try {
2868 String resolvedType = null;
2869 if (fillInIntent != null) {
2870 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
2871 }
2872 int result = ActivityManagerNative.getDefault()
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002873 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002874 fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
2875 requestCode, flagsMask, flagsValues);
2876 if (result == IActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002877 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002878 }
2879 Instrumentation.checkStartActivityResult(result, null);
2880 } catch (RemoteException e) {
2881 }
2882 if (requestCode >= 0) {
2883 // If this start is requesting a result, we can avoid making
2884 // the activity visible until the result is received. Setting
2885 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2886 // activity hidden during this time, to avoid flickering.
2887 // This can only be done when a result is requested because
2888 // that guarantees we will get information back when the
2889 // activity is finished, no matter what happens to it.
2890 mStartedActivity = true;
2891 }
2892 }
2893
2894 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 * Launch a new activity. You will not receive any information about when
2896 * the activity exits. This implementation overrides the base version,
2897 * providing information about
2898 * the activity performing the launch. Because of this additional
2899 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
2900 * required; if not specified, the new activity will be added to the
2901 * task of the caller.
2902 *
2903 * <p>This method throws {@link android.content.ActivityNotFoundException}
2904 * if there was no Activity found to run the given Intent.
2905 *
2906 * @param intent The intent to start.
2907 *
2908 * @throws android.content.ActivityNotFoundException
2909 *
2910 * @see #startActivityForResult
2911 */
2912 @Override
2913 public void startActivity(Intent intent) {
2914 startActivityForResult(intent, -1);
2915 }
2916
2917 /**
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002918 * Like {@link #startActivity(Intent)}, but taking a IntentSender
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002919 * to start; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07002920 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002921 * for more information.
2922 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002923 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002924 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002925 * intent parameter to {@link IntentSender#sendIntent}.
2926 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002927 * would like to change.
2928 * @param flagsValues Desired values for any bits set in
2929 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002930 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002931 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002932 public void startIntentSender(IntentSender intent,
2933 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
2934 throws IntentSender.SendIntentException {
2935 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
2936 flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002937 }
2938
2939 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 * A special variation to launch an activity only if a new activity
2941 * instance is needed to handle the given Intent. In other words, this is
2942 * just like {@link #startActivityForResult(Intent, int)} except: if you are
2943 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
2944 * singleTask or singleTop
2945 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
2946 * and the activity
2947 * that handles <var>intent</var> is the same as your currently running
2948 * activity, then a new instance is not needed. In this case, instead of
2949 * the normal behavior of calling {@link #onNewIntent} this function will
2950 * return and you can handle the Intent yourself.
2951 *
2952 * <p>This function can only be called from a top-level activity; if it is
2953 * called from a child activity, a runtime exception will be thrown.
2954 *
2955 * @param intent The intent to start.
2956 * @param requestCode If >= 0, this code will be returned in
2957 * onActivityResult() when the activity exits, as described in
2958 * {@link #startActivityForResult}.
2959 *
2960 * @return If a new activity was launched then true is returned; otherwise
2961 * false is returned and you must handle the Intent yourself.
2962 *
2963 * @see #startActivity
2964 * @see #startActivityForResult
2965 */
2966 public boolean startActivityIfNeeded(Intent intent, int requestCode) {
2967 if (mParent == null) {
2968 int result = IActivityManager.START_RETURN_INTENT_TO_CALLER;
2969 try {
2970 result = ActivityManagerNative.getDefault()
2971 .startActivity(mMainThread.getApplicationThread(),
2972 intent, intent.resolveTypeIfNeeded(
2973 getContentResolver()),
2974 null, 0,
2975 mToken, mEmbeddedID, requestCode, true, false);
2976 } catch (RemoteException e) {
2977 // Empty
2978 }
2979
2980 Instrumentation.checkStartActivityResult(result, intent);
2981
2982 if (requestCode >= 0) {
2983 // If this start is requesting a result, we can avoid making
2984 // the activity visible until the result is received. Setting
2985 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
2986 // activity hidden during this time, to avoid flickering.
2987 // This can only be done when a result is requested because
2988 // that guarantees we will get information back when the
2989 // activity is finished, no matter what happens to it.
2990 mStartedActivity = true;
2991 }
2992 return result != IActivityManager.START_RETURN_INTENT_TO_CALLER;
2993 }
2994
2995 throw new UnsupportedOperationException(
2996 "startActivityIfNeeded can only be called from a top-level activity");
2997 }
2998
2999 /**
3000 * Special version of starting an activity, for use when you are replacing
3001 * other activity components. You can use this to hand the Intent off
3002 * to the next Activity that can handle it. You typically call this in
3003 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
3004 *
3005 * @param intent The intent to dispatch to the next activity. For
3006 * correct behavior, this must be the same as the Intent that started
3007 * your own activity; the only changes you can make are to the extras
3008 * inside of it.
3009 *
3010 * @return Returns a boolean indicating whether there was another Activity
3011 * to start: true if there was a next activity to start, false if there
3012 * wasn't. In general, if true is returned you will then want to call
3013 * finish() on yourself.
3014 */
3015 public boolean startNextMatchingActivity(Intent intent) {
3016 if (mParent == null) {
3017 try {
3018 return ActivityManagerNative.getDefault()
3019 .startNextMatchingActivity(mToken, intent);
3020 } catch (RemoteException e) {
3021 // Empty
3022 }
3023 return false;
3024 }
3025
3026 throw new UnsupportedOperationException(
3027 "startNextMatchingActivity can only be called from a top-level activity");
3028 }
3029
3030 /**
3031 * This is called when a child activity of this one calls its
3032 * {@link #startActivity} or {@link #startActivityForResult} method.
3033 *
3034 * <p>This method throws {@link android.content.ActivityNotFoundException}
3035 * if there was no Activity found to run the given Intent.
3036 *
3037 * @param child The activity making the call.
3038 * @param intent The intent to start.
3039 * @param requestCode Reply request code. < 0 if reply is not requested.
3040 *
3041 * @throws android.content.ActivityNotFoundException
3042 *
3043 * @see #startActivity
3044 * @see #startActivityForResult
3045 */
3046 public void startActivityFromChild(Activity child, Intent intent,
3047 int requestCode) {
3048 Instrumentation.ActivityResult ar =
3049 mInstrumentation.execStartActivity(
3050 this, mMainThread.getApplicationThread(), mToken, child,
3051 intent, requestCode);
3052 if (ar != null) {
3053 mMainThread.sendActivityResult(
3054 mToken, child.mEmbeddedID, requestCode,
3055 ar.getResultCode(), ar.getResultData());
3056 }
3057 }
3058
3059 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003060 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003061 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07003062 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003063 * for more information.
3064 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07003065 public void startIntentSenderFromChild(Activity child, IntentSender intent,
3066 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
3067 int extraFlags)
3068 throws IntentSender.SendIntentException {
3069 startIntentSenderForResultInner(intent, requestCode, fillInIntent,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07003070 flagsMask, flagsValues, child);
3071 }
3072
3073 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003074 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
3075 * or {@link #finish} to specify an explicit transition animation to
3076 * perform next.
3077 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003078 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003079 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07003080 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07003081 */
3082 public void overridePendingTransition(int enterAnim, int exitAnim) {
3083 try {
3084 ActivityManagerNative.getDefault().overridePendingTransition(
3085 mToken, getPackageName(), enterAnim, exitAnim);
3086 } catch (RemoteException e) {
3087 }
3088 }
3089
3090 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 * Call this to set the result that your activity will return to its
3092 * caller.
3093 *
3094 * @param resultCode The result code to propagate back to the originating
3095 * activity, often RESULT_CANCELED or RESULT_OK
3096 *
3097 * @see #RESULT_CANCELED
3098 * @see #RESULT_OK
3099 * @see #RESULT_FIRST_USER
3100 * @see #setResult(int, Intent)
3101 */
3102 public final void setResult(int resultCode) {
3103 synchronized (this) {
3104 mResultCode = resultCode;
3105 mResultData = null;
3106 }
3107 }
3108
3109 /**
3110 * Call this to set the result that your activity will return to its
3111 * caller.
3112 *
3113 * @param resultCode The result code to propagate back to the originating
3114 * activity, often RESULT_CANCELED or RESULT_OK
3115 * @param data The data to propagate back to the originating activity.
3116 *
3117 * @see #RESULT_CANCELED
3118 * @see #RESULT_OK
3119 * @see #RESULT_FIRST_USER
3120 * @see #setResult(int)
3121 */
3122 public final void setResult(int resultCode, Intent data) {
3123 synchronized (this) {
3124 mResultCode = resultCode;
3125 mResultData = data;
3126 }
3127 }
3128
3129 /**
3130 * Return the name of the package that invoked this activity. This is who
3131 * the data in {@link #setResult setResult()} will be sent to. You can
3132 * use this information to validate that the recipient is allowed to
3133 * receive the data.
3134 *
3135 * <p>Note: if the calling activity is not expecting a result (that is it
3136 * did not use the {@link #startActivityForResult}
3137 * form that includes a request code), then the calling package will be
3138 * null.
3139 *
3140 * @return The package of the activity that will receive your
3141 * reply, or null if none.
3142 */
3143 public String getCallingPackage() {
3144 try {
3145 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
3146 } catch (RemoteException e) {
3147 return null;
3148 }
3149 }
3150
3151 /**
3152 * Return the name of the activity that invoked this activity. This is
3153 * who the data in {@link #setResult setResult()} will be sent to. You
3154 * can use this information to validate that the recipient is allowed to
3155 * receive the data.
3156 *
3157 * <p>Note: if the calling activity is not expecting a result (that is it
3158 * did not use the {@link #startActivityForResult}
3159 * form that includes a request code), then the calling package will be
3160 * null.
3161 *
3162 * @return String The full name of the activity that will receive your
3163 * reply, or null if none.
3164 */
3165 public ComponentName getCallingActivity() {
3166 try {
3167 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
3168 } catch (RemoteException e) {
3169 return null;
3170 }
3171 }
3172
3173 /**
3174 * Control whether this activity's main window is visible. This is intended
3175 * only for the special case of an activity that is not going to show a
3176 * UI itself, but can't just finish prior to onResume() because it needs
3177 * to wait for a service binding or such. Setting this to false allows
3178 * you to prevent your UI from being shown during that time.
3179 *
3180 * <p>The default value for this is taken from the
3181 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
3182 */
3183 public void setVisible(boolean visible) {
3184 if (mVisibleFromClient != visible) {
3185 mVisibleFromClient = visible;
3186 if (mVisibleFromServer) {
3187 if (visible) makeVisible();
3188 else mDecor.setVisibility(View.INVISIBLE);
3189 }
3190 }
3191 }
3192
3193 void makeVisible() {
3194 if (!mWindowAdded) {
3195 ViewManager wm = getWindowManager();
3196 wm.addView(mDecor, getWindow().getAttributes());
3197 mWindowAdded = true;
3198 }
3199 mDecor.setVisibility(View.VISIBLE);
3200 }
3201
3202 /**
3203 * Check to see whether this activity is in the process of finishing,
3204 * either because you called {@link #finish} on it or someone else
3205 * has requested that it finished. This is often used in
3206 * {@link #onPause} to determine whether the activity is simply pausing or
3207 * completely finishing.
3208 *
3209 * @return If the activity is finishing, returns true; else returns false.
3210 *
3211 * @see #finish
3212 */
3213 public boolean isFinishing() {
3214 return mFinished;
3215 }
3216
3217 /**
3218 * Call this when your activity is done and should be closed. The
3219 * ActivityResult is propagated back to whoever launched you via
3220 * onActivityResult().
3221 */
3222 public void finish() {
3223 if (mParent == null) {
3224 int resultCode;
3225 Intent resultData;
3226 synchronized (this) {
3227 resultCode = mResultCode;
3228 resultData = mResultData;
3229 }
3230 if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
3231 try {
3232 if (ActivityManagerNative.getDefault()
3233 .finishActivity(mToken, resultCode, resultData)) {
3234 mFinished = true;
3235 }
3236 } catch (RemoteException e) {
3237 // Empty
3238 }
3239 } else {
3240 mParent.finishFromChild(this);
3241 }
3242 }
3243
3244 /**
3245 * This is called when a child activity of this one calls its
3246 * {@link #finish} method. The default implementation simply calls
3247 * finish() on this activity (the parent), finishing the entire group.
3248 *
3249 * @param child The activity making the call.
3250 *
3251 * @see #finish
3252 */
3253 public void finishFromChild(Activity child) {
3254 finish();
3255 }
3256
3257 /**
3258 * Force finish another activity that you had previously started with
3259 * {@link #startActivityForResult}.
3260 *
3261 * @param requestCode The request code of the activity that you had
3262 * given to startActivityForResult(). If there are multiple
3263 * activities started with this request code, they
3264 * will all be finished.
3265 */
3266 public void finishActivity(int requestCode) {
3267 if (mParent == null) {
3268 try {
3269 ActivityManagerNative.getDefault()
3270 .finishSubActivity(mToken, mEmbeddedID, requestCode);
3271 } catch (RemoteException e) {
3272 // Empty
3273 }
3274 } else {
3275 mParent.finishActivityFromChild(this, requestCode);
3276 }
3277 }
3278
3279 /**
3280 * This is called when a child activity of this one calls its
3281 * finishActivity().
3282 *
3283 * @param child The activity making the call.
3284 * @param requestCode Request code that had been used to start the
3285 * activity.
3286 */
3287 public void finishActivityFromChild(Activity child, int requestCode) {
3288 try {
3289 ActivityManagerNative.getDefault()
3290 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
3291 } catch (RemoteException e) {
3292 // Empty
3293 }
3294 }
3295
3296 /**
3297 * Called when an activity you launched exits, giving you the requestCode
3298 * you started it with, the resultCode it returned, and any additional
3299 * data from it. The <var>resultCode</var> will be
3300 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
3301 * didn't return any result, or crashed during its operation.
3302 *
3303 * <p>You will receive this call immediately before onResume() when your
3304 * activity is re-starting.
3305 *
3306 * @param requestCode The integer request code originally supplied to
3307 * startActivityForResult(), allowing you to identify who this
3308 * result came from.
3309 * @param resultCode The integer result code returned by the child activity
3310 * through its setResult().
3311 * @param data An Intent, which can return result data to the caller
3312 * (various data can be attached to Intent "extras").
3313 *
3314 * @see #startActivityForResult
3315 * @see #createPendingResult
3316 * @see #setResult(int)
3317 */
3318 protected void onActivityResult(int requestCode, int resultCode,
3319 Intent data) {
3320 }
3321
3322 /**
3323 * Create a new PendingIntent object which you can hand to others
3324 * for them to use to send result data back to your
3325 * {@link #onActivityResult} callback. The created object will be either
3326 * one-shot (becoming invalid after a result is sent back) or multiple
3327 * (allowing any number of results to be sent through it).
3328 *
3329 * @param requestCode Private request code for the sender that will be
3330 * associated with the result data when it is returned. The sender can not
3331 * modify this value, allowing you to identify incoming results.
3332 * @param data Default data to supply in the result, which may be modified
3333 * by the sender.
3334 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
3335 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
3336 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
3337 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
3338 * or any of the flags as supported by
3339 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
3340 * of the intent that can be supplied when the actual send happens.
3341 *
3342 * @return Returns an existing or new PendingIntent matching the given
3343 * parameters. May return null only if
3344 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
3345 * supplied.
3346 *
3347 * @see PendingIntent
3348 */
3349 public PendingIntent createPendingResult(int requestCode, Intent data,
3350 int flags) {
3351 String packageName = getPackageName();
3352 try {
3353 IIntentSender target =
3354 ActivityManagerNative.getDefault().getIntentSender(
3355 IActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
3356 mParent == null ? mToken : mParent.mToken,
3357 mEmbeddedID, requestCode, data, null, flags);
3358 return target != null ? new PendingIntent(target) : null;
3359 } catch (RemoteException e) {
3360 // Empty
3361 }
3362 return null;
3363 }
3364
3365 /**
3366 * Change the desired orientation of this activity. If the activity
3367 * is currently in the foreground or otherwise impacting the screen
3368 * orientation, the screen will immediately be changed (possibly causing
3369 * the activity to be restarted). Otherwise, this will be used the next
3370 * time the activity is visible.
3371 *
3372 * @param requestedOrientation An orientation constant as used in
3373 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3374 */
3375 public void setRequestedOrientation(int requestedOrientation) {
3376 if (mParent == null) {
3377 try {
3378 ActivityManagerNative.getDefault().setRequestedOrientation(
3379 mToken, requestedOrientation);
3380 } catch (RemoteException e) {
3381 // Empty
3382 }
3383 } else {
3384 mParent.setRequestedOrientation(requestedOrientation);
3385 }
3386 }
3387
3388 /**
3389 * Return the current requested orientation of the activity. This will
3390 * either be the orientation requested in its component's manifest, or
3391 * the last requested orientation given to
3392 * {@link #setRequestedOrientation(int)}.
3393 *
3394 * @return Returns an orientation constant as used in
3395 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
3396 */
3397 public int getRequestedOrientation() {
3398 if (mParent == null) {
3399 try {
3400 return ActivityManagerNative.getDefault()
3401 .getRequestedOrientation(mToken);
3402 } catch (RemoteException e) {
3403 // Empty
3404 }
3405 } else {
3406 return mParent.getRequestedOrientation();
3407 }
3408 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3409 }
3410
3411 /**
3412 * Return the identifier of the task this activity is in. This identifier
3413 * will remain the same for the lifetime of the activity.
3414 *
3415 * @return Task identifier, an opaque integer.
3416 */
3417 public int getTaskId() {
3418 try {
3419 return ActivityManagerNative.getDefault()
3420 .getTaskForActivity(mToken, false);
3421 } catch (RemoteException e) {
3422 return -1;
3423 }
3424 }
3425
3426 /**
3427 * Return whether this activity is the root of a task. The root is the
3428 * first activity in a task.
3429 *
3430 * @return True if this is the root activity, else false.
3431 */
3432 public boolean isTaskRoot() {
3433 try {
3434 return ActivityManagerNative.getDefault()
3435 .getTaskForActivity(mToken, true) >= 0;
3436 } catch (RemoteException e) {
3437 return false;
3438 }
3439 }
3440
3441 /**
3442 * Move the task containing this activity to the back of the activity
3443 * stack. The activity's order within the task is unchanged.
3444 *
3445 * @param nonRoot If false then this only works if the activity is the root
3446 * of a task; if true it will work for any activity in
3447 * a task.
3448 *
3449 * @return If the task was moved (or it was already at the
3450 * back) true is returned, else false.
3451 */
3452 public boolean moveTaskToBack(boolean nonRoot) {
3453 try {
3454 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
3455 mToken, nonRoot);
3456 } catch (RemoteException e) {
3457 // Empty
3458 }
3459 return false;
3460 }
3461
3462 /**
3463 * Returns class name for this activity with the package prefix removed.
3464 * This is the default name used to read and write settings.
3465 *
3466 * @return The local class name.
3467 */
3468 public String getLocalClassName() {
3469 final String pkg = getPackageName();
3470 final String cls = mComponent.getClassName();
3471 int packageLen = pkg.length();
3472 if (!cls.startsWith(pkg) || cls.length() <= packageLen
3473 || cls.charAt(packageLen) != '.') {
3474 return cls;
3475 }
3476 return cls.substring(packageLen+1);
3477 }
3478
3479 /**
3480 * Returns complete component name of this activity.
3481 *
3482 * @return Returns the complete component name for this activity
3483 */
3484 public ComponentName getComponentName()
3485 {
3486 return mComponent;
3487 }
3488
3489 /**
3490 * Retrieve a {@link SharedPreferences} object for accessing preferences
3491 * that are private to this activity. This simply calls the underlying
3492 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
3493 * class name as the preferences name.
3494 *
3495 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
3496 * operation, {@link #MODE_WORLD_READABLE} and
3497 * {@link #MODE_WORLD_WRITEABLE} to control permissions.
3498 *
3499 * @return Returns the single SharedPreferences instance that can be used
3500 * to retrieve and modify the preference values.
3501 */
3502 public SharedPreferences getPreferences(int mode) {
3503 return getSharedPreferences(getLocalClassName(), mode);
3504 }
3505
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003506 private void ensureSearchManager() {
3507 if (mSearchManager != null) {
3508 return;
3509 }
3510
Amith Yamasanie9ce3f02010-01-25 09:15:50 -08003511 mSearchManager = new SearchManager(this, null);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003512 }
3513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 @Override
3515 public Object getSystemService(String name) {
3516 if (getBaseContext() == null) {
3517 throw new IllegalStateException(
3518 "System services not available to Activities before onCreate()");
3519 }
3520
3521 if (WINDOW_SERVICE.equals(name)) {
3522 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003523 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003524 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01003525 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 }
3527 return super.getSystemService(name);
3528 }
3529
3530 /**
3531 * Change the title associated with this activity. If this is a
3532 * top-level activity, the title for its window will change. If it
3533 * is an embedded activity, the parent can do whatever it wants
3534 * with it.
3535 */
3536 public void setTitle(CharSequence title) {
3537 mTitle = title;
3538 onTitleChanged(title, mTitleColor);
3539
3540 if (mParent != null) {
3541 mParent.onChildTitleChanged(this, title);
3542 }
3543 }
3544
3545 /**
3546 * Change the title associated with this activity. If this is a
3547 * top-level activity, the title for its window will change. If it
3548 * is an embedded activity, the parent can do whatever it wants
3549 * with it.
3550 */
3551 public void setTitle(int titleId) {
3552 setTitle(getText(titleId));
3553 }
3554
3555 public void setTitleColor(int textColor) {
3556 mTitleColor = textColor;
3557 onTitleChanged(mTitle, textColor);
3558 }
3559
3560 public final CharSequence getTitle() {
3561 return mTitle;
3562 }
3563
3564 public final int getTitleColor() {
3565 return mTitleColor;
3566 }
3567
3568 protected void onTitleChanged(CharSequence title, int color) {
3569 if (mTitleReady) {
3570 final Window win = getWindow();
3571 if (win != null) {
3572 win.setTitle(title);
3573 if (color != 0) {
3574 win.setTitleColor(color);
3575 }
3576 }
3577 }
3578 }
3579
3580 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
3581 }
3582
3583 /**
3584 * Sets the visibility of the progress bar in the title.
3585 * <p>
3586 * In order for the progress bar to be shown, the feature must be requested
3587 * via {@link #requestWindowFeature(int)}.
3588 *
3589 * @param visible Whether to show the progress bars in the title.
3590 */
3591 public final void setProgressBarVisibility(boolean visible) {
3592 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
3593 Window.PROGRESS_VISIBILITY_OFF);
3594 }
3595
3596 /**
3597 * Sets the visibility of the indeterminate progress bar in the title.
3598 * <p>
3599 * In order for the progress bar to be shown, the feature must be requested
3600 * via {@link #requestWindowFeature(int)}.
3601 *
3602 * @param visible Whether to show the progress bars in the title.
3603 */
3604 public final void setProgressBarIndeterminateVisibility(boolean visible) {
3605 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
3606 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
3607 }
3608
3609 /**
3610 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
3611 * is always indeterminate).
3612 * <p>
3613 * In order for the progress bar to be shown, the feature must be requested
3614 * via {@link #requestWindowFeature(int)}.
3615 *
3616 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
3617 */
3618 public final void setProgressBarIndeterminate(boolean indeterminate) {
3619 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3620 indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF);
3621 }
3622
3623 /**
3624 * Sets the progress for the progress bars in the title.
3625 * <p>
3626 * In order for the progress bar to be shown, the feature must be requested
3627 * via {@link #requestWindowFeature(int)}.
3628 *
3629 * @param progress The progress for the progress bar. Valid ranges are from
3630 * 0 to 10000 (both inclusive). If 10000 is given, the progress
3631 * bar will be completely filled and will fade out.
3632 */
3633 public final void setProgress(int progress) {
3634 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
3635 }
3636
3637 /**
3638 * Sets the secondary progress for the progress bar in the title. This
3639 * progress is drawn between the primary progress (set via
3640 * {@link #setProgress(int)} and the background. It can be ideal for media
3641 * scenarios such as showing the buffering progress while the default
3642 * progress shows the play progress.
3643 * <p>
3644 * In order for the progress bar to be shown, the feature must be requested
3645 * via {@link #requestWindowFeature(int)}.
3646 *
3647 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
3648 * 0 to 10000 (both inclusive).
3649 */
3650 public final void setSecondaryProgress(int secondaryProgress) {
3651 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3652 secondaryProgress + Window.PROGRESS_SECONDARY_START);
3653 }
3654
3655 /**
3656 * Suggests an audio stream whose volume should be changed by the hardware
3657 * volume controls.
3658 * <p>
3659 * The suggested audio stream will be tied to the window of this Activity.
3660 * If the Activity is switched, the stream set here is no longer the
3661 * suggested stream. The client does not need to save and restore the old
3662 * suggested stream value in onPause and onResume.
3663 *
3664 * @param streamType The type of the audio stream whose volume should be
3665 * changed by the hardware volume controls. It is not guaranteed that
3666 * the hardware volume controls will always change this stream's
3667 * volume (for example, if a call is in progress, its stream's volume
3668 * may be changed instead). To reset back to the default, use
3669 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
3670 */
3671 public final void setVolumeControlStream(int streamType) {
3672 getWindow().setVolumeControlStream(streamType);
3673 }
3674
3675 /**
3676 * Gets the suggested audio stream whose volume should be changed by the
3677 * harwdare volume controls.
3678 *
3679 * @return The suggested audio stream type whose volume should be changed by
3680 * the hardware volume controls.
3681 * @see #setVolumeControlStream(int)
3682 */
3683 public final int getVolumeControlStream() {
3684 return getWindow().getVolumeControlStream();
3685 }
3686
3687 /**
3688 * Runs the specified action on the UI thread. If the current thread is the UI
3689 * thread, then the action is executed immediately. If the current thread is
3690 * not the UI thread, the action is posted to the event queue of the UI thread.
3691 *
3692 * @param action the action to run on the UI thread
3693 */
3694 public final void runOnUiThread(Runnable action) {
3695 if (Thread.currentThread() != mUiThread) {
3696 mHandler.post(action);
3697 } else {
3698 action.run();
3699 }
3700 }
3701
3702 /**
3703 * Stub implementation of {@link android.view.LayoutInflater.Factory#onCreateView} used when
3704 * inflating with the LayoutInflater returned by {@link #getSystemService}. This
3705 * implementation simply returns null for all view names.
3706 *
3707 * @see android.view.LayoutInflater#createView
3708 * @see android.view.Window#getLayoutInflater
3709 */
3710 public View onCreateView(String name, Context context, AttributeSet attrs) {
3711 return null;
3712 }
3713
3714 // ------------------ Internal API ------------------
3715
3716 final void setParent(Activity parent) {
3717 mParent = parent;
3718 }
3719
3720 final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
3721 Application application, Intent intent, ActivityInfo info, CharSequence title,
3722 Activity parent, String id, Object lastNonConfigurationInstance,
3723 Configuration config) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003724 attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 lastNonConfigurationInstance, null, config);
3726 }
3727
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003728 final void attach(Context context, ActivityThread aThread,
3729 Instrumentation instr, IBinder token, int ident,
3730 Application application, Intent intent, ActivityInfo info,
3731 CharSequence title, Activity parent, String id,
3732 Object lastNonConfigurationInstance,
3733 HashMap<String,Object> lastNonConfigurationChildInstances,
3734 Configuration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 attachBaseContext(context);
3736
3737 mWindow = PolicyManager.makeNewWindow(this);
3738 mWindow.setCallback(this);
3739 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
3740 mWindow.setSoftInputMode(info.softInputMode);
3741 }
3742 mUiThread = Thread.currentThread();
3743
3744 mMainThread = aThread;
3745 mInstrumentation = instr;
3746 mToken = token;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003747 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 mApplication = application;
3749 mIntent = intent;
3750 mComponent = intent.getComponent();
3751 mActivityInfo = info;
3752 mTitle = title;
3753 mParent = parent;
3754 mEmbeddedID = id;
3755 mLastNonConfigurationInstance = lastNonConfigurationInstance;
3756 mLastNonConfigurationChildInstances = lastNonConfigurationChildInstances;
3757
3758 mWindow.setWindowManager(null, mToken, mComponent.flattenToString());
3759 if (mParent != null) {
3760 mWindow.setContainer(mParent.getWindow());
3761 }
3762 mWindowManager = mWindow.getWindowManager();
3763 mCurrentConfig = config;
3764 }
3765
3766 final IBinder getActivityToken() {
3767 return mParent != null ? mParent.getActivityToken() : mToken;
3768 }
3769
3770 final void performStart() {
3771 mCalled = false;
3772 mInstrumentation.callActivityOnStart(this);
3773 if (!mCalled) {
3774 throw new SuperNotCalledException(
3775 "Activity " + mComponent.toShortString() +
3776 " did not call through to super.onStart()");
3777 }
3778 }
3779
3780 final void performRestart() {
3781 final int N = mManagedCursors.size();
3782 for (int i=0; i<N; i++) {
3783 ManagedCursor mc = mManagedCursors.get(i);
3784 if (mc.mReleased || mc.mUpdated) {
3785 mc.mCursor.requery();
3786 mc.mReleased = false;
3787 mc.mUpdated = false;
3788 }
3789 }
3790
3791 if (mStopped) {
3792 mStopped = false;
3793 mCalled = false;
3794 mInstrumentation.callActivityOnRestart(this);
3795 if (!mCalled) {
3796 throw new SuperNotCalledException(
3797 "Activity " + mComponent.toShortString() +
3798 " did not call through to super.onRestart()");
3799 }
3800 performStart();
3801 }
3802 }
3803
3804 final void performResume() {
3805 performRestart();
3806
3807 mLastNonConfigurationInstance = null;
3808
3809 // First call onResume() -before- setting mResumed, so we don't
3810 // send out any status bar / menu notifications the client makes.
3811 mCalled = false;
3812 mInstrumentation.callActivityOnResume(this);
3813 if (!mCalled) {
3814 throw new SuperNotCalledException(
3815 "Activity " + mComponent.toShortString() +
3816 " did not call through to super.onResume()");
3817 }
3818
3819 // Now really resume, and install the current status bar and menu.
3820 mResumed = true;
3821 mCalled = false;
3822 onPostResume();
3823 if (!mCalled) {
3824 throw new SuperNotCalledException(
3825 "Activity " + mComponent.toShortString() +
3826 " did not call through to super.onPostResume()");
3827 }
3828 }
3829
3830 final void performPause() {
3831 onPause();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
3833
3834 final void performUserLeaving() {
3835 onUserInteraction();
3836 onUserLeaveHint();
3837 }
3838
3839 final void performStop() {
3840 if (!mStopped) {
3841 if (mWindow != null) {
3842 mWindow.closeAllPanels();
3843 }
3844
3845 mCalled = false;
3846 mInstrumentation.callActivityOnStop(this);
3847 if (!mCalled) {
3848 throw new SuperNotCalledException(
3849 "Activity " + mComponent.toShortString() +
3850 " did not call through to super.onStop()");
3851 }
3852
3853 final int N = mManagedCursors.size();
3854 for (int i=0; i<N; i++) {
3855 ManagedCursor mc = mManagedCursors.get(i);
3856 if (!mc.mReleased) {
3857 mc.mCursor.deactivate();
3858 mc.mReleased = true;
3859 }
3860 }
3861
3862 mStopped = true;
3863 }
3864 mResumed = false;
3865 }
3866
3867 final boolean isResumed() {
3868 return mResumed;
3869 }
3870
3871 void dispatchActivityResult(String who, int requestCode,
3872 int resultCode, Intent data) {
3873 if (Config.LOGV) Log.v(
3874 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
3875 + ", resCode=" + resultCode + ", data=" + data);
3876 if (who == null) {
3877 onActivityResult(requestCode, resultCode, data);
3878 }
3879 }
3880}