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