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