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