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