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