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