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