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