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