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