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