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