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