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