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