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