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