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