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