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