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