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