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