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