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