Activity.java revision 7b02468b34ed3501ef8707e71d8017a2df952329
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 static java.lang.Character.MIN_VALUE; 20 21import android.annotation.CallSuper; 22import android.annotation.DrawableRes; 23import android.annotation.IdRes; 24import android.annotation.IntDef; 25import android.annotation.LayoutRes; 26import android.annotation.MainThread; 27import android.annotation.NonNull; 28import android.annotation.Nullable; 29import android.annotation.RequiresPermission; 30import android.annotation.StyleRes; 31import android.annotation.SystemApi; 32import android.app.admin.DevicePolicyManager; 33import android.app.assist.AssistContent; 34import android.content.ComponentCallbacks2; 35import android.content.ComponentName; 36import android.content.ContentResolver; 37import android.content.Context; 38import android.content.CursorLoader; 39import android.content.IIntentSender; 40import android.content.Intent; 41import android.content.IntentSender; 42import android.content.SharedPreferences; 43import android.content.pm.ActivityInfo; 44import android.content.pm.ApplicationInfo; 45import android.content.pm.PackageManager; 46import android.content.pm.PackageManager.NameNotFoundException; 47import android.content.res.Configuration; 48import android.content.res.Resources; 49import android.content.res.TypedArray; 50import android.database.Cursor; 51import android.graphics.Bitmap; 52import android.graphics.Canvas; 53import android.graphics.Color; 54import android.graphics.drawable.Drawable; 55import android.hardware.input.InputManager; 56import android.media.AudioManager; 57import android.media.session.MediaController; 58import android.net.Uri; 59import android.os.Build; 60import android.os.Bundle; 61import android.os.Handler; 62import android.os.IBinder; 63import android.os.Looper; 64import android.os.Parcelable; 65import android.os.PersistableBundle; 66import android.os.RemoteException; 67import android.os.StrictMode; 68import android.os.SystemProperties; 69import android.os.UserHandle; 70import android.text.Selection; 71import android.text.SpannableStringBuilder; 72import android.text.TextUtils; 73import android.text.method.TextKeyListener; 74import android.transition.Scene; 75import android.transition.TransitionManager; 76import android.util.ArrayMap; 77import android.util.AttributeSet; 78import android.util.EventLog; 79import android.util.Log; 80import android.util.PrintWriterPrinter; 81import android.util.Slog; 82import android.util.SparseArray; 83import android.util.SuperNotCalledException; 84import android.view.ActionMode; 85import android.view.ContextMenu; 86import android.view.ContextMenu.ContextMenuInfo; 87import android.view.ContextThemeWrapper; 88import android.view.DragEvent; 89import android.view.DropPermissions; 90import android.view.InputDevice; 91import android.view.KeyCharacterMap; 92import android.view.KeyEvent; 93import android.view.KeyboardShortcutGroup; 94import android.view.KeyboardShortcutInfo; 95import android.view.LayoutInflater; 96import android.view.Menu; 97import android.view.MenuInflater; 98import android.view.MenuItem; 99import android.view.MotionEvent; 100import android.view.SearchEvent; 101import android.view.View; 102import android.view.View.OnCreateContextMenuListener; 103import android.view.ViewGroup; 104import android.view.ViewGroup.LayoutParams; 105import android.view.ViewManager; 106import android.view.ViewRootImpl; 107import android.view.Window; 108import android.view.Window.WindowControllerCallback; 109import android.view.WindowManager; 110import android.view.WindowManagerGlobal; 111import android.view.accessibility.AccessibilityEvent; 112import android.widget.AdapterView; 113import android.widget.Toast; 114import android.widget.Toolbar; 115 116import com.android.internal.app.IVoiceInteractor; 117import com.android.internal.app.ToolbarActionBar; 118import com.android.internal.app.WindowDecorActionBar; 119import com.android.internal.policy.PhoneWindow; 120 121import java.io.FileDescriptor; 122import java.io.PrintWriter; 123import java.lang.annotation.Retention; 124import java.lang.annotation.RetentionPolicy; 125import java.util.ArrayList; 126import java.util.HashMap; 127import java.util.List; 128 129/** 130 * An activity is a single, focused thing that the user can do. Almost all 131 * activities interact with the user, so the Activity class takes care of 132 * creating a window for you in which you can place your UI with 133 * {@link #setContentView}. While activities are often presented to the user 134 * as full-screen windows, they can also be used in other ways: as floating 135 * windows (via a theme with {@link android.R.attr#windowIsFloating} set) 136 * or embedded inside of another activity (using {@link ActivityGroup}). 137 * 138 * There are two methods almost all subclasses of Activity will implement: 139 * 140 * <ul> 141 * <li> {@link #onCreate} is where you initialize your activity. Most 142 * importantly, here you will usually call {@link #setContentView(int)} 143 * with a layout resource defining your UI, and using {@link #findViewById} 144 * to retrieve the widgets in that UI that you need to interact with 145 * programmatically. 146 * 147 * <li> {@link #onPause} is where you deal with the user leaving your 148 * activity. Most importantly, any changes made by the user should at this 149 * point be committed (usually to the 150 * {@link android.content.ContentProvider} holding the data). 151 * </ul> 152 * 153 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all 154 * activity classes must have a corresponding 155 * {@link android.R.styleable#AndroidManifestActivity <activity>} 156 * declaration in their package's <code>AndroidManifest.xml</code>.</p> 157 * 158 * <p>Topics covered here: 159 * <ol> 160 * <li><a href="#Fragments">Fragments</a> 161 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a> 162 * <li><a href="#ConfigurationChanges">Configuration Changes</a> 163 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a> 164 * <li><a href="#SavingPersistentState">Saving Persistent State</a> 165 * <li><a href="#Permissions">Permissions</a> 166 * <li><a href="#ProcessLifecycle">Process Lifecycle</a> 167 * </ol> 168 * 169 * <div class="special reference"> 170 * <h3>Developer Guides</h3> 171 * <p>The Activity class is an important part of an application's overall lifecycle, 172 * and the way activities are launched and put together is a fundamental 173 * part of the platform's application model. For a detailed perspective on the structure of an 174 * Android application and how activities behave, please read the 175 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and 176 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a> 177 * developer guides.</p> 178 * 179 * <p>You can also find a detailed discussion about how to create activities in the 180 * <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> 181 * developer guide.</p> 182 * </div> 183 * 184 * <a name="Fragments"></a> 185 * <h3>Fragments</h3> 186 * 187 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity 188 * implementations can make use of the {@link Fragment} class to better 189 * modularize their code, build more sophisticated user interfaces for larger 190 * screens, and help scale their application between small and large screens. 191 * 192 * <a name="ActivityLifecycle"></a> 193 * <h3>Activity Lifecycle</h3> 194 * 195 * <p>Activities in the system are managed as an <em>activity stack</em>. 196 * When a new activity is started, it is placed on the top of the stack 197 * and becomes the running activity -- the previous activity always remains 198 * below it in the stack, and will not come to the foreground again until 199 * the new activity exits.</p> 200 * 201 * <p>An activity has essentially four states:</p> 202 * <ul> 203 * <li> If an activity in the foreground of the screen (at the top of 204 * the stack), 205 * it is <em>active</em> or <em>running</em>. </li> 206 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized 207 * or transparent activity has focus on top of your activity), it 208 * is <em>paused</em>. A paused activity is completely alive (it 209 * maintains all state and member information and remains attached to 210 * the window manager), but can be killed by the system in extreme 211 * low memory situations. 212 * <li>If an activity is completely obscured by another activity, 213 * it is <em>stopped</em>. It still retains all state and member information, 214 * however, it is no longer visible to the user so its window is hidden 215 * and it will often be killed by the system when memory is needed 216 * elsewhere.</li> 217 * <li>If an activity is paused or stopped, the system can drop the activity 218 * from memory by either asking it to finish, or simply killing its 219 * process. When it is displayed again to the user, it must be 220 * completely restarted and restored to its previous state.</li> 221 * </ul> 222 * 223 * <p>The following diagram shows the important state paths of an Activity. 224 * The square rectangles represent callback methods you can implement to 225 * perform operations when the Activity moves between states. The colored 226 * ovals are major states the Activity can be in.</p> 227 * 228 * <p><img src="../../../images/activity_lifecycle.png" 229 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p> 230 * 231 * <p>There are three key loops you may be interested in monitoring within your 232 * activity: 233 * 234 * <ul> 235 * <li>The <b>entire lifetime</b> of an activity happens between the first call 236 * to {@link android.app.Activity#onCreate} through to a single final call 237 * to {@link android.app.Activity#onDestroy}. An activity will do all setup 238 * of "global" state in onCreate(), and release all remaining resources in 239 * onDestroy(). For example, if it has a thread running in the background 240 * to download data from the network, it may create that thread in onCreate() 241 * and then stop the thread in onDestroy(). 242 * 243 * <li>The <b>visible lifetime</b> of an activity happens between a call to 244 * {@link android.app.Activity#onStart} until a corresponding call to 245 * {@link android.app.Activity#onStop}. During this time the user can see the 246 * activity on-screen, though it may not be in the foreground and interacting 247 * with the user. Between these two methods you can maintain resources that 248 * are needed to show the activity to the user. For example, you can register 249 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes 250 * that impact your UI, and unregister it in onStop() when the user no 251 * longer sees what you are displaying. The onStart() and onStop() methods 252 * can be called multiple times, as the activity becomes visible and hidden 253 * to the user. 254 * 255 * <li>The <b>foreground lifetime</b> of an activity happens between a call to 256 * {@link android.app.Activity#onResume} until a corresponding call to 257 * {@link android.app.Activity#onPause}. During this time the activity is 258 * in front of all other activities and interacting with the user. An activity 259 * can frequently go between the resumed and paused states -- for example when 260 * the device goes to sleep, when an activity result is delivered, when a new 261 * intent is delivered -- so the code in these methods should be fairly 262 * lightweight. 263 * </ul> 264 * 265 * <p>The entire lifecycle of an activity is defined by the following 266 * Activity methods. All of these are hooks that you can override 267 * to do appropriate work when the activity changes state. All 268 * activities will implement {@link android.app.Activity#onCreate} 269 * to do their initial setup; many will also implement 270 * {@link android.app.Activity#onPause} to commit changes to data and 271 * otherwise prepare to stop interacting with the user. You should always 272 * call up to your superclass when implementing these methods.</p> 273 * 274 * </p> 275 * <pre class="prettyprint"> 276 * public class Activity extends ApplicationContext { 277 * protected void onCreate(Bundle savedInstanceState); 278 * 279 * protected void onStart(); 280 * 281 * protected void onRestart(); 282 * 283 * protected void onResume(); 284 * 285 * protected void onPause(); 286 * 287 * protected void onStop(); 288 * 289 * protected void onDestroy(); 290 * } 291 * </pre> 292 * 293 * <p>In general the movement through an activity's lifecycle looks like 294 * this:</p> 295 * 296 * <table border="2" width="85%" align="center" frame="hsides" rules="rows"> 297 * <colgroup align="left" span="3" /> 298 * <colgroup align="left" /> 299 * <colgroup align="center" /> 300 * <colgroup align="center" /> 301 * 302 * <thead> 303 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr> 304 * </thead> 305 * 306 * <tbody> 307 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</th> 308 * <td>Called when the activity is first created. 309 * This is where you should do all of your normal static set up: 310 * create views, bind data to lists, etc. This method also 311 * provides you with a Bundle containing the activity's previously 312 * frozen state, if there was one. 313 * <p>Always followed by <code>onStart()</code>.</td> 314 * <td align="center">No</td> 315 * <td align="center"><code>onStart()</code></td> 316 * </tr> 317 * 318 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td> 319 * <th colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</th> 320 * <td>Called after your activity has been stopped, prior to it being 321 * started again. 322 * <p>Always followed by <code>onStart()</code></td> 323 * <td align="center">No</td> 324 * <td align="center"><code>onStart()</code></td> 325 * </tr> 326 * 327 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</th> 328 * <td>Called when the activity is becoming visible to the user. 329 * <p>Followed by <code>onResume()</code> if the activity comes 330 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td> 331 * <td align="center">No</td> 332 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td> 333 * </tr> 334 * 335 * <tr><td rowspan="2" style="border-left: none;"> </td> 336 * <th align="left" border="0">{@link android.app.Activity#onResume onResume()}</th> 337 * <td>Called when the activity will start 338 * interacting with the user. At this point your activity is at 339 * the top of the activity stack, with user input going to it. 340 * <p>Always followed by <code>onPause()</code>.</td> 341 * <td align="center">No</td> 342 * <td align="center"><code>onPause()</code></td> 343 * </tr> 344 * 345 * <tr><th align="left" border="0">{@link android.app.Activity#onPause onPause()}</th> 346 * <td>Called when the system is about to start resuming a previous 347 * activity. This is typically used to commit unsaved changes to 348 * persistent data, stop animations and other things that may be consuming 349 * CPU, etc. Implementations of this method must be very quick because 350 * the next activity will not be resumed until this method returns. 351 * <p>Followed by either <code>onResume()</code> if the activity 352 * returns back to the front, or <code>onStop()</code> if it becomes 353 * invisible to the user.</td> 354 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td> 355 * <td align="center"><code>onResume()</code> or<br> 356 * <code>onStop()</code></td> 357 * </tr> 358 * 359 * <tr><th colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</th> 360 * <td>Called when the activity is no longer visible to the user, because 361 * another activity has been resumed and is covering this one. This 362 * may happen either because a new activity is being started, an existing 363 * one is being brought in front of this one, or this one is being 364 * destroyed. 365 * <p>Followed by either <code>onRestart()</code> if 366 * this activity is coming back to interact with the user, or 367 * <code>onDestroy()</code> if this activity is going away.</td> 368 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td> 369 * <td align="center"><code>onRestart()</code> or<br> 370 * <code>onDestroy()</code></td> 371 * </tr> 372 * 373 * <tr><th colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</th> 374 * <td>The final call you receive before your 375 * activity is destroyed. This can happen either because the 376 * activity is finishing (someone called {@link Activity#finish} on 377 * it, or because the system is temporarily destroying this 378 * instance of the activity to save space. You can distinguish 379 * between these two scenarios with the {@link 380 * Activity#isFinishing} method.</td> 381 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td> 382 * <td align="center"><em>nothing</em></td> 383 * </tr> 384 * </tbody> 385 * </table> 386 * 387 * <p>Note the "Killable" column in the above table -- for those methods that 388 * are marked as being killable, after that method returns the process hosting the 389 * activity may be killed by the system <em>at any time</em> without another line 390 * of its code being executed. Because of this, you should use the 391 * {@link #onPause} method to write any persistent data (such as user edits) 392 * to storage. In addition, the method 393 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity 394 * in such a background state, allowing you to save away any dynamic instance 395 * state in your activity into the given Bundle, to be later received in 396 * {@link #onCreate} if the activity needs to be re-created. 397 * See the <a href="#ProcessLifecycle">Process Lifecycle</a> 398 * section for more information on how the lifecycle of a process is tied 399 * to the activities it is hosting. Note that it is important to save 400 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState} 401 * because the latter is not part of the lifecycle callbacks, so will not 402 * be called in every situation as described in its documentation.</p> 403 * 404 * <p class="note">Be aware that these semantics will change slightly between 405 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB} 406 * vs. those targeting prior platforms. Starting with Honeycomb, an application 407 * is not in the killable state until its {@link #onStop} has returned. This 408 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be 409 * safely called after {@link #onPause()} and allows and application to safely 410 * wait until {@link #onStop()} to save persistent state.</p> 411 * 412 * <p>For those methods that are not marked as being killable, the activity's 413 * process will not be killed by the system starting from the time the method 414 * is called and continuing after it returns. Thus an activity is in the killable 415 * state, for example, between after <code>onPause()</code> to the start of 416 * <code>onResume()</code>.</p> 417 * 418 * <a name="ConfigurationChanges"></a> 419 * <h3>Configuration Changes</h3> 420 * 421 * <p>If the configuration of the device (as defined by the 422 * {@link Configuration Resources.Configuration} class) changes, 423 * then anything displaying a user interface will need to update to match that 424 * configuration. Because Activity is the primary mechanism for interacting 425 * with the user, it includes special support for handling configuration 426 * changes.</p> 427 * 428 * <p>Unless you specify otherwise, a configuration change (such as a change 429 * in screen orientation, language, input devices, etc) will cause your 430 * current activity to be <em>destroyed</em>, going through the normal activity 431 * lifecycle process of {@link #onPause}, 432 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity 433 * had been in the foreground or visible to the user, once {@link #onDestroy} is 434 * called in that instance then a new instance of the activity will be 435 * created, with whatever savedInstanceState the previous instance had generated 436 * from {@link #onSaveInstanceState}.</p> 437 * 438 * <p>This is done because any application resource, 439 * including layout files, can change based on any configuration value. Thus 440 * the only safe way to handle a configuration change is to re-retrieve all 441 * resources, including layouts, drawables, and strings. Because activities 442 * must already know how to save their state and re-create themselves from 443 * that state, this is a convenient way to have an activity restart itself 444 * with a new configuration.</p> 445 * 446 * <p>In some special cases, you may want to bypass restarting of your 447 * activity based on one or more types of configuration changes. This is 448 * done with the {@link android.R.attr#configChanges android:configChanges} 449 * attribute in its manifest. For any types of configuration changes you say 450 * that you handle there, you will receive a call to your current activity's 451 * {@link #onConfigurationChanged} method instead of being restarted. If 452 * a configuration change involves any that you do not handle, however, the 453 * activity will still be restarted and {@link #onConfigurationChanged} 454 * will not be called.</p> 455 * 456 * <a name="StartingActivities"></a> 457 * <h3>Starting Activities and Getting Results</h3> 458 * 459 * <p>The {@link android.app.Activity#startActivity} 460 * method is used to start a 461 * new activity, which will be placed at the top of the activity stack. It 462 * takes a single argument, an {@link android.content.Intent Intent}, 463 * which describes the activity 464 * to be executed.</p> 465 * 466 * <p>Sometimes you want to get a result back from an activity when it 467 * ends. For example, you may start an activity that lets the user pick 468 * a person in a list of contacts; when it ends, it returns the person 469 * that was selected. To do this, you call the 470 * {@link android.app.Activity#startActivityForResult(Intent, int)} 471 * version with a second integer parameter identifying the call. The result 472 * will come back through your {@link android.app.Activity#onActivityResult} 473 * method.</p> 474 * 475 * <p>When an activity exits, it can call 476 * {@link android.app.Activity#setResult(int)} 477 * to return data back to its parent. It must always supply a result code, 478 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any 479 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally 480 * return back an Intent containing any additional data it wants. All of this 481 * information appears back on the 482 * parent's <code>Activity.onActivityResult()</code>, along with the integer 483 * identifier it originally supplied.</p> 484 * 485 * <p>If a child activity fails for any reason (such as crashing), the parent 486 * activity will receive a result with the code RESULT_CANCELED.</p> 487 * 488 * <pre class="prettyprint"> 489 * public class MyActivity extends Activity { 490 * ... 491 * 492 * static final int PICK_CONTACT_REQUEST = 0; 493 * 494 * public boolean onKeyDown(int keyCode, KeyEvent event) { 495 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 496 * // When the user center presses, let them pick a contact. 497 * startActivityForResult( 498 * new Intent(Intent.ACTION_PICK, 499 * new Uri("content://contacts")), 500 * PICK_CONTACT_REQUEST); 501 * return true; 502 * } 503 * return false; 504 * } 505 * 506 * protected void onActivityResult(int requestCode, int resultCode, 507 * Intent data) { 508 * if (requestCode == PICK_CONTACT_REQUEST) { 509 * if (resultCode == RESULT_OK) { 510 * // A contact was picked. Here we will just display it 511 * // to the user. 512 * startActivity(new Intent(Intent.ACTION_VIEW, data)); 513 * } 514 * } 515 * } 516 * } 517 * </pre> 518 * 519 * <a name="SavingPersistentState"></a> 520 * <h3>Saving Persistent State</h3> 521 * 522 * <p>There are generally two kinds of persistent state than an activity 523 * will deal with: shared document-like data (typically stored in a SQLite 524 * database using a {@linkplain android.content.ContentProvider content provider}) 525 * and internal state such as user preferences.</p> 526 * 527 * <p>For content provider data, we suggest that activities use a 528 * "edit in place" user model. That is, any edits a user makes are effectively 529 * made immediately without requiring an additional confirmation step. 530 * Supporting this model is generally a simple matter of following two rules:</p> 531 * 532 * <ul> 533 * <li> <p>When creating a new document, the backing database entry or file for 534 * it is created immediately. For example, if the user chooses to write 535 * a new e-mail, a new entry for that e-mail is created as soon as they 536 * start entering data, so that if they go to any other activity after 537 * that point this e-mail will now appear in the list of drafts.</p> 538 * <li> <p>When an activity's <code>onPause()</code> method is called, it should 539 * commit to the backing content provider or file any changes the user 540 * has made. This ensures that those changes will be seen by any other 541 * activity that is about to run. You will probably want to commit 542 * your data even more aggressively at key times during your 543 * activity's lifecycle: for example before starting a new 544 * activity, before finishing your own activity, when the user 545 * switches between input fields, etc.</p> 546 * </ul> 547 * 548 * <p>This model is designed to prevent data loss when a user is navigating 549 * between activities, and allows the system to safely kill an activity (because 550 * system resources are needed somewhere else) at any time after it has been 551 * paused. Note this implies 552 * that the user pressing BACK from your activity does <em>not</em> 553 * mean "cancel" -- it means to leave the activity with its current contents 554 * saved away. Canceling edits in an activity must be provided through 555 * some other mechanism, such as an explicit "revert" or "undo" option.</p> 556 * 557 * <p>See the {@linkplain android.content.ContentProvider content package} for 558 * more information about content providers. These are a key aspect of how 559 * different activities invoke and propagate data between themselves.</p> 560 * 561 * <p>The Activity class also provides an API for managing internal persistent state 562 * associated with an activity. This can be used, for example, to remember 563 * the user's preferred initial display in a calendar (day view or week view) 564 * or the user's default home page in a web browser.</p> 565 * 566 * <p>Activity persistent state is managed 567 * with the method {@link #getPreferences}, 568 * allowing you to retrieve and 569 * modify a set of name/value pairs associated with the activity. To use 570 * preferences that are shared across multiple application components 571 * (activities, receivers, services, providers), you can use the underlying 572 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method 573 * to retrieve a preferences 574 * object stored under a specific name. 575 * (Note that it is not possible to share settings data across application 576 * packages -- for that you will need a content provider.)</p> 577 * 578 * <p>Here is an excerpt from a calendar activity that stores the user's 579 * preferred view mode in its persistent settings:</p> 580 * 581 * <pre class="prettyprint"> 582 * public class CalendarActivity extends Activity { 583 * ... 584 * 585 * static final int DAY_VIEW_MODE = 0; 586 * static final int WEEK_VIEW_MODE = 1; 587 * 588 * private SharedPreferences mPrefs; 589 * private int mCurViewMode; 590 * 591 * protected void onCreate(Bundle savedInstanceState) { 592 * super.onCreate(savedInstanceState); 593 * 594 * SharedPreferences mPrefs = getSharedPreferences(); 595 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE); 596 * } 597 * 598 * protected void onPause() { 599 * super.onPause(); 600 * 601 * SharedPreferences.Editor ed = mPrefs.edit(); 602 * ed.putInt("view_mode", mCurViewMode); 603 * ed.commit(); 604 * } 605 * } 606 * </pre> 607 * 608 * <a name="Permissions"></a> 609 * <h3>Permissions</h3> 610 * 611 * <p>The ability to start a particular Activity can be enforced when it is 612 * declared in its 613 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>} 614 * tag. By doing so, other applications will need to declare a corresponding 615 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} 616 * element in their own manifest to be able to start that activity. 617 * 618 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION 619 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION 620 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the 621 * Activity access to the specific URIs in the Intent. Access will remain 622 * until the Activity has finished (it will remain across the hosting 623 * process being killed and other temporary destruction). As of 624 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity 625 * was already created and a new Intent is being delivered to 626 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added 627 * to the existing ones it holds. 628 * 629 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> 630 * document for more information on permissions and security in general. 631 * 632 * <a name="ProcessLifecycle"></a> 633 * <h3>Process Lifecycle</h3> 634 * 635 * <p>The Android system attempts to keep application process around for as 636 * long as possible, but eventually will need to remove old processes when 637 * memory runs low. As described in <a href="#ActivityLifecycle">Activity 638 * Lifecycle</a>, the decision about which process to remove is intimately 639 * tied to the state of the user's interaction with it. In general, there 640 * are four states a process can be in based on the activities running in it, 641 * listed here in order of importance. The system will kill less important 642 * processes (the last ones) before it resorts to killing more important 643 * processes (the first ones). 644 * 645 * <ol> 646 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen 647 * that the user is currently interacting with) is considered the most important. 648 * Its process will only be killed as a last resort, if it uses more memory 649 * than is available on the device. Generally at this point the device has 650 * reached a memory paging state, so this is required in order to keep the user 651 * interface responsive. 652 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user 653 * but not in the foreground, such as one sitting behind a foreground dialog) 654 * is considered extremely important and will not be killed unless that is 655 * required to keep the foreground activity running. 656 * <li> <p>A <b>background activity</b> (an activity that is not visible to 657 * the user and has been paused) is no longer critical, so the system may 658 * safely kill its process to reclaim memory for other foreground or 659 * visible processes. If its process needs to be killed, when the user navigates 660 * back to the activity (making it visible on the screen again), its 661 * {@link #onCreate} method will be called with the savedInstanceState it had previously 662 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same 663 * state as the user last left it. 664 * <li> <p>An <b>empty process</b> is one hosting no activities or other 665 * application components (such as {@link Service} or 666 * {@link android.content.BroadcastReceiver} classes). These are killed very 667 * quickly by the system as memory becomes low. For this reason, any 668 * background operation you do outside of an activity must be executed in the 669 * context of an activity BroadcastReceiver or Service to ensure that the system 670 * knows it needs to keep your process around. 671 * </ol> 672 * 673 * <p>Sometimes an Activity may need to do a long-running operation that exists 674 * independently of the activity lifecycle itself. An example may be a camera 675 * application that allows you to upload a picture to a web site. The upload 676 * may take a long time, and the application should allow the user to leave 677 * the application will it is executing. To accomplish this, your Activity 678 * should start a {@link Service} in which the upload takes place. This allows 679 * the system to properly prioritize your process (considering it to be more 680 * important than other non-visible applications) for the duration of the 681 * upload, independent of whether the original activity is paused, stopped, 682 * or finished. 683 */ 684public class Activity extends ContextThemeWrapper 685 implements LayoutInflater.Factory2, 686 Window.Callback, KeyEvent.Callback, 687 OnCreateContextMenuListener, ComponentCallbacks2, 688 Window.OnWindowDismissedCallback, WindowControllerCallback { 689 private static final String TAG = "Activity"; 690 private static final boolean DEBUG_LIFECYCLE = false; 691 692 /** Standard activity result: operation canceled. */ 693 public static final int RESULT_CANCELED = 0; 694 /** Standard activity result: operation succeeded. */ 695 public static final int RESULT_OK = -1; 696 /** Start of user-defined activity results. */ 697 public static final int RESULT_FIRST_USER = 1; 698 699 /** @hide Task isn't finished when activity is finished */ 700 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0; 701 /** 702 * @hide Task is finished if the finishing activity is the root of the task. To preserve the 703 * past behavior the task is also removed from recents. 704 */ 705 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1; 706 /** 707 * @hide Task is finished along with the finishing activity, but it is not removed from 708 * recents. 709 */ 710 public static final int FINISH_TASK_WITH_ACTIVITY = 2; 711 712 static final String FRAGMENTS_TAG = "android:fragments"; 713 714 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState"; 715 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds"; 716 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs"; 717 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_"; 718 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_"; 719 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY = 720 "android:hasCurrentPermissionsRequest"; 721 722 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:"; 723 724 private static class ManagedDialog { 725 Dialog mDialog; 726 Bundle mArgs; 727 } 728 private SparseArray<ManagedDialog> mManagedDialogs; 729 730 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called. 731 private Instrumentation mInstrumentation; 732 private IBinder mToken; 733 private int mIdent; 734 /*package*/ String mEmbeddedID; 735 private Application mApplication; 736 /*package*/ Intent mIntent; 737 /*package*/ String mReferrer; 738 private ComponentName mComponent; 739 /*package*/ ActivityInfo mActivityInfo; 740 /*package*/ ActivityThread mMainThread; 741 Activity mParent; 742 boolean mCalled; 743 /*package*/ boolean mResumed; 744 /*package*/ boolean mStopped; 745 boolean mFinished; 746 boolean mStartedActivity; 747 private boolean mDestroyed; 748 private boolean mDoReportFullyDrawn = true; 749 /** true if the activity is going through a transient pause */ 750 /*package*/ boolean mTemporaryPause = false; 751 /** true if the activity is being destroyed in order to recreate it with a new configuration */ 752 /*package*/ boolean mChangingConfigurations = false; 753 /*package*/ int mConfigChangeFlags; 754 /*package*/ Configuration mCurrentConfig; 755 private SearchManager mSearchManager; 756 private MenuInflater mMenuInflater; 757 758 static final class NonConfigurationInstances { 759 Object activity; 760 HashMap<String, Object> children; 761 FragmentManagerNonConfig fragments; 762 ArrayMap<String, LoaderManager> loaders; 763 VoiceInteractor voiceInteractor; 764 } 765 /* package */ NonConfigurationInstances mLastNonConfigurationInstances; 766 767 private Window mWindow; 768 769 private WindowManager mWindowManager; 770 /*package*/ View mDecor = null; 771 /*package*/ boolean mWindowAdded = false; 772 /*package*/ boolean mVisibleFromServer = false; 773 /*package*/ boolean mVisibleFromClient = true; 774 /*package*/ ActionBar mActionBar = null; 775 private boolean mEnableDefaultActionBarUp; 776 777 private VoiceInteractor mVoiceInteractor; 778 779 private CharSequence mTitle; 780 private int mTitleColor = 0; 781 782 // we must have a handler before the FragmentController is constructed 783 final Handler mHandler = new Handler(); 784 final FragmentController mFragments = FragmentController.createController(new HostCallbacks()); 785 786 // Most recent call to requestVisibleBehind(). 787 boolean mVisibleBehind; 788 789 private static final class ManagedCursor { 790 ManagedCursor(Cursor cursor) { 791 mCursor = cursor; 792 mReleased = false; 793 mUpdated = false; 794 } 795 796 private final Cursor mCursor; 797 private boolean mReleased; 798 private boolean mUpdated; 799 } 800 private final ArrayList<ManagedCursor> mManagedCursors = 801 new ArrayList<ManagedCursor>(); 802 803 // protected by synchronized (this) 804 int mResultCode = RESULT_CANCELED; 805 Intent mResultData = null; 806 807 private TranslucentConversionListener mTranslucentCallback; 808 private boolean mChangeCanvasToTranslucent; 809 810 private SearchEvent mSearchEvent; 811 812 private boolean mTitleReady = false; 813 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY; 814 815 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE; 816 private SpannableStringBuilder mDefaultKeySsb = null; 817 818 private ActivityManager.TaskDescription mTaskDescription = 819 new ActivityManager.TaskDescription(); 820 821 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused}; 822 823 @SuppressWarnings("unused") 824 private final Object mInstanceTracker = StrictMode.trackActivity(this); 825 826 private Thread mUiThread; 827 828 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState(); 829 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK; 830 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK; 831 832 private boolean mHasCurrentPermissionsRequest; 833 private boolean mEatKeyUpEvent; 834 835 private static native String getDlWarning(); 836 837 /** Return the intent that started this activity. */ 838 public Intent getIntent() { 839 return mIntent; 840 } 841 842 /** 843 * Change the intent returned by {@link #getIntent}. This holds a 844 * reference to the given intent; it does not copy it. Often used in 845 * conjunction with {@link #onNewIntent}. 846 * 847 * @param newIntent The new Intent object to return from getIntent 848 * 849 * @see #getIntent 850 * @see #onNewIntent 851 */ 852 public void setIntent(Intent newIntent) { 853 mIntent = newIntent; 854 } 855 856 /** Return the application that owns this activity. */ 857 public final Application getApplication() { 858 return mApplication; 859 } 860 861 /** Is this activity embedded inside of another activity? */ 862 public final boolean isChild() { 863 return mParent != null; 864 } 865 866 /** Return the parent activity if this view is an embedded child. */ 867 public final Activity getParent() { 868 return mParent; 869 } 870 871 /** Retrieve the window manager for showing custom windows. */ 872 public WindowManager getWindowManager() { 873 return mWindowManager; 874 } 875 876 /** 877 * Retrieve the current {@link android.view.Window} for the activity. 878 * This can be used to directly access parts of the Window API that 879 * are not available through Activity/Screen. 880 * 881 * @return Window The current window, or null if the activity is not 882 * visual. 883 */ 884 public Window getWindow() { 885 return mWindow; 886 } 887 888 /** 889 * Return the LoaderManager for this activity, creating it if needed. 890 */ 891 public LoaderManager getLoaderManager() { 892 return mFragments.getLoaderManager(); 893 } 894 895 /** 896 * Calls {@link android.view.Window#getCurrentFocus} on the 897 * Window of this Activity to return the currently focused view. 898 * 899 * @return View The current View with focus or null. 900 * 901 * @see #getWindow 902 * @see android.view.Window#getCurrentFocus 903 */ 904 @Nullable 905 public View getCurrentFocus() { 906 return mWindow != null ? mWindow.getCurrentFocus() : null; 907 } 908 909 /** 910 * Called when the activity is starting. This is where most initialization 911 * should go: calling {@link #setContentView(int)} to inflate the 912 * activity's UI, using {@link #findViewById} to programmatically interact 913 * with widgets in the UI, calling 914 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve 915 * cursors for data being displayed, etc. 916 * 917 * <p>You can call {@link #finish} from within this function, in 918 * which case onDestroy() will be immediately called without any of the rest 919 * of the activity lifecycle ({@link #onStart}, {@link #onResume}, 920 * {@link #onPause}, etc) executing. 921 * 922 * <p><em>Derived classes must call through to the super class's 923 * implementation of this method. If they do not, an exception will be 924 * thrown.</em></p> 925 * 926 * @param savedInstanceState If the activity is being re-initialized after 927 * previously being shut down then this Bundle contains the data it most 928 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> 929 * 930 * @see #onStart 931 * @see #onSaveInstanceState 932 * @see #onRestoreInstanceState 933 * @see #onPostCreate 934 */ 935 @MainThread 936 @CallSuper 937 protected void onCreate(@Nullable Bundle savedInstanceState) { 938 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState); 939 if (mLastNonConfigurationInstances != null) { 940 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders); 941 } 942 if (mActivityInfo.parentActivityName != null) { 943 if (mActionBar == null) { 944 mEnableDefaultActionBarUp = true; 945 } else { 946 mActionBar.setDefaultDisplayHomeAsUpEnabled(true); 947 } 948 } 949 if (savedInstanceState != null) { 950 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); 951 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null 952 ? mLastNonConfigurationInstances.fragments : null); 953 } 954 mFragments.dispatchCreate(); 955 getApplication().dispatchActivityCreated(this, savedInstanceState); 956 if (mVoiceInteractor != null) { 957 mVoiceInteractor.attachActivity(this); 958 } 959 mCalled = true; 960 } 961 962 /** 963 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with 964 * the attribute {@link android.R.attr#persistableMode} set to 965 * <code>persistAcrossReboots</code>. 966 * 967 * @param savedInstanceState if the activity is being re-initialized after 968 * previously being shut down then this Bundle contains the data it most 969 * recently supplied in {@link #onSaveInstanceState}. 970 * <b><i>Note: Otherwise it is null.</i></b> 971 * @param persistentState if the activity is being re-initialized after 972 * previously being shut down or powered off then this Bundle contains the data it most 973 * recently supplied to outPersistentState in {@link #onSaveInstanceState}. 974 * <b><i>Note: Otherwise it is null.</i></b> 975 * 976 * @see #onCreate(android.os.Bundle) 977 * @see #onStart 978 * @see #onSaveInstanceState 979 * @see #onRestoreInstanceState 980 * @see #onPostCreate 981 */ 982 public void onCreate(@Nullable Bundle savedInstanceState, 983 @Nullable PersistableBundle persistentState) { 984 onCreate(savedInstanceState); 985 } 986 987 /** 988 * The hook for {@link ActivityThread} to restore the state of this activity. 989 * 990 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and 991 * {@link #restoreManagedDialogs(android.os.Bundle)}. 992 * 993 * @param savedInstanceState contains the saved state 994 */ 995 final void performRestoreInstanceState(Bundle savedInstanceState) { 996 onRestoreInstanceState(savedInstanceState); 997 restoreManagedDialogs(savedInstanceState); 998 } 999 1000 /** 1001 * The hook for {@link ActivityThread} to restore the state of this activity. 1002 * 1003 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and 1004 * {@link #restoreManagedDialogs(android.os.Bundle)}. 1005 * 1006 * @param savedInstanceState contains the saved state 1007 * @param persistentState contains the persistable saved state 1008 */ 1009 final void performRestoreInstanceState(Bundle savedInstanceState, 1010 PersistableBundle persistentState) { 1011 onRestoreInstanceState(savedInstanceState, persistentState); 1012 if (savedInstanceState != null) { 1013 restoreManagedDialogs(savedInstanceState); 1014 } 1015 } 1016 1017 /** 1018 * This method is called after {@link #onStart} when the activity is 1019 * being re-initialized from a previously saved state, given here in 1020 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate} 1021 * to restore their state, but it is sometimes convenient to do it here 1022 * after all of the initialization has been done or to allow subclasses to 1023 * decide whether to use your default implementation. The default 1024 * implementation of this method performs a restore of any view state that 1025 * had previously been frozen by {@link #onSaveInstanceState}. 1026 * 1027 * <p>This method is called between {@link #onStart} and 1028 * {@link #onPostCreate}. 1029 * 1030 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}. 1031 * 1032 * @see #onCreate 1033 * @see #onPostCreate 1034 * @see #onResume 1035 * @see #onSaveInstanceState 1036 */ 1037 protected void onRestoreInstanceState(Bundle savedInstanceState) { 1038 if (mWindow != null) { 1039 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG); 1040 if (windowState != null) { 1041 mWindow.restoreHierarchyState(windowState); 1042 } 1043 } 1044 } 1045 1046 /** 1047 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities 1048 * created with the attribute {@link android.R.attr#persistableMode} set to 1049 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed 1050 * came from the restored PersistableBundle first 1051 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}. 1052 * 1053 * <p>This method is called between {@link #onStart} and 1054 * {@link #onPostCreate}. 1055 * 1056 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called. 1057 * 1058 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}. 1059 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}. 1060 * 1061 * @see #onRestoreInstanceState(Bundle) 1062 * @see #onCreate 1063 * @see #onPostCreate 1064 * @see #onResume 1065 * @see #onSaveInstanceState 1066 */ 1067 public void onRestoreInstanceState(Bundle savedInstanceState, 1068 PersistableBundle persistentState) { 1069 if (savedInstanceState != null) { 1070 onRestoreInstanceState(savedInstanceState); 1071 } 1072 } 1073 1074 /** 1075 * Restore the state of any saved managed dialogs. 1076 * 1077 * @param savedInstanceState The bundle to restore from. 1078 */ 1079 private void restoreManagedDialogs(Bundle savedInstanceState) { 1080 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG); 1081 if (b == null) { 1082 return; 1083 } 1084 1085 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY); 1086 final int numDialogs = ids.length; 1087 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs); 1088 for (int i = 0; i < numDialogs; i++) { 1089 final Integer dialogId = ids[i]; 1090 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId)); 1091 if (dialogState != null) { 1092 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate 1093 // so tell createDialog() not to do it, otherwise we get an exception 1094 final ManagedDialog md = new ManagedDialog(); 1095 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId)); 1096 md.mDialog = createDialog(dialogId, dialogState, md.mArgs); 1097 if (md.mDialog != null) { 1098 mManagedDialogs.put(dialogId, md); 1099 onPrepareDialog(dialogId, md.mDialog, md.mArgs); 1100 md.mDialog.onRestoreInstanceState(dialogState); 1101 } 1102 } 1103 } 1104 } 1105 1106 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) { 1107 final Dialog dialog = onCreateDialog(dialogId, args); 1108 if (dialog == null) { 1109 return null; 1110 } 1111 dialog.dispatchOnCreate(state); 1112 return dialog; 1113 } 1114 1115 private static String savedDialogKeyFor(int key) { 1116 return SAVED_DIALOG_KEY_PREFIX + key; 1117 } 1118 1119 private static String savedDialogArgsKeyFor(int key) { 1120 return SAVED_DIALOG_ARGS_KEY_PREFIX + key; 1121 } 1122 1123 /** 1124 * Called when activity start-up is complete (after {@link #onStart} 1125 * and {@link #onRestoreInstanceState} have been called). Applications will 1126 * generally not implement this method; it is intended for system 1127 * classes to do final initialization after application code has run. 1128 * 1129 * <p><em>Derived classes must call through to the super class's 1130 * implementation of this method. If they do not, an exception will be 1131 * thrown.</em></p> 1132 * 1133 * @param savedInstanceState If the activity is being re-initialized after 1134 * previously being shut down then this Bundle contains the data it most 1135 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> 1136 * @see #onCreate 1137 */ 1138 @CallSuper 1139 protected void onPostCreate(@Nullable Bundle savedInstanceState) { 1140 if (!isChild()) { 1141 mTitleReady = true; 1142 onTitleChanged(getTitle(), getTitleColor()); 1143 } 1144 1145 mCalled = true; 1146 } 1147 1148 /** 1149 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities 1150 * created with the attribute {@link android.R.attr#persistableMode} set to 1151 * <code>persistAcrossReboots</code>. 1152 * 1153 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState} 1154 * @param persistentState The data caming from the PersistableBundle first 1155 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}. 1156 * 1157 * @see #onCreate 1158 */ 1159 public void onPostCreate(@Nullable Bundle savedInstanceState, 1160 @Nullable PersistableBundle persistentState) { 1161 onPostCreate(savedInstanceState); 1162 } 1163 1164 /** 1165 * Called after {@link #onCreate} — or after {@link #onRestart} when 1166 * the activity had been stopped, but is now again being displayed to the 1167 * user. It will be followed by {@link #onResume}. 1168 * 1169 * <p><em>Derived classes must call through to the super class's 1170 * implementation of this method. If they do not, an exception will be 1171 * thrown.</em></p> 1172 * 1173 * @see #onCreate 1174 * @see #onStop 1175 * @see #onResume 1176 */ 1177 @CallSuper 1178 protected void onStart() { 1179 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this); 1180 mCalled = true; 1181 1182 mFragments.doLoaderStart(); 1183 1184 getApplication().dispatchActivityStarted(this); 1185 } 1186 1187 /** 1188 * Called after {@link #onStop} when the current activity is being 1189 * re-displayed to the user (the user has navigated back to it). It will 1190 * be followed by {@link #onStart} and then {@link #onResume}. 1191 * 1192 * <p>For activities that are using raw {@link Cursor} objects (instead of 1193 * creating them through 1194 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)}, 1195 * this is usually the place 1196 * where the cursor should be requeried (because you had deactivated it in 1197 * {@link #onStop}. 1198 * 1199 * <p><em>Derived classes must call through to the super class's 1200 * implementation of this method. If they do not, an exception will be 1201 * thrown.</em></p> 1202 * 1203 * @see #onStop 1204 * @see #onStart 1205 * @see #onResume 1206 */ 1207 @CallSuper 1208 protected void onRestart() { 1209 mCalled = true; 1210 } 1211 1212 /** 1213 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks 1214 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended 1215 * to give the activity a hint that its state is no longer saved -- it will generally 1216 * be called after {@link #onSaveInstanceState} and prior to the activity being 1217 * resumed/started again. 1218 */ 1219 public void onStateNotSaved() { 1220 } 1221 1222 /** 1223 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or 1224 * {@link #onPause}, for your activity to start interacting with the user. 1225 * This is a good place to begin animations, open exclusive-access devices 1226 * (such as the camera), etc. 1227 * 1228 * <p>Keep in mind that onResume is not the best indicator that your activity 1229 * is visible to the user; a system window such as the keyguard may be in 1230 * front. Use {@link #onWindowFocusChanged} to know for certain that your 1231 * activity is visible to the user (for example, to resume a game). 1232 * 1233 * <p><em>Derived classes must call through to the super class's 1234 * implementation of this method. If they do not, an exception will be 1235 * thrown.</em></p> 1236 * 1237 * @see #onRestoreInstanceState 1238 * @see #onRestart 1239 * @see #onPostResume 1240 * @see #onPause 1241 */ 1242 @CallSuper 1243 protected void onResume() { 1244 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this); 1245 getApplication().dispatchActivityResumed(this); 1246 mActivityTransitionState.onResume(this, isTopOfTask()); 1247 mCalled = true; 1248 } 1249 1250 /** 1251 * Called when activity resume is complete (after {@link #onResume} has 1252 * been called). Applications will generally not implement this method; 1253 * it is intended for system classes to do final setup after application 1254 * resume code has run. 1255 * 1256 * <p><em>Derived classes must call through to the super class's 1257 * implementation of this method. If they do not, an exception will be 1258 * thrown.</em></p> 1259 * 1260 * @see #onResume 1261 */ 1262 @CallSuper 1263 protected void onPostResume() { 1264 final Window win = getWindow(); 1265 if (win != null) win.makeActive(); 1266 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true); 1267 mCalled = true; 1268 } 1269 1270 void setVoiceInteractor(IVoiceInteractor voiceInteractor) { 1271 if (voiceInteractor == null) { 1272 mVoiceInteractor = null; 1273 } else { 1274 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this, 1275 Looper.myLooper()); 1276 } 1277 } 1278 1279 /** 1280 * Check whether this activity is running as part of a voice interaction with the user. 1281 * If true, it should perform its interaction with the user through the 1282 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}. 1283 */ 1284 public boolean isVoiceInteraction() { 1285 return mVoiceInteractor != null; 1286 } 1287 1288 /** 1289 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root 1290 * of a voice interaction. That is, returns true if this activity was directly 1291 * started by the voice interaction service as the initiation of a voice interaction. 1292 * Otherwise, for example if it was started by another activity while under voice 1293 * interaction, returns false. 1294 */ 1295 public boolean isVoiceInteractionRoot() { 1296 try { 1297 return mVoiceInteractor != null 1298 && ActivityManagerNative.getDefault().isRootVoiceInteraction(mToken); 1299 } catch (RemoteException e) { 1300 } 1301 return false; 1302 } 1303 1304 /** 1305 * Retrieve the active {@link VoiceInteractor} that the user is going through to 1306 * interact with this activity. 1307 */ 1308 public VoiceInteractor getVoiceInteractor() { 1309 return mVoiceInteractor; 1310 } 1311 1312 /** 1313 * Queries whether the currently enabled voice interaction service supports returning 1314 * a voice interactor for use by the activity. This is valid only for the duration of the 1315 * activity. 1316 * 1317 * @return whether the current voice interaction service supports local voice interaction 1318 */ 1319 public boolean isLocalVoiceInteractionSupported() { 1320 try { 1321 return ActivityManagerNative.getDefault().supportsLocalVoiceInteraction(); 1322 } catch (RemoteException re) { 1323 } 1324 return false; 1325 } 1326 1327 /** 1328 * Starts a local voice interaction session. When ready, 1329 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options 1330 * to the registered voice interaction service. 1331 * @param privateOptions a Bundle of private arguments to the current voice interaction service 1332 */ 1333 public void startLocalVoiceInteraction(Bundle privateOptions) { 1334 try { 1335 ActivityManagerNative.getDefault().startLocalVoiceInteraction(mToken, privateOptions); 1336 } catch (RemoteException re) { 1337 } 1338 } 1339 1340 /** 1341 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a 1342 * voice interaction session being started. You can now retrieve a voice interactor using 1343 * {@link #getVoiceInteractor()}. 1344 */ 1345 public void onLocalVoiceInteractionStarted() { 1346 } 1347 1348 /** 1349 * Callback to indicate that the local voice interaction has stopped either 1350 * because it was requested through a call to {@link #stopLocalVoiceInteraction()} 1351 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor} 1352 * is no longer valid after this. 1353 */ 1354 public void onLocalVoiceInteractionStopped() { 1355 } 1356 1357 /** 1358 * Request to terminate the current voice interaction that was previously started 1359 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is 1360 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called. 1361 */ 1362 public void stopLocalVoiceInteraction() { 1363 try { 1364 ActivityManagerNative.getDefault().stopLocalVoiceInteraction(mToken); 1365 } catch (RemoteException re) { 1366 } 1367 } 1368 1369 /** 1370 * This is called for activities that set launchMode to "singleTop" in 1371 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} 1372 * flag when calling {@link #startActivity}. In either case, when the 1373 * activity is re-launched while at the top of the activity stack instead 1374 * of a new instance of the activity being started, onNewIntent() will be 1375 * called on the existing instance with the Intent that was used to 1376 * re-launch it. 1377 * 1378 * <p>An activity will always be paused before receiving a new intent, so 1379 * you can count on {@link #onResume} being called after this method. 1380 * 1381 * <p>Note that {@link #getIntent} still returns the original Intent. You 1382 * can use {@link #setIntent} to update it to this new Intent. 1383 * 1384 * @param intent The new intent that was started for the activity. 1385 * 1386 * @see #getIntent 1387 * @see #setIntent 1388 * @see #onResume 1389 */ 1390 protected void onNewIntent(Intent intent) { 1391 } 1392 1393 /** 1394 * The hook for {@link ActivityThread} to save the state of this activity. 1395 * 1396 * Calls {@link #onSaveInstanceState(android.os.Bundle)} 1397 * and {@link #saveManagedDialogs(android.os.Bundle)}. 1398 * 1399 * @param outState The bundle to save the state to. 1400 */ 1401 final void performSaveInstanceState(Bundle outState) { 1402 onSaveInstanceState(outState); 1403 saveManagedDialogs(outState); 1404 mActivityTransitionState.saveState(outState); 1405 storeHasCurrentPermissionRequest(outState); 1406 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState); 1407 } 1408 1409 /** 1410 * The hook for {@link ActivityThread} to save the state of this activity. 1411 * 1412 * Calls {@link #onSaveInstanceState(android.os.Bundle)} 1413 * and {@link #saveManagedDialogs(android.os.Bundle)}. 1414 * 1415 * @param outState The bundle to save the state to. 1416 * @param outPersistentState The bundle to save persistent state to. 1417 */ 1418 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { 1419 onSaveInstanceState(outState, outPersistentState); 1420 saveManagedDialogs(outState); 1421 storeHasCurrentPermissionRequest(outState); 1422 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState + 1423 ", " + outPersistentState); 1424 } 1425 1426 /** 1427 * Called to retrieve per-instance state from an activity before being killed 1428 * so that the state can be restored in {@link #onCreate} or 1429 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method 1430 * will be passed to both). 1431 * 1432 * <p>This method is called before an activity may be killed so that when it 1433 * comes back some time in the future it can restore its state. For example, 1434 * if activity B is launched in front of activity A, and at some point activity 1435 * A is killed to reclaim resources, activity A will have a chance to save the 1436 * current state of its user interface via this method so that when the user 1437 * returns to activity A, the state of the user interface can be restored 1438 * via {@link #onCreate} or {@link #onRestoreInstanceState}. 1439 * 1440 * <p>Do not confuse this method with activity lifecycle callbacks such as 1441 * {@link #onPause}, which is always called when an activity is being placed 1442 * in the background or on its way to destruction, or {@link #onStop} which 1443 * is called before destruction. One example of when {@link #onPause} and 1444 * {@link #onStop} is called and not this method is when a user navigates back 1445 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState} 1446 * on B because that particular instance will never be restored, so the 1447 * system avoids calling it. An example when {@link #onPause} is called and 1448 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A: 1449 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't 1450 * killed during the lifetime of B since the state of the user interface of 1451 * A will stay intact. 1452 * 1453 * <p>The default implementation takes care of most of the UI per-instance 1454 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each 1455 * view in the hierarchy that has an id, and by saving the id of the currently 1456 * focused view (all of which is restored by the default implementation of 1457 * {@link #onRestoreInstanceState}). If you override this method to save additional 1458 * information not captured by each individual view, you will likely want to 1459 * call through to the default implementation, otherwise be prepared to save 1460 * all of the state of each view yourself. 1461 * 1462 * <p>If called, this method will occur before {@link #onStop}. There are 1463 * no guarantees about whether it will occur before or after {@link #onPause}. 1464 * 1465 * @param outState Bundle in which to place your saved state. 1466 * 1467 * @see #onCreate 1468 * @see #onRestoreInstanceState 1469 * @see #onPause 1470 */ 1471 protected void onSaveInstanceState(Bundle outState) { 1472 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState()); 1473 Parcelable p = mFragments.saveAllState(); 1474 if (p != null) { 1475 outState.putParcelable(FRAGMENTS_TAG, p); 1476 } 1477 getApplication().dispatchActivitySaveInstanceState(this, outState); 1478 } 1479 1480 /** 1481 * This is the same as {@link #onSaveInstanceState} but is called for activities 1482 * created with the attribute {@link android.R.attr#persistableMode} set to 1483 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed 1484 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)} 1485 * the first time that this activity is restarted following the next device reboot. 1486 * 1487 * @param outState Bundle in which to place your saved state. 1488 * @param outPersistentState State which will be saved across reboots. 1489 * 1490 * @see #onSaveInstanceState(Bundle) 1491 * @see #onCreate 1492 * @see #onRestoreInstanceState(Bundle, PersistableBundle) 1493 * @see #onPause 1494 */ 1495 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { 1496 onSaveInstanceState(outState); 1497 } 1498 1499 /** 1500 * Save the state of any managed dialogs. 1501 * 1502 * @param outState place to store the saved state. 1503 */ 1504 private void saveManagedDialogs(Bundle outState) { 1505 if (mManagedDialogs == null) { 1506 return; 1507 } 1508 1509 final int numDialogs = mManagedDialogs.size(); 1510 if (numDialogs == 0) { 1511 return; 1512 } 1513 1514 Bundle dialogState = new Bundle(); 1515 1516 int[] ids = new int[mManagedDialogs.size()]; 1517 1518 // save each dialog's bundle, gather the ids 1519 for (int i = 0; i < numDialogs; i++) { 1520 final int key = mManagedDialogs.keyAt(i); 1521 ids[i] = key; 1522 final ManagedDialog md = mManagedDialogs.valueAt(i); 1523 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState()); 1524 if (md.mArgs != null) { 1525 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs); 1526 } 1527 } 1528 1529 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids); 1530 outState.putBundle(SAVED_DIALOGS_TAG, dialogState); 1531 } 1532 1533 1534 /** 1535 * Called as part of the activity lifecycle when an activity is going into 1536 * the background, but has not (yet) been killed. The counterpart to 1537 * {@link #onResume}. 1538 * 1539 * <p>When activity B is launched in front of activity A, this callback will 1540 * be invoked on A. B will not be created until A's {@link #onPause} returns, 1541 * so be sure to not do anything lengthy here. 1542 * 1543 * <p>This callback is mostly used for saving any persistent state the 1544 * activity is editing, to present a "edit in place" model to the user and 1545 * making sure nothing is lost if there are not enough resources to start 1546 * the new activity without first killing this one. This is also a good 1547 * place to do things like stop animations and other things that consume a 1548 * noticeable amount of CPU in order to make the switch to the next activity 1549 * as fast as possible, or to close resources that are exclusive access 1550 * such as the camera. 1551 * 1552 * <p>In situations where the system needs more memory it may kill paused 1553 * processes to reclaim resources. Because of this, you should be sure 1554 * that all of your state is saved by the time you return from 1555 * this function. In general {@link #onSaveInstanceState} is used to save 1556 * per-instance state in the activity and this method is used to store 1557 * global persistent data (in content providers, files, etc.) 1558 * 1559 * <p>After receiving this call you will usually receive a following call 1560 * to {@link #onStop} (after the next activity has been resumed and 1561 * displayed), however in some cases there will be a direct call back to 1562 * {@link #onResume} without going through the stopped state. 1563 * 1564 * <p><em>Derived classes must call through to the super class's 1565 * implementation of this method. If they do not, an exception will be 1566 * thrown.</em></p> 1567 * 1568 * @see #onResume 1569 * @see #onSaveInstanceState 1570 * @see #onStop 1571 */ 1572 @CallSuper 1573 protected void onPause() { 1574 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this); 1575 getApplication().dispatchActivityPaused(this); 1576 mCalled = true; 1577 } 1578 1579 /** 1580 * Called as part of the activity lifecycle when an activity is about to go 1581 * into the background as the result of user choice. For example, when the 1582 * user presses the Home key, {@link #onUserLeaveHint} will be called, but 1583 * when an incoming phone call causes the in-call Activity to be automatically 1584 * brought to the foreground, {@link #onUserLeaveHint} will not be called on 1585 * the activity being interrupted. In cases when it is invoked, this method 1586 * is called right before the activity's {@link #onPause} callback. 1587 * 1588 * <p>This callback and {@link #onUserInteraction} are intended to help 1589 * activities manage status bar notifications intelligently; specifically, 1590 * for helping activities determine the proper time to cancel a notfication. 1591 * 1592 * @see #onUserInteraction() 1593 */ 1594 protected void onUserLeaveHint() { 1595 } 1596 1597 /** 1598 * Generate a new thumbnail for this activity. This method is called before 1599 * pausing the activity, and should draw into <var>outBitmap</var> the 1600 * imagery for the desired thumbnail in the dimensions of that bitmap. It 1601 * can use the given <var>canvas</var>, which is configured to draw into the 1602 * bitmap, for rendering if desired. 1603 * 1604 * <p>The default implementation returns fails and does not draw a thumbnail; 1605 * this will result in the platform creating its own thumbnail if needed. 1606 * 1607 * @param outBitmap The bitmap to contain the thumbnail. 1608 * @param canvas Can be used to render into the bitmap. 1609 * 1610 * @return Return true if you have drawn into the bitmap; otherwise after 1611 * you return it will be filled with a default thumbnail. 1612 * 1613 * @see #onCreateDescription 1614 * @see #onSaveInstanceState 1615 * @see #onPause 1616 */ 1617 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) { 1618 return false; 1619 } 1620 1621 /** 1622 * Generate a new description for this activity. This method is called 1623 * before pausing the activity and can, if desired, return some textual 1624 * description of its current state to be displayed to the user. 1625 * 1626 * <p>The default implementation returns null, which will cause you to 1627 * inherit the description from the previous activity. If all activities 1628 * return null, generally the label of the top activity will be used as the 1629 * description. 1630 * 1631 * @return A description of what the user is doing. It should be short and 1632 * sweet (only a few words). 1633 * 1634 * @see #onCreateThumbnail 1635 * @see #onSaveInstanceState 1636 * @see #onPause 1637 */ 1638 @Nullable 1639 public CharSequence onCreateDescription() { 1640 return null; 1641 } 1642 1643 /** 1644 * This is called when the user is requesting an assist, to build a full 1645 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current 1646 * application. You can override this method to place into the bundle anything 1647 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part 1648 * of the assist Intent. 1649 * 1650 * <p>This function will be called after any global assist callbacks that had 1651 * been registered with {@link Application#registerOnProvideAssistDataListener 1652 * Application.registerOnProvideAssistDataListener}. 1653 */ 1654 public void onProvideAssistData(Bundle data) { 1655 } 1656 1657 /** 1658 * This is called when the user is requesting an assist, to provide references 1659 * to content related to the current activity. Before being called, the 1660 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent 1661 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types 1662 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and 1663 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and 1664 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent. 1665 * 1666 * <p>Custom implementation may adjust the content intent to better reflect the top-level 1667 * context of the activity, and fill in its ClipData with additional content of 1668 * interest that the user is currently viewing. For example, an image gallery application 1669 * that has launched in to an activity allowing the user to swipe through pictures should 1670 * modify the intent to reference the current image they are looking it; such an 1671 * application when showing a list of pictures should add a ClipData that has 1672 * references to all of the pictures currently visible on screen.</p> 1673 * 1674 * @param outContent The assist content to return. 1675 */ 1676 public void onProvideAssistContent(AssistContent outContent) { 1677 } 1678 1679 /** 1680 * Request the Keyboard Shortcuts screen to show up. If it succeeds, this will trigger 1681 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity. 1682 */ 1683 public final void requestKeyboardShortcutsHelper() { 1684 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS); 1685 intent.setComponent(new ComponentName("com.android.systemui", 1686 "com.android.systemui.statusbar.KeyboardShortcutsReceiver")); 1687 sendBroadcast(intent); 1688 } 1689 1690 @Override 1691 public void onProvideKeyboardShortcuts( 1692 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) { 1693 if (menu == null) { 1694 return; 1695 } 1696 final InputDevice inputDevice = InputManager.getInstance().getInputDevice(deviceId); 1697 if (inputDevice == null) { 1698 return; 1699 } 1700 final KeyCharacterMap keyCharacterMap = inputDevice.getKeyCharacterMap(); 1701 KeyboardShortcutGroup group = null; 1702 int menuSize = menu.size(); 1703 for (int i = 0; i < menuSize; ++i) { 1704 final MenuItem item = menu.getItem(i); 1705 final CharSequence title = item.getTitle(); 1706 final char alphaShortcut = item.getAlphabeticShortcut(); 1707 if (title != null && alphaShortcut != MIN_VALUE) { 1708 if (group == null) { 1709 final int resource = mApplication.getApplicationInfo().labelRes; 1710 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null); 1711 } 1712 group.addItem(new KeyboardShortcutInfo( 1713 title, alphaShortcut, KeyEvent.META_CTRL_ON)); 1714 } 1715 } 1716 if (group != null) { 1717 data.add(group); 1718 } 1719 } 1720 1721 /** 1722 * Ask to have the current assistant shown to the user. This only works if the calling 1723 * activity is the current foreground activity. It is the same as calling 1724 * {@link android.service.voice.VoiceInteractionService#showSession 1725 * VoiceInteractionService.showSession} and requesting all of the possible context. 1726 * The receiver will always see 1727 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set. 1728 * @return Returns true if the assistant was successfully invoked, else false. For example 1729 * false will be returned if the caller is not the current top activity. 1730 */ 1731 public boolean showAssist(Bundle args) { 1732 try { 1733 return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args); 1734 } catch (RemoteException e) { 1735 } 1736 return false; 1737 } 1738 1739 /** 1740 * Called when you are no longer visible to the user. You will next 1741 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing, 1742 * depending on later user activity. 1743 * 1744 * <p>Note that this method may never be called, in low memory situations 1745 * where the system does not have enough memory to keep your activity's 1746 * process running after its {@link #onPause} method is called. 1747 * 1748 * <p><em>Derived classes must call through to the super class's 1749 * implementation of this method. If they do not, an exception will be 1750 * thrown.</em></p> 1751 * 1752 * @see #onRestart 1753 * @see #onResume 1754 * @see #onSaveInstanceState 1755 * @see #onDestroy 1756 */ 1757 @CallSuper 1758 protected void onStop() { 1759 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this); 1760 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false); 1761 mActivityTransitionState.onStop(); 1762 getApplication().dispatchActivityStopped(this); 1763 mTranslucentCallback = null; 1764 mCalled = true; 1765 } 1766 1767 /** 1768 * Perform any final cleanup before an activity is destroyed. This can 1769 * happen either because the activity is finishing (someone called 1770 * {@link #finish} on it, or because the system is temporarily destroying 1771 * this instance of the activity to save space. You can distinguish 1772 * between these two scenarios with the {@link #isFinishing} method. 1773 * 1774 * <p><em>Note: do not count on this method being called as a place for 1775 * saving data! For example, if an activity is editing data in a content 1776 * provider, those edits should be committed in either {@link #onPause} or 1777 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to 1778 * free resources like threads that are associated with an activity, so 1779 * that a destroyed activity does not leave such things around while the 1780 * rest of its application is still running. There are situations where 1781 * the system will simply kill the activity's hosting process without 1782 * calling this method (or any others) in it, so it should not be used to 1783 * do things that are intended to remain around after the process goes 1784 * away. 1785 * 1786 * <p><em>Derived classes must call through to the super class's 1787 * implementation of this method. If they do not, an exception will be 1788 * thrown.</em></p> 1789 * 1790 * @see #onPause 1791 * @see #onStop 1792 * @see #finish 1793 * @see #isFinishing 1794 */ 1795 @CallSuper 1796 protected void onDestroy() { 1797 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this); 1798 mCalled = true; 1799 1800 // dismiss any dialogs we are managing. 1801 if (mManagedDialogs != null) { 1802 final int numDialogs = mManagedDialogs.size(); 1803 for (int i = 0; i < numDialogs; i++) { 1804 final ManagedDialog md = mManagedDialogs.valueAt(i); 1805 if (md.mDialog.isShowing()) { 1806 md.mDialog.dismiss(); 1807 } 1808 } 1809 mManagedDialogs = null; 1810 } 1811 1812 // close any cursors we are managing. 1813 synchronized (mManagedCursors) { 1814 int numCursors = mManagedCursors.size(); 1815 for (int i = 0; i < numCursors; i++) { 1816 ManagedCursor c = mManagedCursors.get(i); 1817 if (c != null) { 1818 c.mCursor.close(); 1819 } 1820 } 1821 mManagedCursors.clear(); 1822 } 1823 1824 // Close any open search dialog 1825 if (mSearchManager != null) { 1826 mSearchManager.stopSearch(); 1827 } 1828 1829 if (mActionBar != null) { 1830 mActionBar.onDestroy(); 1831 } 1832 1833 getApplication().dispatchActivityDestroyed(this); 1834 } 1835 1836 /** 1837 * Report to the system that your app is now fully drawn, purely for diagnostic 1838 * purposes (calling it does not impact the visible behavior of the activity). 1839 * This is only used to help instrument application launch times, so that the 1840 * app can report when it is fully in a usable state; without this, the only thing 1841 * the system itself can determine is the point at which the activity's window 1842 * is <em>first</em> drawn and displayed. To participate in app launch time 1843 * measurement, you should always call this method after first launch (when 1844 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have 1845 * entirely drawn your UI and populated with all of the significant data. You 1846 * can safely call this method any time after first launch as well, in which case 1847 * it will simply be ignored. 1848 */ 1849 public void reportFullyDrawn() { 1850 if (mDoReportFullyDrawn) { 1851 mDoReportFullyDrawn = false; 1852 try { 1853 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken); 1854 } catch (RemoteException e) { 1855 } 1856 } 1857 } 1858 1859 /** 1860 * Called by the system when the activity changes from fullscreen mode to multi-window mode and 1861 * visa-versa. 1862 * @see android.R.attr#resizeableActivity 1863 * 1864 * @param isInMultiWindowMode True if the activity is in multi-window mode. 1865 */ 1866 @CallSuper 1867 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) { 1868 if (DEBUG_LIFECYCLE) Slog.v(TAG, 1869 "onMultiWindowModeChanged " + this + ": " + isInMultiWindowMode); 1870 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode); 1871 if (mWindow != null) { 1872 mWindow.onMultiWindowModeChanged(); 1873 } 1874 } 1875 1876 /** 1877 * Returns true if the activity is currently in multi-window mode. 1878 * @see android.R.attr#resizeableActivity 1879 * 1880 * @return True if the activity is in multi-window mode. 1881 */ 1882 public boolean isInMultiWindowMode() { 1883 try { 1884 return ActivityManagerNative.getDefault().isInMultiWindowMode(mToken); 1885 } catch (RemoteException e) { 1886 } 1887 return false; 1888 } 1889 1890 /** 1891 * Called by the system when the activity changes to and from picture-in-picture mode. 1892 * @see android.R.attr#supportsPictureInPicture 1893 * 1894 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode. 1895 */ 1896 @CallSuper 1897 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) { 1898 if (DEBUG_LIFECYCLE) Slog.v(TAG, 1899 "onPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode); 1900 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode); 1901 } 1902 1903 /** 1904 * Returns true if the activity is currently in picture-in-picture mode. 1905 * @see android.R.attr#supportsPictureInPicture 1906 * 1907 * @return True if the activity is in picture-in-picture mode. 1908 */ 1909 public boolean isInPictureInPictureMode() { 1910 try { 1911 return ActivityManagerNative.getDefault().isInPictureInPictureMode(mToken); 1912 } catch (RemoteException e) { 1913 } 1914 return false; 1915 } 1916 1917 /** 1918 * Puts the activity in picture-in-picture mode. 1919 * @see android.R.attr#supportsPictureInPicture 1920 */ 1921 public void enterPictureInPictureMode() { 1922 try { 1923 ActivityManagerNative.getDefault().enterPictureInPictureMode(mToken); 1924 } catch (RemoteException e) { 1925 } 1926 } 1927 1928 /** 1929 * Called by the system when the device configuration changes while your 1930 * activity is running. Note that this will <em>only</em> be called if 1931 * you have selected configurations you would like to handle with the 1932 * {@link android.R.attr#configChanges} attribute in your manifest. If 1933 * any configuration change occurs that is not selected to be reported 1934 * by that attribute, then instead of reporting it the system will stop 1935 * and restart the activity (to have it launched with the new 1936 * configuration). 1937 * 1938 * <p>At the time that this function has been called, your Resources 1939 * object will have been updated to return resource values matching the 1940 * new configuration. 1941 * 1942 * @param newConfig The new device configuration. 1943 */ 1944 public void onConfigurationChanged(Configuration newConfig) { 1945 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig); 1946 mCalled = true; 1947 1948 mFragments.dispatchConfigurationChanged(newConfig); 1949 1950 if (mWindow != null) { 1951 // Pass the configuration changed event to the window 1952 mWindow.onConfigurationChanged(newConfig); 1953 } 1954 1955 if (mActionBar != null) { 1956 // Do this last; the action bar will need to access 1957 // view changes from above. 1958 mActionBar.onConfigurationChanged(newConfig); 1959 } 1960 } 1961 1962 /** 1963 * If this activity is being destroyed because it can not handle a 1964 * configuration parameter being changed (and thus its 1965 * {@link #onConfigurationChanged(Configuration)} method is 1966 * <em>not</em> being called), then you can use this method to discover 1967 * the set of changes that have occurred while in the process of being 1968 * destroyed. Note that there is no guarantee that these will be 1969 * accurate (other changes could have happened at any time), so you should 1970 * only use this as an optimization hint. 1971 * 1972 * @return Returns a bit field of the configuration parameters that are 1973 * changing, as defined by the {@link android.content.res.Configuration} 1974 * class. 1975 */ 1976 public int getChangingConfigurations() { 1977 return mConfigChangeFlags; 1978 } 1979 1980 /** 1981 * Retrieve the non-configuration instance data that was previously 1982 * returned by {@link #onRetainNonConfigurationInstance()}. This will 1983 * be available from the initial {@link #onCreate} and 1984 * {@link #onStart} calls to the new instance, allowing you to extract 1985 * any useful dynamic state from the previous instance. 1986 * 1987 * <p>Note that the data you retrieve here should <em>only</em> be used 1988 * as an optimization for handling configuration changes. You should always 1989 * be able to handle getting a null pointer back, and an activity must 1990 * still be able to restore itself to its previous state (through the 1991 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this 1992 * function returns null. 1993 * 1994 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API 1995 * {@link Fragment#setRetainInstance(boolean)} instead; this is also 1996 * available on older platforms through the Android support libraries. 1997 * 1998 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()} 1999 */ 2000 @Nullable 2001 public Object getLastNonConfigurationInstance() { 2002 return mLastNonConfigurationInstances != null 2003 ? mLastNonConfigurationInstances.activity : null; 2004 } 2005 2006 /** 2007 * Called by the system, as part of destroying an 2008 * activity due to a configuration change, when it is known that a new 2009 * instance will immediately be created for the new configuration. You 2010 * can return any object you like here, including the activity instance 2011 * itself, which can later be retrieved by calling 2012 * {@link #getLastNonConfigurationInstance()} in the new activity 2013 * instance. 2014 * 2015 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2016 * or later, consider instead using a {@link Fragment} with 2017 * {@link Fragment#setRetainInstance(boolean) 2018 * Fragment.setRetainInstance(boolean}.</em> 2019 * 2020 * <p>This function is called purely as an optimization, and you must 2021 * not rely on it being called. When it is called, a number of guarantees 2022 * will be made to help optimize configuration switching: 2023 * <ul> 2024 * <li> The function will be called between {@link #onStop} and 2025 * {@link #onDestroy}. 2026 * <li> A new instance of the activity will <em>always</em> be immediately 2027 * created after this one's {@link #onDestroy()} is called. In particular, 2028 * <em>no</em> messages will be dispatched during this time (when the returned 2029 * object does not have an activity to be associated with). 2030 * <li> The object you return here will <em>always</em> be available from 2031 * the {@link #getLastNonConfigurationInstance()} method of the following 2032 * activity instance as described there. 2033 * </ul> 2034 * 2035 * <p>These guarantees are designed so that an activity can use this API 2036 * to propagate extensive state from the old to new activity instance, from 2037 * loaded bitmaps, to network connections, to evenly actively running 2038 * threads. Note that you should <em>not</em> propagate any data that 2039 * may change based on the configuration, including any data loaded from 2040 * resources such as strings, layouts, or drawables. 2041 * 2042 * <p>The guarantee of no message handling during the switch to the next 2043 * activity simplifies use with active objects. For example if your retained 2044 * state is an {@link android.os.AsyncTask} you are guaranteed that its 2045 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will 2046 * not be called from the call here until you execute the next instance's 2047 * {@link #onCreate(Bundle)}. (Note however that there is of course no such 2048 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is 2049 * running in a separate thread.) 2050 * 2051 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API 2052 * {@link Fragment#setRetainInstance(boolean)} instead; this is also 2053 * available on older platforms through the Android support libraries. 2054 * 2055 * @return any Object holding the desired state to propagate to the 2056 * next activity instance 2057 */ 2058 public Object onRetainNonConfigurationInstance() { 2059 return null; 2060 } 2061 2062 /** 2063 * Retrieve the non-configuration instance data that was previously 2064 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will 2065 * be available from the initial {@link #onCreate} and 2066 * {@link #onStart} calls to the new instance, allowing you to extract 2067 * any useful dynamic state from the previous instance. 2068 * 2069 * <p>Note that the data you retrieve here should <em>only</em> be used 2070 * as an optimization for handling configuration changes. You should always 2071 * be able to handle getting a null pointer back, and an activity must 2072 * still be able to restore itself to its previous state (through the 2073 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this 2074 * function returns null. 2075 * 2076 * @return Returns the object previously returned by 2077 * {@link #onRetainNonConfigurationChildInstances()} 2078 */ 2079 @Nullable 2080 HashMap<String, Object> getLastNonConfigurationChildInstances() { 2081 return mLastNonConfigurationInstances != null 2082 ? mLastNonConfigurationInstances.children : null; 2083 } 2084 2085 /** 2086 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that 2087 * it should return either a mapping from child activity id strings to arbitrary objects, 2088 * or null. This method is intended to be used by Activity framework subclasses that control a 2089 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply 2090 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null. 2091 */ 2092 @Nullable 2093 HashMap<String,Object> onRetainNonConfigurationChildInstances() { 2094 return null; 2095 } 2096 2097 NonConfigurationInstances retainNonConfigurationInstances() { 2098 Object activity = onRetainNonConfigurationInstance(); 2099 HashMap<String, Object> children = onRetainNonConfigurationChildInstances(); 2100 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig(); 2101 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig(); 2102 if (activity == null && children == null && fragments == null && loaders == null 2103 && mVoiceInteractor == null) { 2104 return null; 2105 } 2106 2107 NonConfigurationInstances nci = new NonConfigurationInstances(); 2108 nci.activity = activity; 2109 nci.children = children; 2110 nci.fragments = fragments; 2111 nci.loaders = loaders; 2112 if (mVoiceInteractor != null) { 2113 mVoiceInteractor.retainInstance(); 2114 nci.voiceInteractor = mVoiceInteractor; 2115 } 2116 return nci; 2117 } 2118 2119 public void onLowMemory() { 2120 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this); 2121 mCalled = true; 2122 mFragments.dispatchLowMemory(); 2123 } 2124 2125 public void onTrimMemory(int level) { 2126 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level); 2127 mCalled = true; 2128 mFragments.dispatchTrimMemory(level); 2129 } 2130 2131 /** 2132 * Return the FragmentManager for interacting with fragments associated 2133 * with this activity. 2134 */ 2135 public FragmentManager getFragmentManager() { 2136 return mFragments.getFragmentManager(); 2137 } 2138 2139 /** 2140 * Called when a Fragment is being attached to this activity, immediately 2141 * after the call to its {@link Fragment#onAttach Fragment.onAttach()} 2142 * method and before {@link Fragment#onCreate Fragment.onCreate()}. 2143 */ 2144 public void onAttachFragment(Fragment fragment) { 2145 } 2146 2147 /** 2148 * Wrapper around 2149 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)} 2150 * that gives the resulting {@link Cursor} to call 2151 * {@link #startManagingCursor} so that the activity will manage its 2152 * lifecycle for you. 2153 * 2154 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2155 * or later, consider instead using {@link LoaderManager} instead, available 2156 * via {@link #getLoaderManager()}.</em> 2157 * 2158 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using 2159 * this method, because the activity will do that for you at the appropriate time. However, if 2160 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will 2161 * not</em> automatically close the cursor and, in that case, you must call 2162 * {@link Cursor#close()}.</p> 2163 * 2164 * @param uri The URI of the content provider to query. 2165 * @param projection List of columns to return. 2166 * @param selection SQL WHERE clause. 2167 * @param sortOrder SQL ORDER BY clause. 2168 * 2169 * @return The Cursor that was returned by query(). 2170 * 2171 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) 2172 * @see #startManagingCursor 2173 * @hide 2174 * 2175 * @deprecated Use {@link CursorLoader} instead. 2176 */ 2177 @Deprecated 2178 public final Cursor managedQuery(Uri uri, String[] projection, String selection, 2179 String sortOrder) { 2180 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder); 2181 if (c != null) { 2182 startManagingCursor(c); 2183 } 2184 return c; 2185 } 2186 2187 /** 2188 * Wrapper around 2189 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)} 2190 * that gives the resulting {@link Cursor} to call 2191 * {@link #startManagingCursor} so that the activity will manage its 2192 * lifecycle for you. 2193 * 2194 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2195 * or later, consider instead using {@link LoaderManager} instead, available 2196 * via {@link #getLoaderManager()}.</em> 2197 * 2198 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using 2199 * this method, because the activity will do that for you at the appropriate time. However, if 2200 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will 2201 * not</em> automatically close the cursor and, in that case, you must call 2202 * {@link Cursor#close()}.</p> 2203 * 2204 * @param uri The URI of the content provider to query. 2205 * @param projection List of columns to return. 2206 * @param selection SQL WHERE clause. 2207 * @param selectionArgs The arguments to selection, if any ?s are pesent 2208 * @param sortOrder SQL ORDER BY clause. 2209 * 2210 * @return The Cursor that was returned by query(). 2211 * 2212 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) 2213 * @see #startManagingCursor 2214 * 2215 * @deprecated Use {@link CursorLoader} instead. 2216 */ 2217 @Deprecated 2218 public final Cursor managedQuery(Uri uri, String[] projection, String selection, 2219 String[] selectionArgs, String sortOrder) { 2220 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); 2221 if (c != null) { 2222 startManagingCursor(c); 2223 } 2224 return c; 2225 } 2226 2227 /** 2228 * This method allows the activity to take care of managing the given 2229 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle. 2230 * That is, when the activity is stopped it will automatically call 2231 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 2232 * it will call {@link Cursor#requery} for you. When the activity is 2233 * destroyed, all managed Cursors will be closed automatically. 2234 * 2235 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 2236 * or later, consider instead using {@link LoaderManager} instead, available 2237 * via {@link #getLoaderManager()}.</em> 2238 * 2239 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from 2240 * {@link #managedQuery}, because the activity will do that for you at the appropriate time. 2241 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system 2242 * <em>will not</em> automatically close the cursor and, in that case, you must call 2243 * {@link Cursor#close()}.</p> 2244 * 2245 * @param c The Cursor to be managed. 2246 * 2247 * @see #managedQuery(android.net.Uri , String[], String, String[], String) 2248 * @see #stopManagingCursor 2249 * 2250 * @deprecated Use the new {@link android.content.CursorLoader} class with 2251 * {@link LoaderManager} instead; this is also 2252 * available on older platforms through the Android compatibility package. 2253 */ 2254 @Deprecated 2255 public void startManagingCursor(Cursor c) { 2256 synchronized (mManagedCursors) { 2257 mManagedCursors.add(new ManagedCursor(c)); 2258 } 2259 } 2260 2261 /** 2262 * Given a Cursor that was previously given to 2263 * {@link #startManagingCursor}, stop the activity's management of that 2264 * cursor. 2265 * 2266 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query, 2267 * the system <em>will not</em> automatically close the cursor and you must call 2268 * {@link Cursor#close()}.</p> 2269 * 2270 * @param c The Cursor that was being managed. 2271 * 2272 * @see #startManagingCursor 2273 * 2274 * @deprecated Use the new {@link android.content.CursorLoader} class with 2275 * {@link LoaderManager} instead; this is also 2276 * available on older platforms through the Android compatibility package. 2277 */ 2278 @Deprecated 2279 public void stopManagingCursor(Cursor c) { 2280 synchronized (mManagedCursors) { 2281 final int N = mManagedCursors.size(); 2282 for (int i=0; i<N; i++) { 2283 ManagedCursor mc = mManagedCursors.get(i); 2284 if (mc.mCursor == c) { 2285 mManagedCursors.remove(i); 2286 break; 2287 } 2288 } 2289 } 2290 } 2291 2292 /** 2293 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD} 2294 * this is a no-op. 2295 * @hide 2296 */ 2297 @Deprecated 2298 public void setPersistent(boolean isPersistent) { 2299 } 2300 2301 /** 2302 * Finds a view that was identified by the id attribute from the XML that 2303 * was processed in {@link #onCreate}. 2304 * 2305 * @return The view if found or null otherwise. 2306 */ 2307 @Nullable 2308 public View findViewById(@IdRes int id) { 2309 return getWindow().findViewById(id); 2310 } 2311 2312 /** 2313 * Retrieve a reference to this activity's ActionBar. 2314 * 2315 * @return The Activity's ActionBar, or null if it does not have one. 2316 */ 2317 @Nullable 2318 public ActionBar getActionBar() { 2319 initWindowDecorActionBar(); 2320 return mActionBar; 2321 } 2322 2323 /** 2324 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this 2325 * Activity window. 2326 * 2327 * <p>When set to a non-null value the {@link #getActionBar()} method will return 2328 * an {@link ActionBar} object that can be used to control the given toolbar as if it were 2329 * a traditional window decor action bar. The toolbar's menu will be populated with the 2330 * Activity's options menu and the navigation button will be wired through the standard 2331 * {@link android.R.id#home home} menu select action.</p> 2332 * 2333 * <p>In order to use a Toolbar within the Activity's window content the application 2334 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p> 2335 * 2336 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it 2337 */ 2338 public void setActionBar(@Nullable Toolbar toolbar) { 2339 final ActionBar ab = getActionBar(); 2340 if (ab instanceof WindowDecorActionBar) { 2341 throw new IllegalStateException("This Activity already has an action bar supplied " + 2342 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " + 2343 "android:windowActionBar to false in your theme to use a Toolbar instead."); 2344 } 2345 2346 // If we reach here then we're setting a new action bar 2347 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar 2348 mMenuInflater = null; 2349 2350 // If we have an action bar currently, destroy it 2351 if (ab != null) { 2352 ab.onDestroy(); 2353 } 2354 2355 if (toolbar != null) { 2356 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this); 2357 mActionBar = tbab; 2358 mWindow.setCallback(tbab.getWrappedWindowCallback()); 2359 } else { 2360 mActionBar = null; 2361 // Re-set the original window callback since we may have already set a Toolbar wrapper 2362 mWindow.setCallback(this); 2363 } 2364 2365 invalidateOptionsMenu(); 2366 } 2367 2368 /** 2369 * Creates a new ActionBar, locates the inflated ActionBarView, 2370 * initializes the ActionBar with the view, and sets mActionBar. 2371 */ 2372 private void initWindowDecorActionBar() { 2373 Window window = getWindow(); 2374 2375 // Initializing the window decor can change window feature flags. 2376 // Make sure that we have the correct set before performing the test below. 2377 window.getDecorView(); 2378 2379 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) { 2380 return; 2381 } 2382 2383 mActionBar = new WindowDecorActionBar(this); 2384 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp); 2385 2386 mWindow.setDefaultIcon(mActivityInfo.getIconResource()); 2387 mWindow.setDefaultLogo(mActivityInfo.getLogoResource()); 2388 } 2389 2390 /** 2391 * Set the activity content from a layout resource. The resource will be 2392 * inflated, adding all top-level views to the activity. 2393 * 2394 * @param layoutResID Resource ID to be inflated. 2395 * 2396 * @see #setContentView(android.view.View) 2397 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 2398 */ 2399 public void setContentView(@LayoutRes int layoutResID) { 2400 getWindow().setContentView(layoutResID); 2401 initWindowDecorActionBar(); 2402 } 2403 2404 /** 2405 * Set the activity content to an explicit view. This view is placed 2406 * directly into the activity's view hierarchy. It can itself be a complex 2407 * view hierarchy. When calling this method, the layout parameters of the 2408 * specified view are ignored. Both the width and the height of the view are 2409 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use 2410 * your own layout parameters, invoke 2411 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} 2412 * instead. 2413 * 2414 * @param view The desired content to display. 2415 * 2416 * @see #setContentView(int) 2417 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) 2418 */ 2419 public void setContentView(View view) { 2420 getWindow().setContentView(view); 2421 initWindowDecorActionBar(); 2422 } 2423 2424 /** 2425 * Set the activity content to an explicit view. This view is placed 2426 * directly into the activity's view hierarchy. It can itself be a complex 2427 * view hierarchy. 2428 * 2429 * @param view The desired content to display. 2430 * @param params Layout parameters for the view. 2431 * 2432 * @see #setContentView(android.view.View) 2433 * @see #setContentView(int) 2434 */ 2435 public void setContentView(View view, ViewGroup.LayoutParams params) { 2436 getWindow().setContentView(view, params); 2437 initWindowDecorActionBar(); 2438 } 2439 2440 /** 2441 * Add an additional content view to the activity. Added after any existing 2442 * ones in the activity -- existing views are NOT removed. 2443 * 2444 * @param view The desired content to display. 2445 * @param params Layout parameters for the view. 2446 */ 2447 public void addContentView(View view, ViewGroup.LayoutParams params) { 2448 getWindow().addContentView(view, params); 2449 initWindowDecorActionBar(); 2450 } 2451 2452 /** 2453 * Retrieve the {@link TransitionManager} responsible for default transitions in this window. 2454 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}. 2455 * 2456 * <p>This method will return non-null after content has been initialized (e.g. by using 2457 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p> 2458 * 2459 * @return This window's content TransitionManager or null if none is set. 2460 */ 2461 public TransitionManager getContentTransitionManager() { 2462 return getWindow().getTransitionManager(); 2463 } 2464 2465 /** 2466 * Set the {@link TransitionManager} to use for default transitions in this window. 2467 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}. 2468 * 2469 * @param tm The TransitionManager to use for scene changes. 2470 */ 2471 public void setContentTransitionManager(TransitionManager tm) { 2472 getWindow().setTransitionManager(tm); 2473 } 2474 2475 /** 2476 * Retrieve the {@link Scene} representing this window's current content. 2477 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}. 2478 * 2479 * <p>This method will return null if the current content is not represented by a Scene.</p> 2480 * 2481 * @return Current Scene being shown or null 2482 */ 2483 public Scene getContentScene() { 2484 return getWindow().getContentScene(); 2485 } 2486 2487 /** 2488 * Sets whether this activity is finished when touched outside its window's 2489 * bounds. 2490 */ 2491 public void setFinishOnTouchOutside(boolean finish) { 2492 mWindow.setCloseOnTouchOutside(finish); 2493 } 2494 2495 /** @hide */ 2496 @IntDef({ 2497 DEFAULT_KEYS_DISABLE, 2498 DEFAULT_KEYS_DIALER, 2499 DEFAULT_KEYS_SHORTCUT, 2500 DEFAULT_KEYS_SEARCH_LOCAL, 2501 DEFAULT_KEYS_SEARCH_GLOBAL}) 2502 @Retention(RetentionPolicy.SOURCE) 2503 @interface DefaultKeyMode {} 2504 2505 /** 2506 * Use with {@link #setDefaultKeyMode} to turn off default handling of 2507 * keys. 2508 * 2509 * @see #setDefaultKeyMode 2510 */ 2511 static public final int DEFAULT_KEYS_DISABLE = 0; 2512 /** 2513 * Use with {@link #setDefaultKeyMode} to launch the dialer during default 2514 * key handling. 2515 * 2516 * @see #setDefaultKeyMode 2517 */ 2518 static public final int DEFAULT_KEYS_DIALER = 1; 2519 /** 2520 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in 2521 * default key handling. 2522 * 2523 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts. 2524 * 2525 * @see #setDefaultKeyMode 2526 */ 2527 static public final int DEFAULT_KEYS_SHORTCUT = 2; 2528 /** 2529 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes 2530 * will start an application-defined search. (If the application or activity does not 2531 * actually define a search, the the keys will be ignored.) 2532 * 2533 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details. 2534 * 2535 * @see #setDefaultKeyMode 2536 */ 2537 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3; 2538 2539 /** 2540 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes 2541 * will start a global search (typically web search, but some platforms may define alternate 2542 * methods for global search) 2543 * 2544 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details. 2545 * 2546 * @see #setDefaultKeyMode 2547 */ 2548 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4; 2549 2550 /** 2551 * Select the default key handling for this activity. This controls what 2552 * will happen to key events that are not otherwise handled. The default 2553 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the 2554 * floor. Other modes allow you to launch the dialer 2555 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options 2556 * menu without requiring the menu key be held down 2557 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL} 2558 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}). 2559 * 2560 * <p>Note that the mode selected here does not impact the default 2561 * handling of system keys, such as the "back" and "menu" keys, and your 2562 * activity and its views always get a first chance to receive and handle 2563 * all application keys. 2564 * 2565 * @param mode The desired default key mode constant. 2566 * 2567 * @see #DEFAULT_KEYS_DISABLE 2568 * @see #DEFAULT_KEYS_DIALER 2569 * @see #DEFAULT_KEYS_SHORTCUT 2570 * @see #DEFAULT_KEYS_SEARCH_LOCAL 2571 * @see #DEFAULT_KEYS_SEARCH_GLOBAL 2572 * @see #onKeyDown 2573 */ 2574 public final void setDefaultKeyMode(@DefaultKeyMode int mode) { 2575 mDefaultKeyMode = mode; 2576 2577 // Some modes use a SpannableStringBuilder to track & dispatch input events 2578 // This list must remain in sync with the switch in onKeyDown() 2579 switch (mode) { 2580 case DEFAULT_KEYS_DISABLE: 2581 case DEFAULT_KEYS_SHORTCUT: 2582 mDefaultKeySsb = null; // not used in these modes 2583 break; 2584 case DEFAULT_KEYS_DIALER: 2585 case DEFAULT_KEYS_SEARCH_LOCAL: 2586 case DEFAULT_KEYS_SEARCH_GLOBAL: 2587 mDefaultKeySsb = new SpannableStringBuilder(); 2588 Selection.setSelection(mDefaultKeySsb,0); 2589 break; 2590 default: 2591 throw new IllegalArgumentException(); 2592 } 2593 } 2594 2595 /** 2596 * Called when a key was pressed down and not handled by any of the views 2597 * inside of the activity. So, for example, key presses while the cursor 2598 * is inside a TextView will not trigger the event (unless it is a navigation 2599 * to another object) because TextView handles its own key presses. 2600 * 2601 * <p>If the focused view didn't want this event, this method is called. 2602 * 2603 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK} 2604 * by calling {@link #onBackPressed()}, though the behavior varies based 2605 * on the application compatibility mode: for 2606 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications, 2607 * it will set up the dispatch to call {@link #onKeyUp} where the action 2608 * will be performed; for earlier applications, it will perform the 2609 * action immediately in on-down, as those versions of the platform 2610 * behaved. 2611 * 2612 * <p>Other additional default key handling may be performed 2613 * if configured with {@link #setDefaultKeyMode}. 2614 * 2615 * @return Return <code>true</code> to prevent this event from being propagated 2616 * further, or <code>false</code> to indicate that you have not handled 2617 * this event and it should continue to be propagated. 2618 * @see #onKeyUp 2619 * @see android.view.KeyEvent 2620 */ 2621 public boolean onKeyDown(int keyCode, KeyEvent event) { 2622 if (keyCode == KeyEvent.KEYCODE_BACK) { 2623 if (getApplicationInfo().targetSdkVersion 2624 >= Build.VERSION_CODES.ECLAIR) { 2625 event.startTracking(); 2626 } else { 2627 onBackPressed(); 2628 } 2629 return true; 2630 } 2631 2632 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) { 2633 return false; 2634 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) { 2635 Window w = getWindow(); 2636 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) && 2637 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event, 2638 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) { 2639 return true; 2640 } 2641 return false; 2642 } else { 2643 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_* 2644 boolean clearSpannable = false; 2645 boolean handled; 2646 if ((event.getRepeatCount() != 0) || event.isSystem()) { 2647 clearSpannable = true; 2648 handled = false; 2649 } else { 2650 handled = TextKeyListener.getInstance().onKeyDown( 2651 null, mDefaultKeySsb, keyCode, event); 2652 if (handled && mDefaultKeySsb.length() > 0) { 2653 // something useable has been typed - dispatch it now. 2654 2655 final String str = mDefaultKeySsb.toString(); 2656 clearSpannable = true; 2657 2658 switch (mDefaultKeyMode) { 2659 case DEFAULT_KEYS_DIALER: 2660 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str)); 2661 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2662 startActivity(intent); 2663 break; 2664 case DEFAULT_KEYS_SEARCH_LOCAL: 2665 startSearch(str, false, null, false); 2666 break; 2667 case DEFAULT_KEYS_SEARCH_GLOBAL: 2668 startSearch(str, false, null, true); 2669 break; 2670 } 2671 } 2672 } 2673 if (clearSpannable) { 2674 mDefaultKeySsb.clear(); 2675 mDefaultKeySsb.clearSpans(); 2676 Selection.setSelection(mDefaultKeySsb,0); 2677 } 2678 return handled; 2679 } 2680 } 2681 2682 /** 2683 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 2684 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 2685 * the event). 2686 */ 2687 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 2688 return false; 2689 } 2690 2691 /** 2692 * Called when a key was released and not handled by any of the views 2693 * inside of the activity. So, for example, key presses while the cursor 2694 * is inside a TextView will not trigger the event (unless it is a navigation 2695 * to another object) because TextView handles its own key presses. 2696 * 2697 * <p>The default implementation handles KEYCODE_BACK to stop the activity 2698 * and go back. 2699 * 2700 * @return Return <code>true</code> to prevent this event from being propagated 2701 * further, or <code>false</code> to indicate that you have not handled 2702 * this event and it should continue to be propagated. 2703 * @see #onKeyDown 2704 * @see KeyEvent 2705 */ 2706 public boolean onKeyUp(int keyCode, KeyEvent event) { 2707 if (getApplicationInfo().targetSdkVersion 2708 >= Build.VERSION_CODES.ECLAIR) { 2709 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() 2710 && !event.isCanceled()) { 2711 onBackPressed(); 2712 return true; 2713 } 2714 } 2715 return false; 2716 } 2717 2718 /** 2719 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 2720 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 2721 * the event). 2722 */ 2723 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 2724 return false; 2725 } 2726 2727 /** 2728 * Called when the activity has detected the user's press of the back 2729 * key. The default implementation simply finishes the current activity, 2730 * but you can override this to do whatever you want. 2731 */ 2732 public void onBackPressed() { 2733 if (mActionBar != null && mActionBar.collapseActionView()) { 2734 return; 2735 } 2736 2737 if (!mFragments.getFragmentManager().popBackStackImmediate()) { 2738 finishAfterTransition(); 2739 } 2740 } 2741 2742 /** 2743 * Called when a key shortcut event is not handled by any of the views in the Activity. 2744 * Override this method to implement global key shortcuts for the Activity. 2745 * Key shortcuts can also be implemented by setting the 2746 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 2747 * 2748 * @param keyCode The value in event.getKeyCode(). 2749 * @param event Description of the key event. 2750 * @return True if the key shortcut was handled. 2751 */ 2752 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 2753 // Let the Action Bar have a chance at handling the shortcut. 2754 ActionBar actionBar = getActionBar(); 2755 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event)); 2756 } 2757 2758 /** 2759 * Called when a touch screen event was not handled by any of the views 2760 * under it. This is most useful to process touch events that happen 2761 * outside of your window bounds, where there is no view to receive it. 2762 * 2763 * @param event The touch screen event being processed. 2764 * 2765 * @return Return true if you have consumed the event, false if you haven't. 2766 * The default implementation always returns false. 2767 */ 2768 public boolean onTouchEvent(MotionEvent event) { 2769 if (mWindow.shouldCloseOnTouch(this, event)) { 2770 finish(); 2771 return true; 2772 } 2773 2774 return false; 2775 } 2776 2777 /** 2778 * Called when the trackball was moved and not handled by any of the 2779 * views inside of the activity. So, for example, if the trackball moves 2780 * while focus is on a button, you will receive a call here because 2781 * buttons do not normally do anything with trackball events. The call 2782 * here happens <em>before</em> trackball movements are converted to 2783 * DPAD key events, which then get sent back to the view hierarchy, and 2784 * will be processed at the point for things like focus navigation. 2785 * 2786 * @param event The trackball event being processed. 2787 * 2788 * @return Return true if you have consumed the event, false if you haven't. 2789 * The default implementation always returns false. 2790 */ 2791 public boolean onTrackballEvent(MotionEvent event) { 2792 return false; 2793 } 2794 2795 /** 2796 * Called when a generic motion event was not handled by any of the 2797 * views inside of the activity. 2798 * <p> 2799 * Generic motion events describe joystick movements, mouse hovers, track pad 2800 * touches, scroll wheel movements and other input events. The 2801 * {@link MotionEvent#getSource() source} of the motion event specifies 2802 * the class of input that was received. Implementations of this method 2803 * must examine the bits in the source before processing the event. 2804 * The following code example shows how this is done. 2805 * </p><p> 2806 * Generic motion events with source class 2807 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER} 2808 * are delivered to the view under the pointer. All other generic motion events are 2809 * delivered to the focused view. 2810 * </p><p> 2811 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to 2812 * handle this event. 2813 * </p> 2814 * 2815 * @param event The generic motion event being processed. 2816 * 2817 * @return Return true if you have consumed the event, false if you haven't. 2818 * The default implementation always returns false. 2819 */ 2820 public boolean onGenericMotionEvent(MotionEvent event) { 2821 return false; 2822 } 2823 2824 /** 2825 * Called whenever a key, touch, or trackball event is dispatched to the 2826 * activity. Implement this method if you wish to know that the user has 2827 * interacted with the device in some way while your activity is running. 2828 * This callback and {@link #onUserLeaveHint} are intended to help 2829 * activities manage status bar notifications intelligently; specifically, 2830 * for helping activities determine the proper time to cancel a notfication. 2831 * 2832 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will 2833 * be accompanied by calls to {@link #onUserInteraction}. This 2834 * ensures that your activity will be told of relevant user activity such 2835 * as pulling down the notification pane and touching an item there. 2836 * 2837 * <p>Note that this callback will be invoked for the touch down action 2838 * that begins a touch gesture, but may not be invoked for the touch-moved 2839 * and touch-up actions that follow. 2840 * 2841 * @see #onUserLeaveHint() 2842 */ 2843 public void onUserInteraction() { 2844 } 2845 2846 public void onWindowAttributesChanged(WindowManager.LayoutParams params) { 2847 // Update window manager if: we have a view, that view is 2848 // attached to its parent (which will be a RootView), and 2849 // this activity is not embedded. 2850 if (mParent == null) { 2851 View decor = mDecor; 2852 if (decor != null && decor.getParent() != null) { 2853 getWindowManager().updateViewLayout(decor, params); 2854 } 2855 } 2856 } 2857 2858 public void onContentChanged() { 2859 } 2860 2861 /** 2862 * Called when the current {@link Window} of the activity gains or loses 2863 * focus. This is the best indicator of whether this activity is visible 2864 * to the user. The default implementation clears the key tracking 2865 * state, so should always be called. 2866 * 2867 * <p>Note that this provides information about global focus state, which 2868 * is managed independently of activity lifecycles. As such, while focus 2869 * changes will generally have some relation to lifecycle changes (an 2870 * activity that is stopped will not generally get window focus), you 2871 * should not rely on any particular order between the callbacks here and 2872 * those in the other lifecycle methods such as {@link #onResume}. 2873 * 2874 * <p>As a general rule, however, a resumed activity will have window 2875 * focus... unless it has displayed other dialogs or popups that take 2876 * input focus, in which case the activity itself will not have focus 2877 * when the other windows have it. Likewise, the system may display 2878 * system-level windows (such as the status bar notification panel or 2879 * a system alert) which will temporarily take window input focus without 2880 * pausing the foreground activity. 2881 * 2882 * @param hasFocus Whether the window of this activity has focus. 2883 * 2884 * @see #hasWindowFocus() 2885 * @see #onResume 2886 * @see View#onWindowFocusChanged(boolean) 2887 */ 2888 public void onWindowFocusChanged(boolean hasFocus) { 2889 } 2890 2891 /** 2892 * Called when the main window associated with the activity has been 2893 * attached to the window manager. 2894 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()} 2895 * for more information. 2896 * @see View#onAttachedToWindow 2897 */ 2898 public void onAttachedToWindow() { 2899 } 2900 2901 /** 2902 * Called when the main window associated with the activity has been 2903 * detached from the window manager. 2904 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()} 2905 * for more information. 2906 * @see View#onDetachedFromWindow 2907 */ 2908 public void onDetachedFromWindow() { 2909 } 2910 2911 /** 2912 * Returns true if this activity's <em>main</em> window currently has window focus. 2913 * Note that this is not the same as the view itself having focus. 2914 * 2915 * @return True if this activity's main window currently has window focus. 2916 * 2917 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams) 2918 */ 2919 public boolean hasWindowFocus() { 2920 Window w = getWindow(); 2921 if (w != null) { 2922 View d = w.getDecorView(); 2923 if (d != null) { 2924 return d.hasWindowFocus(); 2925 } 2926 } 2927 return false; 2928 } 2929 2930 /** 2931 * Called when the main window associated with the activity has been dismissed. 2932 * @hide 2933 */ 2934 @Override 2935 public void onWindowDismissed(boolean finishTask) { 2936 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY); 2937 } 2938 2939 2940 /** 2941 * Moves the activity from 2942 * {@link android.app.ActivityManager.StackId#FREEFORM_WORKSPACE_STACK_ID} to 2943 * {@link android.app.ActivityManager.StackId#FULLSCREEN_WORKSPACE_STACK_ID} stack. 2944 * 2945 * @hide 2946 */ 2947 @Override 2948 public void exitFreeformMode() throws RemoteException { 2949 ActivityManagerNative.getDefault().exitFreeformMode(mToken); 2950 } 2951 2952 /** Returns the current stack Id for the window. 2953 * @hide 2954 */ 2955 @Override 2956 public int getWindowStackId() throws RemoteException { 2957 return ActivityManagerNative.getDefault().getActivityStackId(mToken); 2958 } 2959 2960 /** 2961 * Called to process key events. You can override this to intercept all 2962 * key events before they are dispatched to the window. Be sure to call 2963 * this implementation for key events that should be handled normally. 2964 * 2965 * @param event The key event. 2966 * 2967 * @return boolean Return true if this event was consumed. 2968 */ 2969 public boolean dispatchKeyEvent(KeyEvent event) { 2970 onUserInteraction(); 2971 2972 // Let action bars open menus in response to the menu key prioritized over 2973 // the window handling it 2974 final int keyCode = event.getKeyCode(); 2975 if (keyCode == KeyEvent.KEYCODE_MENU && 2976 mActionBar != null && mActionBar.onMenuKeyEvent(event)) { 2977 return true; 2978 } else if (event.isCtrlPressed() && 2979 event.getUnicodeChar(event.getMetaState() & ~KeyEvent.META_CTRL_MASK) == '<') { 2980 // Capture the Control-< and send focus to the ActionBar 2981 final int action = event.getAction(); 2982 if (action == KeyEvent.ACTION_DOWN) { 2983 final ActionBar actionBar = getActionBar(); 2984 if (actionBar != null && actionBar.isShowing() && actionBar.requestFocus()) { 2985 mEatKeyUpEvent = true; 2986 return true; 2987 } 2988 } else if (action == KeyEvent.ACTION_UP && mEatKeyUpEvent) { 2989 mEatKeyUpEvent = false; 2990 return true; 2991 } 2992 } 2993 2994 Window win = getWindow(); 2995 if (win.superDispatchKeyEvent(event)) { 2996 return true; 2997 } 2998 View decor = mDecor; 2999 if (decor == null) decor = win.getDecorView(); 3000 return event.dispatch(this, decor != null 3001 ? decor.getKeyDispatcherState() : null, this); 3002 } 3003 3004 /** 3005 * Called to process a key shortcut event. 3006 * You can override this to intercept all key shortcut events before they are 3007 * dispatched to the window. Be sure to call this implementation for key shortcut 3008 * events that should be handled normally. 3009 * 3010 * @param event The key shortcut event. 3011 * @return True if this event was consumed. 3012 */ 3013 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 3014 onUserInteraction(); 3015 if (getWindow().superDispatchKeyShortcutEvent(event)) { 3016 return true; 3017 } 3018 return onKeyShortcut(event.getKeyCode(), event); 3019 } 3020 3021 /** 3022 * Called to process touch screen events. You can override this to 3023 * intercept all touch screen events before they are dispatched to the 3024 * window. Be sure to call this implementation for touch screen events 3025 * that should be handled normally. 3026 * 3027 * @param ev The touch screen event. 3028 * 3029 * @return boolean Return true if this event was consumed. 3030 */ 3031 public boolean dispatchTouchEvent(MotionEvent ev) { 3032 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 3033 onUserInteraction(); 3034 } 3035 if (getWindow().superDispatchTouchEvent(ev)) { 3036 return true; 3037 } 3038 return onTouchEvent(ev); 3039 } 3040 3041 /** 3042 * Called to process trackball events. You can override this to 3043 * intercept all trackball events before they are dispatched to the 3044 * window. Be sure to call this implementation for trackball events 3045 * that should be handled normally. 3046 * 3047 * @param ev The trackball event. 3048 * 3049 * @return boolean Return true if this event was consumed. 3050 */ 3051 public boolean dispatchTrackballEvent(MotionEvent ev) { 3052 onUserInteraction(); 3053 if (getWindow().superDispatchTrackballEvent(ev)) { 3054 return true; 3055 } 3056 return onTrackballEvent(ev); 3057 } 3058 3059 /** 3060 * Called to process generic motion events. You can override this to 3061 * intercept all generic motion events before they are dispatched to the 3062 * window. Be sure to call this implementation for generic motion events 3063 * that should be handled normally. 3064 * 3065 * @param ev The generic motion event. 3066 * 3067 * @return boolean Return true if this event was consumed. 3068 */ 3069 public boolean dispatchGenericMotionEvent(MotionEvent ev) { 3070 onUserInteraction(); 3071 if (getWindow().superDispatchGenericMotionEvent(ev)) { 3072 return true; 3073 } 3074 return onGenericMotionEvent(ev); 3075 } 3076 3077 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 3078 event.setClassName(getClass().getName()); 3079 event.setPackageName(getPackageName()); 3080 3081 LayoutParams params = getWindow().getAttributes(); 3082 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) && 3083 (params.height == LayoutParams.MATCH_PARENT); 3084 event.setFullScreen(isFullScreen); 3085 3086 CharSequence title = getTitle(); 3087 if (!TextUtils.isEmpty(title)) { 3088 event.getText().add(title); 3089 } 3090 3091 return true; 3092 } 3093 3094 /** 3095 * Default implementation of 3096 * {@link android.view.Window.Callback#onCreatePanelView} 3097 * for activities. This 3098 * simply returns null so that all panel sub-windows will have the default 3099 * menu behavior. 3100 */ 3101 @Nullable 3102 public View onCreatePanelView(int featureId) { 3103 return null; 3104 } 3105 3106 /** 3107 * Default implementation of 3108 * {@link android.view.Window.Callback#onCreatePanelMenu} 3109 * for activities. This calls through to the new 3110 * {@link #onCreateOptionsMenu} method for the 3111 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel, 3112 * so that subclasses of Activity don't need to deal with feature codes. 3113 */ 3114 public boolean onCreatePanelMenu(int featureId, Menu menu) { 3115 if (featureId == Window.FEATURE_OPTIONS_PANEL) { 3116 boolean show = onCreateOptionsMenu(menu); 3117 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater()); 3118 return show; 3119 } 3120 return false; 3121 } 3122 3123 /** 3124 * Default implementation of 3125 * {@link android.view.Window.Callback#onPreparePanel} 3126 * for activities. This 3127 * calls through to the new {@link #onPrepareOptionsMenu} method for the 3128 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} 3129 * panel, so that subclasses of 3130 * Activity don't need to deal with feature codes. 3131 */ 3132 public boolean onPreparePanel(int featureId, View view, Menu menu) { 3133 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) { 3134 boolean goforit = onPrepareOptionsMenu(menu); 3135 goforit |= mFragments.dispatchPrepareOptionsMenu(menu); 3136 return goforit; 3137 } 3138 return true; 3139 } 3140 3141 /** 3142 * {@inheritDoc} 3143 * 3144 * @return The default implementation returns true. 3145 */ 3146 public boolean onMenuOpened(int featureId, Menu menu) { 3147 if (featureId == Window.FEATURE_ACTION_BAR) { 3148 initWindowDecorActionBar(); 3149 if (mActionBar != null) { 3150 mActionBar.dispatchMenuVisibilityChanged(true); 3151 } else { 3152 Log.e(TAG, "Tried to open action bar menu with no action bar"); 3153 } 3154 } 3155 return true; 3156 } 3157 3158 /** 3159 * Default implementation of 3160 * {@link android.view.Window.Callback#onMenuItemSelected} 3161 * for activities. This calls through to the new 3162 * {@link #onOptionsItemSelected} method for the 3163 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} 3164 * panel, so that subclasses of 3165 * Activity don't need to deal with feature codes. 3166 */ 3167 public boolean onMenuItemSelected(int featureId, MenuItem item) { 3168 CharSequence titleCondensed = item.getTitleCondensed(); 3169 3170 switch (featureId) { 3171 case Window.FEATURE_OPTIONS_PANEL: 3172 // Put event logging here so it gets called even if subclass 3173 // doesn't call through to superclass's implmeentation of each 3174 // of these methods below 3175 if(titleCondensed != null) { 3176 EventLog.writeEvent(50000, 0, titleCondensed.toString()); 3177 } 3178 if (onOptionsItemSelected(item)) { 3179 return true; 3180 } 3181 if (mFragments.dispatchOptionsItemSelected(item)) { 3182 return true; 3183 } 3184 if (item.getItemId() == android.R.id.home && mActionBar != null && 3185 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) { 3186 if (mParent == null) { 3187 return onNavigateUp(); 3188 } else { 3189 return mParent.onNavigateUpFromChild(this); 3190 } 3191 } 3192 return false; 3193 3194 case Window.FEATURE_CONTEXT_MENU: 3195 if(titleCondensed != null) { 3196 EventLog.writeEvent(50000, 1, titleCondensed.toString()); 3197 } 3198 if (onContextItemSelected(item)) { 3199 return true; 3200 } 3201 return mFragments.dispatchContextItemSelected(item); 3202 3203 default: 3204 return false; 3205 } 3206 } 3207 3208 /** 3209 * Default implementation of 3210 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for 3211 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)} 3212 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel, 3213 * so that subclasses of Activity don't need to deal with feature codes. 3214 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the 3215 * {@link #onContextMenuClosed(Menu)} will be called. 3216 */ 3217 public void onPanelClosed(int featureId, Menu menu) { 3218 switch (featureId) { 3219 case Window.FEATURE_OPTIONS_PANEL: 3220 mFragments.dispatchOptionsMenuClosed(menu); 3221 onOptionsMenuClosed(menu); 3222 break; 3223 3224 case Window.FEATURE_CONTEXT_MENU: 3225 onContextMenuClosed(menu); 3226 break; 3227 3228 case Window.FEATURE_ACTION_BAR: 3229 initWindowDecorActionBar(); 3230 mActionBar.dispatchMenuVisibilityChanged(false); 3231 break; 3232 } 3233 } 3234 3235 /** 3236 * Declare that the options menu has changed, so should be recreated. 3237 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next 3238 * time it needs to be displayed. 3239 */ 3240 public void invalidateOptionsMenu() { 3241 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) && 3242 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) { 3243 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); 3244 } 3245 } 3246 3247 /** 3248 * Initialize the contents of the Activity's standard options menu. You 3249 * should place your menu items in to <var>menu</var>. 3250 * 3251 * <p>This is only called once, the first time the options menu is 3252 * displayed. To update the menu every time it is displayed, see 3253 * {@link #onPrepareOptionsMenu}. 3254 * 3255 * <p>The default implementation populates the menu with standard system 3256 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that 3257 * they will be correctly ordered with application-defined menu items. 3258 * Deriving classes should always call through to the base implementation. 3259 * 3260 * <p>You can safely hold on to <var>menu</var> (and any items created 3261 * from it), making modifications to it as desired, until the next 3262 * time onCreateOptionsMenu() is called. 3263 * 3264 * <p>When you add items to the menu, you can implement the Activity's 3265 * {@link #onOptionsItemSelected} method to handle them there. 3266 * 3267 * @param menu The options menu in which you place your items. 3268 * 3269 * @return You must return true for the menu to be displayed; 3270 * if you return false it will not be shown. 3271 * 3272 * @see #onPrepareOptionsMenu 3273 * @see #onOptionsItemSelected 3274 */ 3275 public boolean onCreateOptionsMenu(Menu menu) { 3276 if (mParent != null) { 3277 return mParent.onCreateOptionsMenu(menu); 3278 } 3279 return true; 3280 } 3281 3282 /** 3283 * Prepare the Screen's standard options menu to be displayed. This is 3284 * called right before the menu is shown, every time it is shown. You can 3285 * use this method to efficiently enable/disable items or otherwise 3286 * dynamically modify the contents. 3287 * 3288 * <p>The default implementation updates the system menu items based on the 3289 * activity's state. Deriving classes should always call through to the 3290 * base class implementation. 3291 * 3292 * @param menu The options menu as last shown or first initialized by 3293 * onCreateOptionsMenu(). 3294 * 3295 * @return You must return true for the menu to be displayed; 3296 * if you return false it will not be shown. 3297 * 3298 * @see #onCreateOptionsMenu 3299 */ 3300 public boolean onPrepareOptionsMenu(Menu menu) { 3301 if (mParent != null) { 3302 return mParent.onPrepareOptionsMenu(menu); 3303 } 3304 return true; 3305 } 3306 3307 /** 3308 * This hook is called whenever an item in your options menu is selected. 3309 * The default implementation simply returns false to have the normal 3310 * processing happen (calling the item's Runnable or sending a message to 3311 * its Handler as appropriate). You can use this method for any items 3312 * for which you would like to do processing without those other 3313 * facilities. 3314 * 3315 * <p>Derived classes should call through to the base class for it to 3316 * perform the default menu handling.</p> 3317 * 3318 * @param item The menu item that was selected. 3319 * 3320 * @return boolean Return false to allow normal menu processing to 3321 * proceed, true to consume it here. 3322 * 3323 * @see #onCreateOptionsMenu 3324 */ 3325 public boolean onOptionsItemSelected(MenuItem item) { 3326 if (mParent != null) { 3327 return mParent.onOptionsItemSelected(item); 3328 } 3329 return false; 3330 } 3331 3332 /** 3333 * This method is called whenever the user chooses to navigate Up within your application's 3334 * activity hierarchy from the action bar. 3335 * 3336 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName} 3337 * was specified in the manifest for this activity or an activity-alias to it, 3338 * default Up navigation will be handled automatically. If any activity 3339 * along the parent chain requires extra Intent arguments, the Activity subclass 3340 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)} 3341 * to supply those arguments.</p> 3342 * 3343 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a> 3344 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> 3345 * from the design guide for more information about navigating within your app.</p> 3346 * 3347 * <p>See the {@link TaskStackBuilder} class and the Activity methods 3348 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and 3349 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation. 3350 * The AppNavigation sample application in the Android SDK is also available for reference.</p> 3351 * 3352 * @return true if Up navigation completed successfully and this Activity was finished, 3353 * false otherwise. 3354 */ 3355 public boolean onNavigateUp() { 3356 // Automatically handle hierarchical Up navigation if the proper 3357 // metadata is available. 3358 Intent upIntent = getParentActivityIntent(); 3359 if (upIntent != null) { 3360 if (mActivityInfo.taskAffinity == null) { 3361 // Activities with a null affinity are special; they really shouldn't 3362 // specify a parent activity intent in the first place. Just finish 3363 // the current activity and call it a day. 3364 finish(); 3365 } else if (shouldUpRecreateTask(upIntent)) { 3366 TaskStackBuilder b = TaskStackBuilder.create(this); 3367 onCreateNavigateUpTaskStack(b); 3368 onPrepareNavigateUpTaskStack(b); 3369 b.startActivities(); 3370 3371 // We can't finishAffinity if we have a result. 3372 // Fall back and simply finish the current activity instead. 3373 if (mResultCode != RESULT_CANCELED || mResultData != null) { 3374 // Tell the developer what's going on to avoid hair-pulling. 3375 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result"); 3376 finish(); 3377 } else { 3378 finishAffinity(); 3379 } 3380 } else { 3381 navigateUpTo(upIntent); 3382 } 3383 return true; 3384 } 3385 return false; 3386 } 3387 3388 /** 3389 * This is called when a child activity of this one attempts to navigate up. 3390 * The default implementation simply calls onNavigateUp() on this activity (the parent). 3391 * 3392 * @param child The activity making the call. 3393 */ 3394 public boolean onNavigateUpFromChild(Activity child) { 3395 return onNavigateUp(); 3396 } 3397 3398 /** 3399 * Define the synthetic task stack that will be generated during Up navigation from 3400 * a different task. 3401 * 3402 * <p>The default implementation of this method adds the parent chain of this activity 3403 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications 3404 * may choose to override this method to construct the desired task stack in a different 3405 * way.</p> 3406 * 3407 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()} 3408 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent 3409 * returned by {@link #getParentActivityIntent()}.</p> 3410 * 3411 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined 3412 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p> 3413 * 3414 * @param builder An empty TaskStackBuilder - the application should add intents representing 3415 * the desired task stack 3416 */ 3417 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) { 3418 builder.addParentStack(this); 3419 } 3420 3421 /** 3422 * Prepare the synthetic task stack that will be generated during Up navigation 3423 * from a different task. 3424 * 3425 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of 3426 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}. 3427 * If any extra data should be added to these intents before launching the new task, 3428 * the application should override this method and add that data here.</p> 3429 * 3430 * @param builder A TaskStackBuilder that has been populated with Intents by 3431 * onCreateNavigateUpTaskStack. 3432 */ 3433 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) { 3434 } 3435 3436 /** 3437 * This hook is called whenever the options menu is being closed (either by the user canceling 3438 * the menu with the back/menu button, or when an item is selected). 3439 * 3440 * @param menu The options menu as last shown or first initialized by 3441 * onCreateOptionsMenu(). 3442 */ 3443 public void onOptionsMenuClosed(Menu menu) { 3444 if (mParent != null) { 3445 mParent.onOptionsMenuClosed(menu); 3446 } 3447 } 3448 3449 /** 3450 * Programmatically opens the options menu. If the options menu is already 3451 * open, this method does nothing. 3452 */ 3453 public void openOptionsMenu() { 3454 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) && 3455 (mActionBar == null || !mActionBar.openOptionsMenu())) { 3456 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null); 3457 } 3458 } 3459 3460 /** 3461 * Progammatically closes the options menu. If the options menu is already 3462 * closed, this method does nothing. 3463 */ 3464 public void closeOptionsMenu() { 3465 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) { 3466 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL); 3467 } 3468 } 3469 3470 /** 3471 * Called when a context menu for the {@code view} is about to be shown. 3472 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every 3473 * time the context menu is about to be shown and should be populated for 3474 * the view (or item inside the view for {@link AdapterView} subclasses, 3475 * this can be found in the {@code menuInfo})). 3476 * <p> 3477 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an 3478 * item has been selected. 3479 * <p> 3480 * It is not safe to hold onto the context menu after this method returns. 3481 * 3482 */ 3483 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 3484 } 3485 3486 /** 3487 * Registers a context menu to be shown for the given view (multiple views 3488 * can show the context menu). This method will set the 3489 * {@link OnCreateContextMenuListener} on the view to this activity, so 3490 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be 3491 * called when it is time to show the context menu. 3492 * 3493 * @see #unregisterForContextMenu(View) 3494 * @param view The view that should show a context menu. 3495 */ 3496 public void registerForContextMenu(View view) { 3497 view.setOnCreateContextMenuListener(this); 3498 } 3499 3500 /** 3501 * Prevents a context menu to be shown for the given view. This method will remove the 3502 * {@link OnCreateContextMenuListener} on the view. 3503 * 3504 * @see #registerForContextMenu(View) 3505 * @param view The view that should stop showing a context menu. 3506 */ 3507 public void unregisterForContextMenu(View view) { 3508 view.setOnCreateContextMenuListener(null); 3509 } 3510 3511 /** 3512 * Programmatically opens the context menu for a particular {@code view}. 3513 * The {@code view} should have been added via 3514 * {@link #registerForContextMenu(View)}. 3515 * 3516 * @param view The view to show the context menu for. 3517 */ 3518 public void openContextMenu(View view) { 3519 view.showContextMenu(); 3520 } 3521 3522 /** 3523 * Programmatically closes the most recently opened context menu, if showing. 3524 */ 3525 public void closeContextMenu() { 3526 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) { 3527 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU); 3528 } 3529 } 3530 3531 /** 3532 * This hook is called whenever an item in a context menu is selected. The 3533 * default implementation simply returns false to have the normal processing 3534 * happen (calling the item's Runnable or sending a message to its Handler 3535 * as appropriate). You can use this method for any items for which you 3536 * would like to do processing without those other facilities. 3537 * <p> 3538 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the 3539 * View that added this menu item. 3540 * <p> 3541 * Derived classes should call through to the base class for it to perform 3542 * the default menu handling. 3543 * 3544 * @param item The context menu item that was selected. 3545 * @return boolean Return false to allow normal context menu processing to 3546 * proceed, true to consume it here. 3547 */ 3548 public boolean onContextItemSelected(MenuItem item) { 3549 if (mParent != null) { 3550 return mParent.onContextItemSelected(item); 3551 } 3552 return false; 3553 } 3554 3555 /** 3556 * This hook is called whenever the context menu is being closed (either by 3557 * the user canceling the menu with the back/menu button, or when an item is 3558 * selected). 3559 * 3560 * @param menu The context menu that is being closed. 3561 */ 3562 public void onContextMenuClosed(Menu menu) { 3563 if (mParent != null) { 3564 mParent.onContextMenuClosed(menu); 3565 } 3566 } 3567 3568 /** 3569 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}. 3570 */ 3571 @Deprecated 3572 protected Dialog onCreateDialog(int id) { 3573 return null; 3574 } 3575 3576 /** 3577 * Callback for creating dialogs that are managed (saved and restored) for you 3578 * by the activity. The default implementation calls through to 3579 * {@link #onCreateDialog(int)} for compatibility. 3580 * 3581 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 3582 * or later, consider instead using a {@link DialogFragment} instead.</em> 3583 * 3584 * <p>If you use {@link #showDialog(int)}, the activity will call through to 3585 * this method the first time, and hang onto it thereafter. Any dialog 3586 * that is created by this method will automatically be saved and restored 3587 * for you, including whether it is showing. 3588 * 3589 * <p>If you would like the activity to manage saving and restoring dialogs 3590 * for you, you should override this method and handle any ids that are 3591 * passed to {@link #showDialog}. 3592 * 3593 * <p>If you would like an opportunity to prepare your dialog before it is shown, 3594 * override {@link #onPrepareDialog(int, Dialog, Bundle)}. 3595 * 3596 * @param id The id of the dialog. 3597 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}. 3598 * @return The dialog. If you return null, the dialog will not be created. 3599 * 3600 * @see #onPrepareDialog(int, Dialog, Bundle) 3601 * @see #showDialog(int, Bundle) 3602 * @see #dismissDialog(int) 3603 * @see #removeDialog(int) 3604 * 3605 * @deprecated Use the new {@link DialogFragment} class with 3606 * {@link FragmentManager} instead; this is also 3607 * available on older platforms through the Android compatibility package. 3608 */ 3609 @Nullable 3610 @Deprecated 3611 protected Dialog onCreateDialog(int id, Bundle args) { 3612 return onCreateDialog(id); 3613 } 3614 3615 /** 3616 * @deprecated Old no-arguments version of 3617 * {@link #onPrepareDialog(int, Dialog, Bundle)}. 3618 */ 3619 @Deprecated 3620 protected void onPrepareDialog(int id, Dialog dialog) { 3621 dialog.setOwnerActivity(this); 3622 } 3623 3624 /** 3625 * Provides an opportunity to prepare a managed dialog before it is being 3626 * shown. The default implementation calls through to 3627 * {@link #onPrepareDialog(int, Dialog)} for compatibility. 3628 * 3629 * <p> 3630 * Override this if you need to update a managed dialog based on the state 3631 * of the application each time it is shown. For example, a time picker 3632 * dialog might want to be updated with the current time. You should call 3633 * through to the superclass's implementation. The default implementation 3634 * will set this Activity as the owner activity on the Dialog. 3635 * 3636 * @param id The id of the managed dialog. 3637 * @param dialog The dialog. 3638 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}. 3639 * @see #onCreateDialog(int, Bundle) 3640 * @see #showDialog(int) 3641 * @see #dismissDialog(int) 3642 * @see #removeDialog(int) 3643 * 3644 * @deprecated Use the new {@link DialogFragment} class with 3645 * {@link FragmentManager} instead; this is also 3646 * available on older platforms through the Android compatibility package. 3647 */ 3648 @Deprecated 3649 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { 3650 onPrepareDialog(id, dialog); 3651 } 3652 3653 /** 3654 * Simple version of {@link #showDialog(int, Bundle)} that does not 3655 * take any arguments. Simply calls {@link #showDialog(int, Bundle)} 3656 * with null arguments. 3657 * 3658 * @deprecated Use the new {@link DialogFragment} class with 3659 * {@link FragmentManager} instead; this is also 3660 * available on older platforms through the Android compatibility package. 3661 */ 3662 @Deprecated 3663 public final void showDialog(int id) { 3664 showDialog(id, null); 3665 } 3666 3667 /** 3668 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)} 3669 * will be made with the same id the first time this is called for a given 3670 * id. From thereafter, the dialog will be automatically saved and restored. 3671 * 3672 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB} 3673 * or later, consider instead using a {@link DialogFragment} instead.</em> 3674 * 3675 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will 3676 * be made to provide an opportunity to do any timely preparation. 3677 * 3678 * @param id The id of the managed dialog. 3679 * @param args Arguments to pass through to the dialog. These will be saved 3680 * and restored for you. Note that if the dialog is already created, 3681 * {@link #onCreateDialog(int, Bundle)} will not be called with the new 3682 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be. 3683 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first. 3684 * @return Returns true if the Dialog was created; false is returned if 3685 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false. 3686 * 3687 * @see Dialog 3688 * @see #onCreateDialog(int, Bundle) 3689 * @see #onPrepareDialog(int, Dialog, Bundle) 3690 * @see #dismissDialog(int) 3691 * @see #removeDialog(int) 3692 * 3693 * @deprecated Use the new {@link DialogFragment} class with 3694 * {@link FragmentManager} instead; this is also 3695 * available on older platforms through the Android compatibility package. 3696 */ 3697 @Nullable 3698 @Deprecated 3699 public final boolean showDialog(int id, Bundle args) { 3700 if (mManagedDialogs == null) { 3701 mManagedDialogs = new SparseArray<ManagedDialog>(); 3702 } 3703 ManagedDialog md = mManagedDialogs.get(id); 3704 if (md == null) { 3705 md = new ManagedDialog(); 3706 md.mDialog = createDialog(id, null, args); 3707 if (md.mDialog == null) { 3708 return false; 3709 } 3710 mManagedDialogs.put(id, md); 3711 } 3712 3713 md.mArgs = args; 3714 onPrepareDialog(id, md.mDialog, args); 3715 md.mDialog.show(); 3716 return true; 3717 } 3718 3719 /** 3720 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}. 3721 * 3722 * @param id The id of the managed dialog. 3723 * 3724 * @throws IllegalArgumentException if the id was not previously shown via 3725 * {@link #showDialog(int)}. 3726 * 3727 * @see #onCreateDialog(int, Bundle) 3728 * @see #onPrepareDialog(int, Dialog, Bundle) 3729 * @see #showDialog(int) 3730 * @see #removeDialog(int) 3731 * 3732 * @deprecated Use the new {@link DialogFragment} class with 3733 * {@link FragmentManager} instead; this is also 3734 * available on older platforms through the Android compatibility package. 3735 */ 3736 @Deprecated 3737 public final void dismissDialog(int id) { 3738 if (mManagedDialogs == null) { 3739 throw missingDialog(id); 3740 } 3741 3742 final ManagedDialog md = mManagedDialogs.get(id); 3743 if (md == null) { 3744 throw missingDialog(id); 3745 } 3746 md.mDialog.dismiss(); 3747 } 3748 3749 /** 3750 * Creates an exception to throw if a user passed in a dialog id that is 3751 * unexpected. 3752 */ 3753 private IllegalArgumentException missingDialog(int id) { 3754 return new IllegalArgumentException("no dialog with id " + id + " was ever " 3755 + "shown via Activity#showDialog"); 3756 } 3757 3758 /** 3759 * Removes any internal references to a dialog managed by this Activity. 3760 * If the dialog is showing, it will dismiss it as part of the clean up. 3761 * 3762 * <p>This can be useful if you know that you will never show a dialog again and 3763 * want to avoid the overhead of saving and restoring it in the future. 3764 * 3765 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function 3766 * will not throw an exception if you try to remove an ID that does not 3767 * currently have an associated dialog.</p> 3768 * 3769 * @param id The id of the managed dialog. 3770 * 3771 * @see #onCreateDialog(int, Bundle) 3772 * @see #onPrepareDialog(int, Dialog, Bundle) 3773 * @see #showDialog(int) 3774 * @see #dismissDialog(int) 3775 * 3776 * @deprecated Use the new {@link DialogFragment} class with 3777 * {@link FragmentManager} instead; this is also 3778 * available on older platforms through the Android compatibility package. 3779 */ 3780 @Deprecated 3781 public final void removeDialog(int id) { 3782 if (mManagedDialogs != null) { 3783 final ManagedDialog md = mManagedDialogs.get(id); 3784 if (md != null) { 3785 md.mDialog.dismiss(); 3786 mManagedDialogs.remove(id); 3787 } 3788 } 3789 } 3790 3791 /** 3792 * This hook is called when the user signals the desire to start a search. 3793 * 3794 * <p>You can use this function as a simple way to launch the search UI, in response to a 3795 * menu item, search button, or other widgets within your activity. Unless overidden, 3796 * calling this function is the same as calling 3797 * {@link #startSearch startSearch(null, false, null, false)}, which launches 3798 * search for the current activity as specified in its manifest, see {@link SearchManager}. 3799 * 3800 * <p>You can override this function to force global search, e.g. in response to a dedicated 3801 * search key, or to block search entirely (by simply returning false). 3802 * 3803 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default 3804 * implementation changes to simply return false and you must supply your own custom 3805 * implementation if you want to support search.</p> 3806 * 3807 * @param searchEvent The {@link SearchEvent} that signaled this search. 3808 * @return Returns {@code true} if search launched, and {@code false} if the activity does 3809 * not respond to search. The default implementation always returns {@code true}, except 3810 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false. 3811 * 3812 * @see android.app.SearchManager 3813 */ 3814 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) { 3815 mSearchEvent = searchEvent; 3816 boolean result = onSearchRequested(); 3817 mSearchEvent = null; 3818 return result; 3819 } 3820 3821 /** 3822 * @see #onSearchRequested(SearchEvent) 3823 */ 3824 public boolean onSearchRequested() { 3825 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK) 3826 != Configuration.UI_MODE_TYPE_TELEVISION) { 3827 startSearch(null, false, null, false); 3828 return true; 3829 } else { 3830 return false; 3831 } 3832 } 3833 3834 /** 3835 * During the onSearchRequested() callbacks, this function will return the 3836 * {@link SearchEvent} that triggered the callback, if it exists. 3837 * 3838 * @return SearchEvent The SearchEvent that triggered the {@link 3839 * #onSearchRequested} callback. 3840 */ 3841 public final SearchEvent getSearchEvent() { 3842 return mSearchEvent; 3843 } 3844 3845 /** 3846 * This hook is called to launch the search UI. 3847 * 3848 * <p>It is typically called from onSearchRequested(), either directly from 3849 * Activity.onSearchRequested() or from an overridden version in any given 3850 * Activity. If your goal is simply to activate search, it is preferred to call 3851 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal 3852 * is to inject specific data such as context data, it is preferred to <i>override</i> 3853 * onSearchRequested(), so that any callers to it will benefit from the override. 3854 * 3855 * @param initialQuery Any non-null non-empty string will be inserted as 3856 * pre-entered text in the search query box. 3857 * @param selectInitialQuery If true, the initial query will be preselected, which means that 3858 * any further typing will replace it. This is useful for cases where an entire pre-formed 3859 * query is being inserted. If false, the selection point will be placed at the end of the 3860 * inserted query. This is useful when the inserted query is text that the user entered, 3861 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful 3862 * if initialQuery is a non-empty string.</i> 3863 * @param appSearchData An application can insert application-specific 3864 * context here, in order to improve quality or specificity of its own 3865 * searches. This data will be returned with SEARCH intent(s). Null if 3866 * no extra data is required. 3867 * @param globalSearch If false, this will only launch the search that has been specifically 3868 * defined by the application (which is usually defined as a local search). If no default 3869 * search is defined in the current application or activity, global search will be launched. 3870 * If true, this will always launch a platform-global (e.g. web-based) search instead. 3871 * 3872 * @see android.app.SearchManager 3873 * @see #onSearchRequested 3874 */ 3875 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery, 3876 @Nullable Bundle appSearchData, boolean globalSearch) { 3877 ensureSearchManager(); 3878 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), 3879 appSearchData, globalSearch); 3880 } 3881 3882 /** 3883 * Similar to {@link #startSearch}, but actually fires off the search query after invoking 3884 * the search dialog. Made available for testing purposes. 3885 * 3886 * @param query The query to trigger. If empty, the request will be ignored. 3887 * @param appSearchData An application can insert application-specific 3888 * context here, in order to improve quality or specificity of its own 3889 * searches. This data will be returned with SEARCH intent(s). Null if 3890 * no extra data is required. 3891 */ 3892 public void triggerSearch(String query, @Nullable Bundle appSearchData) { 3893 ensureSearchManager(); 3894 mSearchManager.triggerSearch(query, getComponentName(), appSearchData); 3895 } 3896 3897 /** 3898 * Request that key events come to this activity. Use this if your 3899 * activity has no views with focus, but the activity still wants 3900 * a chance to process key events. 3901 * 3902 * @see android.view.Window#takeKeyEvents 3903 */ 3904 public void takeKeyEvents(boolean get) { 3905 getWindow().takeKeyEvents(get); 3906 } 3907 3908 /** 3909 * Enable extended window features. This is a convenience for calling 3910 * {@link android.view.Window#requestFeature getWindow().requestFeature()}. 3911 * 3912 * @param featureId The desired feature as defined in 3913 * {@link android.view.Window}. 3914 * @return Returns true if the requested feature is supported and now 3915 * enabled. 3916 * 3917 * @see android.view.Window#requestFeature 3918 */ 3919 public final boolean requestWindowFeature(int featureId) { 3920 return getWindow().requestFeature(featureId); 3921 } 3922 3923 /** 3924 * Convenience for calling 3925 * {@link android.view.Window#setFeatureDrawableResource}. 3926 */ 3927 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) { 3928 getWindow().setFeatureDrawableResource(featureId, resId); 3929 } 3930 3931 /** 3932 * Convenience for calling 3933 * {@link android.view.Window#setFeatureDrawableUri}. 3934 */ 3935 public final void setFeatureDrawableUri(int featureId, Uri uri) { 3936 getWindow().setFeatureDrawableUri(featureId, uri); 3937 } 3938 3939 /** 3940 * Convenience for calling 3941 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}. 3942 */ 3943 public final void setFeatureDrawable(int featureId, Drawable drawable) { 3944 getWindow().setFeatureDrawable(featureId, drawable); 3945 } 3946 3947 /** 3948 * Convenience for calling 3949 * {@link android.view.Window#setFeatureDrawableAlpha}. 3950 */ 3951 public final void setFeatureDrawableAlpha(int featureId, int alpha) { 3952 getWindow().setFeatureDrawableAlpha(featureId, alpha); 3953 } 3954 3955 /** 3956 * Convenience for calling 3957 * {@link android.view.Window#getLayoutInflater}. 3958 */ 3959 @NonNull 3960 public LayoutInflater getLayoutInflater() { 3961 return getWindow().getLayoutInflater(); 3962 } 3963 3964 /** 3965 * Returns a {@link MenuInflater} with this context. 3966 */ 3967 @NonNull 3968 public MenuInflater getMenuInflater() { 3969 // Make sure that action views can get an appropriate theme. 3970 if (mMenuInflater == null) { 3971 initWindowDecorActionBar(); 3972 if (mActionBar != null) { 3973 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this); 3974 } else { 3975 mMenuInflater = new MenuInflater(this); 3976 } 3977 } 3978 return mMenuInflater; 3979 } 3980 3981 @Override 3982 public void setTheme(int resid) { 3983 super.setTheme(resid); 3984 mWindow.setTheme(resid); 3985 } 3986 3987 @Override 3988 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid, 3989 boolean first) { 3990 if (mParent == null) { 3991 super.onApplyThemeResource(theme, resid, first); 3992 } else { 3993 try { 3994 theme.setTo(mParent.getTheme()); 3995 } catch (Exception e) { 3996 // Empty 3997 } 3998 theme.applyStyle(resid, false); 3999 } 4000 4001 // Get the primary color and update the TaskDescription for this activity 4002 TypedArray a = theme.obtainStyledAttributes( 4003 com.android.internal.R.styleable.ActivityTaskDescription); 4004 if (mTaskDescription.getPrimaryColor() == 0) { 4005 int colorPrimary = a.getColor( 4006 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0); 4007 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) { 4008 mTaskDescription.setPrimaryColor(colorPrimary); 4009 } 4010 } 4011 // For dev-preview only. 4012 if (mTaskDescription.getBackgroundColor() == 0) { 4013 int colorBackground = a.getColor( 4014 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0); 4015 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) { 4016 mTaskDescription.setBackgroundColor(colorBackground); 4017 } 4018 } 4019 a.recycle(); 4020 setTaskDescription(mTaskDescription); 4021 } 4022 4023 /** 4024 * Requests permissions to be granted to this application. These permissions 4025 * must be requested in your manifest, they should not be granted to your app, 4026 * and they should have protection level {@link android.content.pm.PermissionInfo 4027 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by 4028 * the platform or a third-party app. 4029 * <p> 4030 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL} 4031 * are granted at install time if requested in the manifest. Signature permissions 4032 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at 4033 * install time if requested in the manifest and the signature of your app matches 4034 * the signature of the app declaring the permissions. 4035 * </p> 4036 * <p> 4037 * If your app does not have the requested permissions the user will be presented 4038 * with UI for accepting them. After the user has accepted or rejected the 4039 * requested permissions you will receive a callback on {@link 4040 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the 4041 * permissions were granted or not. 4042 * </p> 4043 * <p> 4044 * Note that requesting a permission does not guarantee it will be granted and 4045 * your app should be able to run without having this permission. 4046 * </p> 4047 * <p> 4048 * This method may start an activity allowing the user to choose which permissions 4049 * to grant and which to reject. Hence, you should be prepared that your activity 4050 * may be paused and resumed. Further, granting some permissions may require 4051 * a restart of you application. In such a case, the system will recreate the 4052 * activity stack before delivering the result to {@link 4053 * #onRequestPermissionsResult(int, String[], int[])}. 4054 * </p> 4055 * <p> 4056 * When checking whether you have a permission you should use {@link 4057 * #checkSelfPermission(String)}. 4058 * </p> 4059 * <p> 4060 * Calling this API for permissions already granted to your app would show UI 4061 * to the user to decide whether the app can still hold these permissions. This 4062 * can be useful if the way your app uses data guarded by the permissions 4063 * changes significantly. 4064 * </p> 4065 * <p> 4066 * You cannot request a permission if your activity sets {@link 4067 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to 4068 * <code>true</code> because in this case the activity would not receive 4069 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}. 4070 * </p> 4071 * <p> 4072 * A sample permissions request looks like this: 4073 * </p> 4074 * <code><pre><p> 4075 * private void showContacts() { 4076 * if (checkSelfPermission(Manifest.permission.READ_CONTACTS) 4077 * != PackageManager.PERMISSION_GRANTED) { 4078 * requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 4079 * PERMISSIONS_REQUEST_READ_CONTACTS); 4080 * } else { 4081 * doShowContacts(); 4082 * } 4083 * } 4084 * 4085 * {@literal @}Override 4086 * public void onRequestPermissionsResult(int requestCode, String[] permissions, 4087 * int[] grantResults) { 4088 * if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS 4089 * && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 4090 * showContacts(); 4091 * } 4092 * } 4093 * </code></pre></p> 4094 * 4095 * @param permissions The requested permissions. Must me non-null and not empty. 4096 * @param requestCode Application specific request code to match with a result 4097 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}. 4098 * Should be >= 0. 4099 * 4100 * @throws IllegalArgumentException if requestCode is negative. 4101 * 4102 * @see #onRequestPermissionsResult(int, String[], int[]) 4103 * @see #checkSelfPermission(String) 4104 * @see #shouldShowRequestPermissionRationale(String) 4105 */ 4106 public final void requestPermissions(@NonNull String[] permissions, int requestCode) { 4107 if (requestCode < 0) { 4108 throw new IllegalArgumentException("requestCode should be >= 0"); 4109 } 4110 if (mHasCurrentPermissionsRequest) { 4111 Log.w(TAG, "Can reqeust only one set of permissions at a time"); 4112 // Dispatch the callback with empty arrays which means a cancellation. 4113 onRequestPermissionsResult(requestCode, new String[0], new int[0]); 4114 return; 4115 } 4116 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions); 4117 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null); 4118 mHasCurrentPermissionsRequest = true; 4119 } 4120 4121 /** 4122 * Callback for the result from requesting permissions. This method 4123 * is invoked for every call on {@link #requestPermissions(String[], int)}. 4124 * <p> 4125 * <strong>Note:</strong> It is possible that the permissions request interaction 4126 * with the user is interrupted. In this case you will receive empty permissions 4127 * and results arrays which should be treated as a cancellation. 4128 * </p> 4129 * 4130 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}. 4131 * @param permissions The requested permissions. Never null. 4132 * @param grantResults The grant results for the corresponding permissions 4133 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED} 4134 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null. 4135 * 4136 * @see #requestPermissions(String[], int) 4137 */ 4138 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 4139 @NonNull int[] grantResults) { 4140 /* callback - no nothing */ 4141 } 4142 4143 /** 4144 * Gets whether you should show UI with rationale for requesting a permission. 4145 * You should do this only if you do not have the permission and the context in 4146 * which the permission is requested does not clearly communicate to the user 4147 * what would be the benefit from granting this permission. 4148 * <p> 4149 * For example, if you write a camera app, requesting the camera permission 4150 * would be expected by the user and no rationale for why it is requested is 4151 * needed. If however, the app needs location for tagging photos then a non-tech 4152 * savvy user may wonder how location is related to taking photos. In this case 4153 * you may choose to show UI with rationale of requesting this permission. 4154 * </p> 4155 * 4156 * @param permission A permission your app wants to request. 4157 * @return Whether you can show permission rationale UI. 4158 * 4159 * @see #checkSelfPermission(String) 4160 * @see #requestPermissions(String[], int) 4161 * @see #onRequestPermissionsResult(int, String[], int[]) 4162 */ 4163 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) { 4164 return getPackageManager().shouldShowRequestPermissionRationale(permission); 4165 } 4166 4167 /** 4168 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)} 4169 * with no options. 4170 * 4171 * @param intent The intent to start. 4172 * @param requestCode If >= 0, this code will be returned in 4173 * onActivityResult() when the activity exits. 4174 * 4175 * @throws android.content.ActivityNotFoundException 4176 * 4177 * @see #startActivity 4178 */ 4179 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) { 4180 startActivityForResult(intent, requestCode, null); 4181 } 4182 4183 /** 4184 * Launch an activity for which you would like a result when it finished. 4185 * When this activity exits, your 4186 * onActivityResult() method will be called with the given requestCode. 4187 * Using a negative requestCode is the same as calling 4188 * {@link #startActivity} (the activity is not launched as a sub-activity). 4189 * 4190 * <p>Note that this method should only be used with Intent protocols 4191 * that are defined to return a result. In other protocols (such as 4192 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may 4193 * not get the result when you expect. For example, if the activity you 4194 * are launching uses the singleTask launch mode, it will not run in your 4195 * task and thus you will immediately receive a cancel result. 4196 * 4197 * <p>As a special case, if you call startActivityForResult() with a requestCode 4198 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your 4199 * activity, then your window will not be displayed until a result is 4200 * returned back from the started activity. This is to avoid visible 4201 * flickering when redirecting to another activity. 4202 * 4203 * <p>This method throws {@link android.content.ActivityNotFoundException} 4204 * if there was no Activity found to run the given Intent. 4205 * 4206 * @param intent The intent to start. 4207 * @param requestCode If >= 0, this code will be returned in 4208 * onActivityResult() when the activity exits. 4209 * @param options Additional options for how the Activity should be started. 4210 * See {@link android.content.Context#startActivity(Intent, Bundle) 4211 * Context.startActivity(Intent, Bundle)} for more details. 4212 * 4213 * @throws android.content.ActivityNotFoundException 4214 * 4215 * @see #startActivity 4216 */ 4217 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, 4218 @Nullable Bundle options) { 4219 if (mParent == null) { 4220 Instrumentation.ActivityResult ar = 4221 mInstrumentation.execStartActivity( 4222 this, mMainThread.getApplicationThread(), mToken, this, 4223 intent, requestCode, options); 4224 if (ar != null) { 4225 mMainThread.sendActivityResult( 4226 mToken, mEmbeddedID, requestCode, ar.getResultCode(), 4227 ar.getResultData()); 4228 } 4229 if (requestCode >= 0) { 4230 // If this start is requesting a result, we can avoid making 4231 // the activity visible until the result is received. Setting 4232 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 4233 // activity hidden during this time, to avoid flickering. 4234 // This can only be done when a result is requested because 4235 // that guarantees we will get information back when the 4236 // activity is finished, no matter what happens to it. 4237 mStartedActivity = true; 4238 } 4239 4240 cancelInputsAndStartExitTransition(options); 4241 // TODO Consider clearing/flushing other event sources and events for child windows. 4242 } else { 4243 if (options != null) { 4244 mParent.startActivityFromChild(this, intent, requestCode, options); 4245 } else { 4246 // Note we want to go through this method for compatibility with 4247 // existing applications that may have overridden it. 4248 mParent.startActivityFromChild(this, intent, requestCode); 4249 } 4250 } 4251 } 4252 4253 /** 4254 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition. 4255 * 4256 * @param options The ActivityOptions bundle used to start an Activity. 4257 */ 4258 private void cancelInputsAndStartExitTransition(Bundle options) { 4259 final View decor = mWindow != null ? mWindow.peekDecorView() : null; 4260 if (decor != null) { 4261 decor.cancelPendingInputEvents(); 4262 } 4263 if (options != null && !isTopOfTask()) { 4264 mActivityTransitionState.startExitOutTransition(this, options); 4265 } 4266 } 4267 4268 /** 4269 * @hide Implement to provide correct calling token. 4270 */ 4271 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) { 4272 startActivityForResultAsUser(intent, requestCode, null, user); 4273 } 4274 4275 /** 4276 * @hide Implement to provide correct calling token. 4277 */ 4278 public void startActivityForResultAsUser(Intent intent, int requestCode, 4279 @Nullable Bundle options, UserHandle user) { 4280 if (mParent != null) { 4281 throw new RuntimeException("Can't be called from a child"); 4282 } 4283 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( 4284 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, 4285 options, user); 4286 if (ar != null) { 4287 mMainThread.sendActivityResult( 4288 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); 4289 } 4290 if (requestCode >= 0) { 4291 // If this start is requesting a result, we can avoid making 4292 // the activity visible until the result is received. Setting 4293 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 4294 // activity hidden during this time, to avoid flickering. 4295 // This can only be done when a result is requested because 4296 // that guarantees we will get information back when the 4297 // activity is finished, no matter what happens to it. 4298 mStartedActivity = true; 4299 } 4300 4301 cancelInputsAndStartExitTransition(options); 4302 } 4303 4304 /** 4305 * @hide Implement to provide correct calling token. 4306 */ 4307 public void startActivityAsUser(Intent intent, UserHandle user) { 4308 startActivityAsUser(intent, null, user); 4309 } 4310 4311 /** 4312 * @hide Implement to provide correct calling token. 4313 */ 4314 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { 4315 if (mParent != null) { 4316 throw new RuntimeException("Can't be called from a child"); 4317 } 4318 Instrumentation.ActivityResult ar = 4319 mInstrumentation.execStartActivity( 4320 this, mMainThread.getApplicationThread(), mToken, this, 4321 intent, -1, options, user); 4322 if (ar != null) { 4323 mMainThread.sendActivityResult( 4324 mToken, mEmbeddedID, -1, ar.getResultCode(), 4325 ar.getResultData()); 4326 } 4327 cancelInputsAndStartExitTransition(options); 4328 } 4329 4330 /** 4331 * Start a new activity as if it was started by the activity that started our 4332 * current activity. This is for the resolver and chooser activities, which operate 4333 * as intermediaries that dispatch their intent to the target the user selects -- to 4334 * do this, they must perform all security checks including permission grants as if 4335 * their launch had come from the original activity. 4336 * @param intent The Intent to start. 4337 * @param options ActivityOptions or null. 4338 * @param ignoreTargetSecurity If true, the activity manager will not check whether the 4339 * caller it is doing the start is, is actually allowed to start the target activity. 4340 * If you set this to true, you must set an explicit component in the Intent and do any 4341 * appropriate security checks yourself. 4342 * @param userId The user the new activity should run as. 4343 * @hide 4344 */ 4345 public void startActivityAsCaller(Intent intent, @Nullable Bundle options, 4346 boolean ignoreTargetSecurity, int userId) { 4347 if (mParent != null) { 4348 throw new RuntimeException("Can't be called from a child"); 4349 } 4350 Instrumentation.ActivityResult ar = 4351 mInstrumentation.execStartActivityAsCaller( 4352 this, mMainThread.getApplicationThread(), mToken, this, 4353 intent, -1, options, ignoreTargetSecurity, userId); 4354 if (ar != null) { 4355 mMainThread.sendActivityResult( 4356 mToken, mEmbeddedID, -1, ar.getResultCode(), 4357 ar.getResultData()); 4358 } 4359 cancelInputsAndStartExitTransition(options); 4360 } 4361 4362 /** 4363 * Same as calling {@link #startIntentSenderForResult(IntentSender, int, 4364 * Intent, int, int, int, Bundle)} with no options. 4365 * 4366 * @param intent The IntentSender to launch. 4367 * @param requestCode If >= 0, this code will be returned in 4368 * onActivityResult() when the activity exits. 4369 * @param fillInIntent If non-null, this will be provided as the 4370 * intent parameter to {@link IntentSender#sendIntent}. 4371 * @param flagsMask Intent flags in the original IntentSender that you 4372 * would like to change. 4373 * @param flagsValues Desired values for any bits set in 4374 * <var>flagsMask</var> 4375 * @param extraFlags Always set to 0. 4376 */ 4377 public void startIntentSenderForResult(IntentSender intent, int requestCode, 4378 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 4379 throws IntentSender.SendIntentException { 4380 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, 4381 flagsValues, extraFlags, null); 4382 } 4383 4384 /** 4385 * Like {@link #startActivityForResult(Intent, int)}, but allowing you 4386 * to use a IntentSender to describe the activity to be started. If 4387 * the IntentSender is for an activity, that activity will be started 4388 * as if you had called the regular {@link #startActivityForResult(Intent, int)} 4389 * here; otherwise, its associated action will be executed (such as 4390 * sending a broadcast) as if you had called 4391 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it. 4392 * 4393 * @param intent The IntentSender to launch. 4394 * @param requestCode If >= 0, this code will be returned in 4395 * onActivityResult() when the activity exits. 4396 * @param fillInIntent If non-null, this will be provided as the 4397 * intent parameter to {@link IntentSender#sendIntent}. 4398 * @param flagsMask Intent flags in the original IntentSender that you 4399 * would like to change. 4400 * @param flagsValues Desired values for any bits set in 4401 * <var>flagsMask</var> 4402 * @param extraFlags Always set to 0. 4403 * @param options Additional options for how the Activity should be started. 4404 * See {@link android.content.Context#startActivity(Intent, Bundle) 4405 * Context.startActivity(Intent, Bundle)} for more details. If options 4406 * have also been supplied by the IntentSender, options given here will 4407 * override any that conflict with those given by the IntentSender. 4408 */ 4409 public void startIntentSenderForResult(IntentSender intent, int requestCode, 4410 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, 4411 Bundle options) throws IntentSender.SendIntentException { 4412 if (mParent == null) { 4413 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent, 4414 flagsMask, flagsValues, options); 4415 } else if (options != null) { 4416 mParent.startIntentSenderFromChild(this, intent, requestCode, 4417 fillInIntent, flagsMask, flagsValues, extraFlags, options); 4418 } else { 4419 // Note we want to go through this call for compatibility with 4420 // existing applications that may have overridden the method. 4421 mParent.startIntentSenderFromChild(this, intent, requestCode, 4422 fillInIntent, flagsMask, flagsValues, extraFlags); 4423 } 4424 } 4425 4426 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode, 4427 Intent fillInIntent, int flagsMask, int flagsValues, 4428 Bundle options) 4429 throws IntentSender.SendIntentException { 4430 try { 4431 String resolvedType = null; 4432 if (fillInIntent != null) { 4433 fillInIntent.migrateExtraStreamToClipData(); 4434 fillInIntent.prepareToLeaveProcess(this); 4435 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 4436 } 4437 int result = ActivityManagerNative.getDefault() 4438 .startActivityIntentSender(mMainThread.getApplicationThread(), intent, 4439 fillInIntent, resolvedType, mToken, who, 4440 requestCode, flagsMask, flagsValues, options); 4441 if (result == ActivityManager.START_CANCELED) { 4442 throw new IntentSender.SendIntentException(); 4443 } 4444 Instrumentation.checkStartActivityResult(result, null); 4445 } catch (RemoteException e) { 4446 } 4447 if (requestCode >= 0) { 4448 // If this start is requesting a result, we can avoid making 4449 // the activity visible until the result is received. Setting 4450 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 4451 // activity hidden during this time, to avoid flickering. 4452 // This can only be done when a result is requested because 4453 // that guarantees we will get information back when the 4454 // activity is finished, no matter what happens to it. 4455 mStartedActivity = true; 4456 } 4457 } 4458 4459 /** 4460 * Same as {@link #startActivity(Intent, Bundle)} with no options 4461 * specified. 4462 * 4463 * @param intent The intent to start. 4464 * 4465 * @throws android.content.ActivityNotFoundException 4466 * 4467 * @see {@link #startActivity(Intent, Bundle)} 4468 * @see #startActivityForResult 4469 */ 4470 @Override 4471 public void startActivity(Intent intent) { 4472 this.startActivity(intent, null); 4473 } 4474 4475 /** 4476 * Launch a new activity. You will not receive any information about when 4477 * the activity exits. This implementation overrides the base version, 4478 * providing information about 4479 * the activity performing the launch. Because of this additional 4480 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not 4481 * required; if not specified, the new activity will be added to the 4482 * task of the caller. 4483 * 4484 * <p>This method throws {@link android.content.ActivityNotFoundException} 4485 * if there was no Activity found to run the given Intent. 4486 * 4487 * @param intent The intent to start. 4488 * @param options Additional options for how the Activity should be started. 4489 * See {@link android.content.Context#startActivity(Intent, Bundle) 4490 * Context.startActivity(Intent, Bundle)} for more details. 4491 * 4492 * @throws android.content.ActivityNotFoundException 4493 * 4494 * @see {@link #startActivity(Intent)} 4495 * @see #startActivityForResult 4496 */ 4497 @Override 4498 public void startActivity(Intent intent, @Nullable Bundle options) { 4499 if (options != null) { 4500 startActivityForResult(intent, -1, options); 4501 } else { 4502 // Note we want to go through this call for compatibility with 4503 // applications that may have overridden the method. 4504 startActivityForResult(intent, -1); 4505 } 4506 } 4507 4508 /** 4509 * Same as {@link #startActivities(Intent[], Bundle)} with no options 4510 * specified. 4511 * 4512 * @param intents The intents to start. 4513 * 4514 * @throws android.content.ActivityNotFoundException 4515 * 4516 * @see {@link #startActivities(Intent[], Bundle)} 4517 * @see #startActivityForResult 4518 */ 4519 @Override 4520 public void startActivities(Intent[] intents) { 4521 startActivities(intents, null); 4522 } 4523 4524 /** 4525 * Launch a new activity. You will not receive any information about when 4526 * the activity exits. This implementation overrides the base version, 4527 * providing information about 4528 * the activity performing the launch. Because of this additional 4529 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not 4530 * required; if not specified, the new activity will be added to the 4531 * task of the caller. 4532 * 4533 * <p>This method throws {@link android.content.ActivityNotFoundException} 4534 * if there was no Activity found to run the given Intent. 4535 * 4536 * @param intents The intents to start. 4537 * @param options Additional options for how the Activity should be started. 4538 * See {@link android.content.Context#startActivity(Intent, Bundle) 4539 * Context.startActivity(Intent, Bundle)} for more details. 4540 * 4541 * @throws android.content.ActivityNotFoundException 4542 * 4543 * @see {@link #startActivities(Intent[])} 4544 * @see #startActivityForResult 4545 */ 4546 @Override 4547 public void startActivities(Intent[] intents, @Nullable Bundle options) { 4548 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(), 4549 mToken, this, intents, options); 4550 } 4551 4552 /** 4553 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)} 4554 * with no options. 4555 * 4556 * @param intent The IntentSender to launch. 4557 * @param fillInIntent If non-null, this will be provided as the 4558 * intent parameter to {@link IntentSender#sendIntent}. 4559 * @param flagsMask Intent flags in the original IntentSender that you 4560 * would like to change. 4561 * @param flagsValues Desired values for any bits set in 4562 * <var>flagsMask</var> 4563 * @param extraFlags Always set to 0. 4564 */ 4565 public void startIntentSender(IntentSender intent, 4566 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 4567 throws IntentSender.SendIntentException { 4568 startIntentSender(intent, fillInIntent, flagsMask, flagsValues, 4569 extraFlags, null); 4570 } 4571 4572 /** 4573 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender 4574 * to start; see 4575 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)} 4576 * for more information. 4577 * 4578 * @param intent The IntentSender to launch. 4579 * @param fillInIntent If non-null, this will be provided as the 4580 * intent parameter to {@link IntentSender#sendIntent}. 4581 * @param flagsMask Intent flags in the original IntentSender that you 4582 * would like to change. 4583 * @param flagsValues Desired values for any bits set in 4584 * <var>flagsMask</var> 4585 * @param extraFlags Always set to 0. 4586 * @param options Additional options for how the Activity should be started. 4587 * See {@link android.content.Context#startActivity(Intent, Bundle) 4588 * Context.startActivity(Intent, Bundle)} for more details. If options 4589 * have also been supplied by the IntentSender, options given here will 4590 * override any that conflict with those given by the IntentSender. 4591 */ 4592 public void startIntentSender(IntentSender intent, 4593 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, 4594 Bundle options) throws IntentSender.SendIntentException { 4595 if (options != null) { 4596 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask, 4597 flagsValues, extraFlags, options); 4598 } else { 4599 // Note we want to go through this call for compatibility with 4600 // applications that may have overridden the method. 4601 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask, 4602 flagsValues, extraFlags); 4603 } 4604 } 4605 4606 /** 4607 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)} 4608 * with no options. 4609 * 4610 * @param intent The intent to start. 4611 * @param requestCode If >= 0, this code will be returned in 4612 * onActivityResult() when the activity exits, as described in 4613 * {@link #startActivityForResult}. 4614 * 4615 * @return If a new activity was launched then true is returned; otherwise 4616 * false is returned and you must handle the Intent yourself. 4617 * 4618 * @see #startActivity 4619 * @see #startActivityForResult 4620 */ 4621 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent, 4622 int requestCode) { 4623 return startActivityIfNeeded(intent, requestCode, null); 4624 } 4625 4626 /** 4627 * A special variation to launch an activity only if a new activity 4628 * instance is needed to handle the given Intent. In other words, this is 4629 * just like {@link #startActivityForResult(Intent, int)} except: if you are 4630 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or 4631 * singleTask or singleTop 4632 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode}, 4633 * and the activity 4634 * that handles <var>intent</var> is the same as your currently running 4635 * activity, then a new instance is not needed. In this case, instead of 4636 * the normal behavior of calling {@link #onNewIntent} this function will 4637 * return and you can handle the Intent yourself. 4638 * 4639 * <p>This function can only be called from a top-level activity; if it is 4640 * called from a child activity, a runtime exception will be thrown. 4641 * 4642 * @param intent The intent to start. 4643 * @param requestCode If >= 0, this code will be returned in 4644 * onActivityResult() when the activity exits, as described in 4645 * {@link #startActivityForResult}. 4646 * @param options Additional options for how the Activity should be started. 4647 * See {@link android.content.Context#startActivity(Intent, Bundle) 4648 * Context.startActivity(Intent, Bundle)} for more details. 4649 * 4650 * @return If a new activity was launched then true is returned; otherwise 4651 * false is returned and you must handle the Intent yourself. 4652 * 4653 * @see #startActivity 4654 * @see #startActivityForResult 4655 */ 4656 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent, 4657 int requestCode, @Nullable Bundle options) { 4658 if (mParent == null) { 4659 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER; 4660 try { 4661 Uri referrer = onProvideReferrer(); 4662 if (referrer != null) { 4663 intent.putExtra(Intent.EXTRA_REFERRER, referrer); 4664 } 4665 intent.migrateExtraStreamToClipData(); 4666 intent.prepareToLeaveProcess(this); 4667 result = ActivityManagerNative.getDefault() 4668 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(), 4669 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken, 4670 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, 4671 null, options); 4672 } catch (RemoteException e) { 4673 // Empty 4674 } 4675 4676 Instrumentation.checkStartActivityResult(result, intent); 4677 4678 if (requestCode >= 0) { 4679 // If this start is requesting a result, we can avoid making 4680 // the activity visible until the result is received. Setting 4681 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 4682 // activity hidden during this time, to avoid flickering. 4683 // This can only be done when a result is requested because 4684 // that guarantees we will get information back when the 4685 // activity is finished, no matter what happens to it. 4686 mStartedActivity = true; 4687 } 4688 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER; 4689 } 4690 4691 throw new UnsupportedOperationException( 4692 "startActivityIfNeeded can only be called from a top-level activity"); 4693 } 4694 4695 /** 4696 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with 4697 * no options. 4698 * 4699 * @param intent The intent to dispatch to the next activity. For 4700 * correct behavior, this must be the same as the Intent that started 4701 * your own activity; the only changes you can make are to the extras 4702 * inside of it. 4703 * 4704 * @return Returns a boolean indicating whether there was another Activity 4705 * to start: true if there was a next activity to start, false if there 4706 * wasn't. In general, if true is returned you will then want to call 4707 * finish() on yourself. 4708 */ 4709 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) { 4710 return startNextMatchingActivity(intent, null); 4711 } 4712 4713 /** 4714 * Special version of starting an activity, for use when you are replacing 4715 * other activity components. You can use this to hand the Intent off 4716 * to the next Activity that can handle it. You typically call this in 4717 * {@link #onCreate} with the Intent returned by {@link #getIntent}. 4718 * 4719 * @param intent The intent to dispatch to the next activity. For 4720 * correct behavior, this must be the same as the Intent that started 4721 * your own activity; the only changes you can make are to the extras 4722 * inside of it. 4723 * @param options Additional options for how the Activity should be started. 4724 * See {@link android.content.Context#startActivity(Intent, Bundle) 4725 * Context.startActivity(Intent, Bundle)} for more details. 4726 * 4727 * @return Returns a boolean indicating whether there was another Activity 4728 * to start: true if there was a next activity to start, false if there 4729 * wasn't. In general, if true is returned you will then want to call 4730 * finish() on yourself. 4731 */ 4732 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent, 4733 @Nullable Bundle options) { 4734 if (mParent == null) { 4735 try { 4736 intent.migrateExtraStreamToClipData(); 4737 intent.prepareToLeaveProcess(this); 4738 return ActivityManagerNative.getDefault() 4739 .startNextMatchingActivity(mToken, intent, options); 4740 } catch (RemoteException e) { 4741 // Empty 4742 } 4743 return false; 4744 } 4745 4746 throw new UnsupportedOperationException( 4747 "startNextMatchingActivity can only be called from a top-level activity"); 4748 } 4749 4750 /** 4751 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)} 4752 * with no options. 4753 * 4754 * @param child The activity making the call. 4755 * @param intent The intent to start. 4756 * @param requestCode Reply request code. < 0 if reply is not requested. 4757 * 4758 * @throws android.content.ActivityNotFoundException 4759 * 4760 * @see #startActivity 4761 * @see #startActivityForResult 4762 */ 4763 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent, 4764 int requestCode) { 4765 startActivityFromChild(child, intent, requestCode, null); 4766 } 4767 4768 /** 4769 * This is called when a child activity of this one calls its 4770 * {@link #startActivity} or {@link #startActivityForResult} method. 4771 * 4772 * <p>This method throws {@link android.content.ActivityNotFoundException} 4773 * if there was no Activity found to run the given Intent. 4774 * 4775 * @param child The activity making the call. 4776 * @param intent The intent to start. 4777 * @param requestCode Reply request code. < 0 if reply is not requested. 4778 * @param options Additional options for how the Activity should be started. 4779 * See {@link android.content.Context#startActivity(Intent, Bundle) 4780 * Context.startActivity(Intent, Bundle)} for more details. 4781 * 4782 * @throws android.content.ActivityNotFoundException 4783 * 4784 * @see #startActivity 4785 * @see #startActivityForResult 4786 */ 4787 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent, 4788 int requestCode, @Nullable Bundle options) { 4789 Instrumentation.ActivityResult ar = 4790 mInstrumentation.execStartActivity( 4791 this, mMainThread.getApplicationThread(), mToken, child, 4792 intent, requestCode, options); 4793 if (ar != null) { 4794 mMainThread.sendActivityResult( 4795 mToken, child.mEmbeddedID, requestCode, 4796 ar.getResultCode(), ar.getResultData()); 4797 } 4798 cancelInputsAndStartExitTransition(options); 4799 } 4800 4801 /** 4802 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)} 4803 * with no options. 4804 * 4805 * @param fragment The fragment making the call. 4806 * @param intent The intent to start. 4807 * @param requestCode Reply request code. < 0 if reply is not requested. 4808 * 4809 * @throws android.content.ActivityNotFoundException 4810 * 4811 * @see Fragment#startActivity 4812 * @see Fragment#startActivityForResult 4813 */ 4814 public void startActivityFromFragment(@NonNull Fragment fragment, 4815 @RequiresPermission Intent intent, int requestCode) { 4816 startActivityFromFragment(fragment, intent, requestCode, null); 4817 } 4818 4819 /** 4820 * This is called when a Fragment in this activity calls its 4821 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult} 4822 * method. 4823 * 4824 * <p>This method throws {@link android.content.ActivityNotFoundException} 4825 * if there was no Activity found to run the given Intent. 4826 * 4827 * @param fragment The fragment making the call. 4828 * @param intent The intent to start. 4829 * @param requestCode Reply request code. < 0 if reply is not requested. 4830 * @param options Additional options for how the Activity should be started. 4831 * See {@link android.content.Context#startActivity(Intent, Bundle) 4832 * Context.startActivity(Intent, Bundle)} for more details. 4833 * 4834 * @throws android.content.ActivityNotFoundException 4835 * 4836 * @see Fragment#startActivity 4837 * @see Fragment#startActivityForResult 4838 */ 4839 public void startActivityFromFragment(@NonNull Fragment fragment, 4840 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { 4841 startActivityForResult(fragment.mWho, intent, requestCode, options); 4842 } 4843 4844 /** 4845 * @hide 4846 */ 4847 @Override 4848 public void startActivityForResult( 4849 String who, Intent intent, int requestCode, @Nullable Bundle options) { 4850 Uri referrer = onProvideReferrer(); 4851 if (referrer != null) { 4852 intent.putExtra(Intent.EXTRA_REFERRER, referrer); 4853 } 4854 Instrumentation.ActivityResult ar = 4855 mInstrumentation.execStartActivity( 4856 this, mMainThread.getApplicationThread(), mToken, who, 4857 intent, requestCode, options); 4858 if (ar != null) { 4859 mMainThread.sendActivityResult( 4860 mToken, who, requestCode, 4861 ar.getResultCode(), ar.getResultData()); 4862 } 4863 cancelInputsAndStartExitTransition(options); 4864 } 4865 4866 /** 4867 * @hide 4868 */ 4869 @Override 4870 public boolean canStartActivityForResult() { 4871 return true; 4872 } 4873 4874 /** 4875 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender, 4876 * int, Intent, int, int, int, Bundle)} with no options. 4877 */ 4878 public void startIntentSenderFromChild(Activity child, IntentSender intent, 4879 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, 4880 int extraFlags) 4881 throws IntentSender.SendIntentException { 4882 startIntentSenderFromChild(child, intent, requestCode, fillInIntent, 4883 flagsMask, flagsValues, extraFlags, null); 4884 } 4885 4886 /** 4887 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but 4888 * taking a IntentSender; see 4889 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)} 4890 * for more information. 4891 */ 4892 public void startIntentSenderFromChild(Activity child, IntentSender intent, 4893 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, 4894 int extraFlags, @Nullable Bundle options) 4895 throws IntentSender.SendIntentException { 4896 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent, 4897 flagsMask, flagsValues, options); 4898 } 4899 4900 /** 4901 * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see 4902 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)} 4903 * for more information. 4904 * 4905 * @hide 4906 */ 4907 public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent, 4908 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, 4909 int extraFlags, @Nullable Bundle options) 4910 throws IntentSender.SendIntentException { 4911 startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent, 4912 flagsMask, flagsValues, options); 4913 } 4914 4915 /** 4916 * Call immediately after one of the flavors of {@link #startActivity(Intent)} 4917 * or {@link #finish} to specify an explicit transition animation to 4918 * perform next. 4919 * 4920 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative 4921 * to using this with starting activities is to supply the desired animation 4922 * information through a {@link ActivityOptions} bundle to 4923 * {@link #startActivity(Intent, Bundle) or a related function. This allows 4924 * you to specify a custom animation even when starting an activity from 4925 * outside the context of the current top activity. 4926 * 4927 * @param enterAnim A resource ID of the animation resource to use for 4928 * the incoming activity. Use 0 for no animation. 4929 * @param exitAnim A resource ID of the animation resource to use for 4930 * the outgoing activity. Use 0 for no animation. 4931 */ 4932 public void overridePendingTransition(int enterAnim, int exitAnim) { 4933 try { 4934 ActivityManagerNative.getDefault().overridePendingTransition( 4935 mToken, getPackageName(), enterAnim, exitAnim); 4936 } catch (RemoteException e) { 4937 } 4938 } 4939 4940 /** 4941 * Call this to set the result that your activity will return to its 4942 * caller. 4943 * 4944 * @param resultCode The result code to propagate back to the originating 4945 * activity, often RESULT_CANCELED or RESULT_OK 4946 * 4947 * @see #RESULT_CANCELED 4948 * @see #RESULT_OK 4949 * @see #RESULT_FIRST_USER 4950 * @see #setResult(int, Intent) 4951 */ 4952 public final void setResult(int resultCode) { 4953 synchronized (this) { 4954 mResultCode = resultCode; 4955 mResultData = null; 4956 } 4957 } 4958 4959 /** 4960 * Call this to set the result that your activity will return to its 4961 * caller. 4962 * 4963 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent 4964 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION 4965 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION 4966 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the 4967 * Activity receiving the result access to the specific URIs in the Intent. 4968 * Access will remain until the Activity has finished (it will remain across the hosting 4969 * process being killed and other temporary destruction) and will be added 4970 * to any existing set of URI permissions it already holds. 4971 * 4972 * @param resultCode The result code to propagate back to the originating 4973 * activity, often RESULT_CANCELED or RESULT_OK 4974 * @param data The data to propagate back to the originating activity. 4975 * 4976 * @see #RESULT_CANCELED 4977 * @see #RESULT_OK 4978 * @see #RESULT_FIRST_USER 4979 * @see #setResult(int) 4980 */ 4981 public final void setResult(int resultCode, Intent data) { 4982 synchronized (this) { 4983 mResultCode = resultCode; 4984 mResultData = data; 4985 } 4986 } 4987 4988 /** 4989 * Return information about who launched this activity. If the launching Intent 4990 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER}, 4991 * that will be returned as-is; otherwise, if known, an 4992 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the 4993 * package name that started the Intent will be returned. This may return null if no 4994 * referrer can be identified -- it is neither explicitly specified, nor is it known which 4995 * application package was involved. 4996 * 4997 * <p>If called while inside the handling of {@link #onNewIntent}, this function will 4998 * return the referrer that submitted that new intent to the activity. Otherwise, it 4999 * always returns the referrer of the original Intent.</p> 5000 * 5001 * <p>Note that this is <em>not</em> a security feature -- you can not trust the 5002 * referrer information, applications can spoof it.</p> 5003 */ 5004 @Nullable 5005 public Uri getReferrer() { 5006 Intent intent = getIntent(); 5007 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER); 5008 if (referrer != null) { 5009 return referrer; 5010 } 5011 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME); 5012 if (referrerName != null) { 5013 return Uri.parse(referrerName); 5014 } 5015 if (mReferrer != null) { 5016 return new Uri.Builder().scheme("android-app").authority(mReferrer).build(); 5017 } 5018 return null; 5019 } 5020 5021 /** 5022 * Override to generate the desired referrer for the content currently being shown 5023 * by the app. The default implementation returns null, meaning the referrer will simply 5024 * be the android-app: of the package name of this activity. Return a non-null Uri to 5025 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it. 5026 */ 5027 public Uri onProvideReferrer() { 5028 return null; 5029 } 5030 5031 /** 5032 * Return the name of the package that invoked this activity. This is who 5033 * the data in {@link #setResult setResult()} will be sent to. You can 5034 * use this information to validate that the recipient is allowed to 5035 * receive the data. 5036 * 5037 * <p class="note">Note: if the calling activity is not expecting a result (that is it 5038 * did not use the {@link #startActivityForResult} 5039 * form that includes a request code), then the calling package will be 5040 * null.</p> 5041 * 5042 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, 5043 * the result from this method was unstable. If the process hosting the calling 5044 * package was no longer running, it would return null instead of the proper package 5045 * name. You can use {@link #getCallingActivity()} and retrieve the package name 5046 * from that instead.</p> 5047 * 5048 * @return The package of the activity that will receive your 5049 * reply, or null if none. 5050 */ 5051 @Nullable 5052 public String getCallingPackage() { 5053 try { 5054 return ActivityManagerNative.getDefault().getCallingPackage(mToken); 5055 } catch (RemoteException e) { 5056 return null; 5057 } 5058 } 5059 5060 /** 5061 * Return the name of the activity that invoked this activity. This is 5062 * who the data in {@link #setResult setResult()} will be sent to. You 5063 * can use this information to validate that the recipient is allowed to 5064 * receive the data. 5065 * 5066 * <p class="note">Note: if the calling activity is not expecting a result (that is it 5067 * did not use the {@link #startActivityForResult} 5068 * form that includes a request code), then the calling package will be 5069 * null. 5070 * 5071 * @return The ComponentName of the activity that will receive your 5072 * reply, or null if none. 5073 */ 5074 @Nullable 5075 public ComponentName getCallingActivity() { 5076 try { 5077 return ActivityManagerNative.getDefault().getCallingActivity(mToken); 5078 } catch (RemoteException e) { 5079 return null; 5080 } 5081 } 5082 5083 /** 5084 * Control whether this activity's main window is visible. This is intended 5085 * only for the special case of an activity that is not going to show a 5086 * UI itself, but can't just finish prior to onResume() because it needs 5087 * to wait for a service binding or such. Setting this to false allows 5088 * you to prevent your UI from being shown during that time. 5089 * 5090 * <p>The default value for this is taken from the 5091 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme. 5092 */ 5093 public void setVisible(boolean visible) { 5094 if (mVisibleFromClient != visible) { 5095 mVisibleFromClient = visible; 5096 if (mVisibleFromServer) { 5097 if (visible) makeVisible(); 5098 else mDecor.setVisibility(View.INVISIBLE); 5099 } 5100 } 5101 } 5102 5103 void makeVisible() { 5104 if (!mWindowAdded) { 5105 ViewManager wm = getWindowManager(); 5106 wm.addView(mDecor, getWindow().getAttributes()); 5107 mWindowAdded = true; 5108 } 5109 mDecor.setVisibility(View.VISIBLE); 5110 } 5111 5112 /** 5113 * Check to see whether this activity is in the process of finishing, 5114 * either because you called {@link #finish} on it or someone else 5115 * has requested that it finished. This is often used in 5116 * {@link #onPause} to determine whether the activity is simply pausing or 5117 * completely finishing. 5118 * 5119 * @return If the activity is finishing, returns true; else returns false. 5120 * 5121 * @see #finish 5122 */ 5123 public boolean isFinishing() { 5124 return mFinished; 5125 } 5126 5127 /** 5128 * Returns true if the final {@link #onDestroy()} call has been made 5129 * on the Activity, so this instance is now dead. 5130 */ 5131 public boolean isDestroyed() { 5132 return mDestroyed; 5133 } 5134 5135 /** 5136 * Check to see whether this activity is in the process of being destroyed in order to be 5137 * recreated with a new configuration. This is often used in 5138 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed 5139 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}. 5140 * 5141 * @return If the activity is being torn down in order to be recreated with a new configuration, 5142 * returns true; else returns false. 5143 */ 5144 public boolean isChangingConfigurations() { 5145 return mChangingConfigurations; 5146 } 5147 5148 /** 5149 * Cause this Activity to be recreated with a new instance. This results 5150 * in essentially the same flow as when the Activity is created due to 5151 * a configuration change -- the current instance will go through its 5152 * lifecycle to {@link #onDestroy} and a new instance then created after it. 5153 */ 5154 public void recreate() { 5155 if (mParent != null) { 5156 throw new IllegalStateException("Can only be called on top-level activity"); 5157 } 5158 if (Looper.myLooper() != mMainThread.getLooper()) { 5159 throw new IllegalStateException("Must be called from main thread"); 5160 } 5161 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false, 5162 false /* preserveWindow */); 5163 } 5164 5165 /** 5166 * Finishes the current activity and specifies whether to remove the task associated with this 5167 * activity. 5168 */ 5169 private void finish(int finishTask) { 5170 if (mParent == null) { 5171 int resultCode; 5172 Intent resultData; 5173 synchronized (this) { 5174 resultCode = mResultCode; 5175 resultData = mResultData; 5176 } 5177 if (false) Log.v(TAG, "Finishing self: token=" + mToken); 5178 try { 5179 if (resultData != null) { 5180 resultData.prepareToLeaveProcess(this); 5181 } 5182 if (ActivityManagerNative.getDefault() 5183 .finishActivity(mToken, resultCode, resultData, finishTask)) { 5184 mFinished = true; 5185 } 5186 } catch (RemoteException e) { 5187 // Empty 5188 } 5189 } else { 5190 mParent.finishFromChild(this); 5191 } 5192 } 5193 5194 /** 5195 * Call this when your activity is done and should be closed. The 5196 * ActivityResult is propagated back to whoever launched you via 5197 * onActivityResult(). 5198 */ 5199 public void finish() { 5200 finish(DONT_FINISH_TASK_WITH_ACTIVITY); 5201 } 5202 5203 /** 5204 * Finish this activity as well as all activities immediately below it 5205 * in the current task that have the same affinity. This is typically 5206 * used when an application can be launched on to another task (such as 5207 * from an ACTION_VIEW of a content type it understands) and the user 5208 * has used the up navigation to switch out of the current task and in 5209 * to its own task. In this case, if the user has navigated down into 5210 * any other activities of the second application, all of those should 5211 * be removed from the original task as part of the task switch. 5212 * 5213 * <p>Note that this finish does <em>not</em> allow you to deliver results 5214 * to the previous activity, and an exception will be thrown if you are trying 5215 * to do so.</p> 5216 */ 5217 public void finishAffinity() { 5218 if (mParent != null) { 5219 throw new IllegalStateException("Can not be called from an embedded activity"); 5220 } 5221 if (mResultCode != RESULT_CANCELED || mResultData != null) { 5222 throw new IllegalStateException("Can not be called to deliver a result"); 5223 } 5224 try { 5225 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) { 5226 mFinished = true; 5227 } 5228 } catch (RemoteException e) { 5229 // Empty 5230 } 5231 } 5232 5233 /** 5234 * This is called when a child activity of this one calls its 5235 * {@link #finish} method. The default implementation simply calls 5236 * finish() on this activity (the parent), finishing the entire group. 5237 * 5238 * @param child The activity making the call. 5239 * 5240 * @see #finish 5241 */ 5242 public void finishFromChild(Activity child) { 5243 finish(); 5244 } 5245 5246 /** 5247 * Reverses the Activity Scene entry Transition and triggers the calling Activity 5248 * to reverse its exit Transition. When the exit Transition completes, 5249 * {@link #finish()} is called. If no entry Transition was used, finish() is called 5250 * immediately and the Activity exit Transition is run. 5251 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[]) 5252 */ 5253 public void finishAfterTransition() { 5254 if (!mActivityTransitionState.startExitBackTransition(this)) { 5255 finish(); 5256 } 5257 } 5258 5259 /** 5260 * Force finish another activity that you had previously started with 5261 * {@link #startActivityForResult}. 5262 * 5263 * @param requestCode The request code of the activity that you had 5264 * given to startActivityForResult(). If there are multiple 5265 * activities started with this request code, they 5266 * will all be finished. 5267 */ 5268 public void finishActivity(int requestCode) { 5269 if (mParent == null) { 5270 try { 5271 ActivityManagerNative.getDefault() 5272 .finishSubActivity(mToken, mEmbeddedID, requestCode); 5273 } catch (RemoteException e) { 5274 // Empty 5275 } 5276 } else { 5277 mParent.finishActivityFromChild(this, requestCode); 5278 } 5279 } 5280 5281 /** 5282 * This is called when a child activity of this one calls its 5283 * finishActivity(). 5284 * 5285 * @param child The activity making the call. 5286 * @param requestCode Request code that had been used to start the 5287 * activity. 5288 */ 5289 public void finishActivityFromChild(@NonNull Activity child, int requestCode) { 5290 try { 5291 ActivityManagerNative.getDefault() 5292 .finishSubActivity(mToken, child.mEmbeddedID, requestCode); 5293 } catch (RemoteException e) { 5294 // Empty 5295 } 5296 } 5297 5298 /** 5299 * Call this when your activity is done and should be closed and the task should be completely 5300 * removed as a part of finishing the root activity of the task. 5301 */ 5302 public void finishAndRemoveTask() { 5303 finish(FINISH_TASK_WITH_ROOT_ACTIVITY); 5304 } 5305 5306 /** 5307 * Ask that the local app instance of this activity be released to free up its memory. 5308 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity -- 5309 * a new instance of the activity will later be re-created if needed due to the user 5310 * navigating back to it. 5311 * 5312 * @return Returns true if the activity was in a state that it has started the process 5313 * of destroying its current instance; returns false if for any reason this could not 5314 * be done: it is currently visible to the user, it is already being destroyed, it is 5315 * being finished, it hasn't yet saved its state, etc. 5316 */ 5317 public boolean releaseInstance() { 5318 try { 5319 return ActivityManagerNative.getDefault().releaseActivityInstance(mToken); 5320 } catch (RemoteException e) { 5321 // Empty 5322 } 5323 return false; 5324 } 5325 5326 /** 5327 * Called when an activity you launched exits, giving you the requestCode 5328 * you started it with, the resultCode it returned, and any additional 5329 * data from it. The <var>resultCode</var> will be 5330 * {@link #RESULT_CANCELED} if the activity explicitly returned that, 5331 * didn't return any result, or crashed during its operation. 5332 * 5333 * <p>You will receive this call immediately before onResume() when your 5334 * activity is re-starting. 5335 * 5336 * <p>This method is never invoked if your activity sets 5337 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to 5338 * <code>true</code>. 5339 * 5340 * @param requestCode The integer request code originally supplied to 5341 * startActivityForResult(), allowing you to identify who this 5342 * result came from. 5343 * @param resultCode The integer result code returned by the child activity 5344 * through its setResult(). 5345 * @param data An Intent, which can return result data to the caller 5346 * (various data can be attached to Intent "extras"). 5347 * 5348 * @see #startActivityForResult 5349 * @see #createPendingResult 5350 * @see #setResult(int) 5351 */ 5352 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 5353 } 5354 5355 /** 5356 * Called when an activity you launched with an activity transition exposes this 5357 * Activity through a returning activity transition, giving you the resultCode 5358 * and any additional data from it. This method will only be called if the activity 5359 * set a result code other than {@link #RESULT_CANCELED} and it supports activity 5360 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}. 5361 * 5362 * <p>The purpose of this function is to let the called Activity send a hint about 5363 * its state so that this underlying Activity can prepare to be exposed. A call to 5364 * this method does not guarantee that the called Activity has or will be exiting soon. 5365 * It only indicates that it will expose this Activity's Window and it has 5366 * some data to pass to prepare it.</p> 5367 * 5368 * @param resultCode The integer result code returned by the child activity 5369 * through its setResult(). 5370 * @param data An Intent, which can return result data to the caller 5371 * (various data can be attached to Intent "extras"). 5372 */ 5373 public void onActivityReenter(int resultCode, Intent data) { 5374 } 5375 5376 /** 5377 * Create a new PendingIntent object which you can hand to others 5378 * for them to use to send result data back to your 5379 * {@link #onActivityResult} callback. The created object will be either 5380 * one-shot (becoming invalid after a result is sent back) or multiple 5381 * (allowing any number of results to be sent through it). 5382 * 5383 * @param requestCode Private request code for the sender that will be 5384 * associated with the result data when it is returned. The sender can not 5385 * modify this value, allowing you to identify incoming results. 5386 * @param data Default data to supply in the result, which may be modified 5387 * by the sender. 5388 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT}, 5389 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE}, 5390 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT}, 5391 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT}, 5392 * or any of the flags as supported by 5393 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts 5394 * of the intent that can be supplied when the actual send happens. 5395 * 5396 * @return Returns an existing or new PendingIntent matching the given 5397 * parameters. May return null only if 5398 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been 5399 * supplied. 5400 * 5401 * @see PendingIntent 5402 */ 5403 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data, 5404 @PendingIntent.Flags int flags) { 5405 String packageName = getPackageName(); 5406 try { 5407 data.prepareToLeaveProcess(this); 5408 IIntentSender target = 5409 ActivityManagerNative.getDefault().getIntentSender( 5410 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, 5411 mParent == null ? mToken : mParent.mToken, 5412 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null, 5413 UserHandle.myUserId()); 5414 return target != null ? new PendingIntent(target) : null; 5415 } catch (RemoteException e) { 5416 // Empty 5417 } 5418 return null; 5419 } 5420 5421 /** 5422 * Change the desired orientation of this activity. If the activity 5423 * is currently in the foreground or otherwise impacting the screen 5424 * orientation, the screen will immediately be changed (possibly causing 5425 * the activity to be restarted). Otherwise, this will be used the next 5426 * time the activity is visible. 5427 * 5428 * @param requestedOrientation An orientation constant as used in 5429 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}. 5430 */ 5431 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) { 5432 if (mParent == null) { 5433 try { 5434 ActivityManagerNative.getDefault().setRequestedOrientation( 5435 mToken, requestedOrientation); 5436 } catch (RemoteException e) { 5437 // Empty 5438 } 5439 } else { 5440 mParent.setRequestedOrientation(requestedOrientation); 5441 } 5442 } 5443 5444 /** 5445 * Return the current requested orientation of the activity. This will 5446 * either be the orientation requested in its component's manifest, or 5447 * the last requested orientation given to 5448 * {@link #setRequestedOrientation(int)}. 5449 * 5450 * @return Returns an orientation constant as used in 5451 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}. 5452 */ 5453 @ActivityInfo.ScreenOrientation 5454 public int getRequestedOrientation() { 5455 if (mParent == null) { 5456 try { 5457 return ActivityManagerNative.getDefault() 5458 .getRequestedOrientation(mToken); 5459 } catch (RemoteException e) { 5460 // Empty 5461 } 5462 } else { 5463 return mParent.getRequestedOrientation(); 5464 } 5465 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 5466 } 5467 5468 /** 5469 * Return the identifier of the task this activity is in. This identifier 5470 * will remain the same for the lifetime of the activity. 5471 * 5472 * @return Task identifier, an opaque integer. 5473 */ 5474 public int getTaskId() { 5475 try { 5476 return ActivityManagerNative.getDefault() 5477 .getTaskForActivity(mToken, false); 5478 } catch (RemoteException e) { 5479 return -1; 5480 } 5481 } 5482 5483 /** 5484 * Return whether this activity is the root of a task. The root is the 5485 * first activity in a task. 5486 * 5487 * @return True if this is the root activity, else false. 5488 */ 5489 public boolean isTaskRoot() { 5490 try { 5491 return ActivityManagerNative.getDefault().getTaskForActivity(mToken, true) >= 0; 5492 } catch (RemoteException e) { 5493 return false; 5494 } 5495 } 5496 5497 /** 5498 * Move the task containing this activity to the back of the activity 5499 * stack. The activity's order within the task is unchanged. 5500 * 5501 * @param nonRoot If false then this only works if the activity is the root 5502 * of a task; if true it will work for any activity in 5503 * a task. 5504 * 5505 * @return If the task was moved (or it was already at the 5506 * back) true is returned, else false. 5507 */ 5508 public boolean moveTaskToBack(boolean nonRoot) { 5509 try { 5510 return ActivityManagerNative.getDefault().moveActivityTaskToBack( 5511 mToken, nonRoot); 5512 } catch (RemoteException e) { 5513 // Empty 5514 } 5515 return false; 5516 } 5517 5518 /** 5519 * Returns class name for this activity with the package prefix removed. 5520 * This is the default name used to read and write settings. 5521 * 5522 * @return The local class name. 5523 */ 5524 @NonNull 5525 public String getLocalClassName() { 5526 final String pkg = getPackageName(); 5527 final String cls = mComponent.getClassName(); 5528 int packageLen = pkg.length(); 5529 if (!cls.startsWith(pkg) || cls.length() <= packageLen 5530 || cls.charAt(packageLen) != '.') { 5531 return cls; 5532 } 5533 return cls.substring(packageLen+1); 5534 } 5535 5536 /** 5537 * Returns complete component name of this activity. 5538 * 5539 * @return Returns the complete component name for this activity 5540 */ 5541 public ComponentName getComponentName() 5542 { 5543 return mComponent; 5544 } 5545 5546 /** 5547 * Retrieve a {@link SharedPreferences} object for accessing preferences 5548 * that are private to this activity. This simply calls the underlying 5549 * {@link #getSharedPreferences(String, int)} method by passing in this activity's 5550 * class name as the preferences name. 5551 * 5552 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default 5553 * operation. 5554 * 5555 * @return Returns the single SharedPreferences instance that can be used 5556 * to retrieve and modify the preference values. 5557 */ 5558 public SharedPreferences getPreferences(int mode) { 5559 return getSharedPreferences(getLocalClassName(), mode); 5560 } 5561 5562 private void ensureSearchManager() { 5563 if (mSearchManager != null) { 5564 return; 5565 } 5566 5567 mSearchManager = new SearchManager(this, null); 5568 } 5569 5570 @Override 5571 public Object getSystemService(@ServiceName @NonNull String name) { 5572 if (getBaseContext() == null) { 5573 throw new IllegalStateException( 5574 "System services not available to Activities before onCreate()"); 5575 } 5576 5577 if (WINDOW_SERVICE.equals(name)) { 5578 return mWindowManager; 5579 } else if (SEARCH_SERVICE.equals(name)) { 5580 ensureSearchManager(); 5581 return mSearchManager; 5582 } 5583 return super.getSystemService(name); 5584 } 5585 5586 /** 5587 * Change the title associated with this activity. If this is a 5588 * top-level activity, the title for its window will change. If it 5589 * is an embedded activity, the parent can do whatever it wants 5590 * with it. 5591 */ 5592 public void setTitle(CharSequence title) { 5593 mTitle = title; 5594 onTitleChanged(title, mTitleColor); 5595 5596 if (mParent != null) { 5597 mParent.onChildTitleChanged(this, title); 5598 } 5599 } 5600 5601 /** 5602 * Change the title associated with this activity. If this is a 5603 * top-level activity, the title for its window will change. If it 5604 * is an embedded activity, the parent can do whatever it wants 5605 * with it. 5606 */ 5607 public void setTitle(int titleId) { 5608 setTitle(getText(titleId)); 5609 } 5610 5611 /** 5612 * Change the color of the title associated with this activity. 5613 * <p> 5614 * This method is deprecated starting in API Level 11 and replaced by action 5615 * bar styles. For information on styling the Action Bar, read the <a 5616 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer 5617 * guide. 5618 * 5619 * @deprecated Use action bar styles instead. 5620 */ 5621 @Deprecated 5622 public void setTitleColor(int textColor) { 5623 mTitleColor = textColor; 5624 onTitleChanged(mTitle, textColor); 5625 } 5626 5627 public final CharSequence getTitle() { 5628 return mTitle; 5629 } 5630 5631 public final int getTitleColor() { 5632 return mTitleColor; 5633 } 5634 5635 protected void onTitleChanged(CharSequence title, int color) { 5636 if (mTitleReady) { 5637 final Window win = getWindow(); 5638 if (win != null) { 5639 win.setTitle(title); 5640 if (color != 0) { 5641 win.setTitleColor(color); 5642 } 5643 } 5644 if (mActionBar != null) { 5645 mActionBar.setWindowTitle(title); 5646 } 5647 } 5648 } 5649 5650 protected void onChildTitleChanged(Activity childActivity, CharSequence title) { 5651 } 5652 5653 /** 5654 * Sets information describing the task with this activity for presentation inside the Recents 5655 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task 5656 * are traversed in order from the topmost activity to the bottommost. The traversal continues 5657 * for each property until a suitable value is found. For each task the taskDescription will be 5658 * returned in {@link android.app.ActivityManager.TaskDescription}. 5659 * 5660 * @see ActivityManager#getRecentTasks 5661 * @see android.app.ActivityManager.TaskDescription 5662 * 5663 * @param taskDescription The TaskDescription properties that describe the task with this activity 5664 */ 5665 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) { 5666 if (mTaskDescription != taskDescription) { 5667 mTaskDescription.copyFrom(taskDescription); 5668 // Scale the icon down to something reasonable if it is provided 5669 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) { 5670 final int size = ActivityManager.getLauncherLargeIconSizeInner(this); 5671 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size, 5672 true); 5673 mTaskDescription.setIcon(icon); 5674 } 5675 } 5676 try { 5677 ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription); 5678 } catch (RemoteException e) { 5679 } 5680 } 5681 5682 /** 5683 * Sets the visibility of the progress bar in the title. 5684 * <p> 5685 * In order for the progress bar to be shown, the feature must be requested 5686 * via {@link #requestWindowFeature(int)}. 5687 * 5688 * @param visible Whether to show the progress bars in the title. 5689 * @deprecated No longer supported starting in API 21. 5690 */ 5691 @Deprecated 5692 public final void setProgressBarVisibility(boolean visible) { 5693 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON : 5694 Window.PROGRESS_VISIBILITY_OFF); 5695 } 5696 5697 /** 5698 * Sets the visibility of the indeterminate progress bar in the title. 5699 * <p> 5700 * In order for the progress bar to be shown, the feature must be requested 5701 * via {@link #requestWindowFeature(int)}. 5702 * 5703 * @param visible Whether to show the progress bars in the title. 5704 * @deprecated No longer supported starting in API 21. 5705 */ 5706 @Deprecated 5707 public final void setProgressBarIndeterminateVisibility(boolean visible) { 5708 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 5709 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF); 5710 } 5711 5712 /** 5713 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular 5714 * is always indeterminate). 5715 * <p> 5716 * In order for the progress bar to be shown, the feature must be requested 5717 * via {@link #requestWindowFeature(int)}. 5718 * 5719 * @param indeterminate Whether the horizontal progress bar should be indeterminate. 5720 * @deprecated No longer supported starting in API 21. 5721 */ 5722 @Deprecated 5723 public final void setProgressBarIndeterminate(boolean indeterminate) { 5724 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 5725 indeterminate ? Window.PROGRESS_INDETERMINATE_ON 5726 : Window.PROGRESS_INDETERMINATE_OFF); 5727 } 5728 5729 /** 5730 * Sets the progress for the progress bars in the title. 5731 * <p> 5732 * In order for the progress bar to be shown, the feature must be requested 5733 * via {@link #requestWindowFeature(int)}. 5734 * 5735 * @param progress The progress for the progress bar. Valid ranges are from 5736 * 0 to 10000 (both inclusive). If 10000 is given, the progress 5737 * bar will be completely filled and will fade out. 5738 * @deprecated No longer supported starting in API 21. 5739 */ 5740 @Deprecated 5741 public final void setProgress(int progress) { 5742 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START); 5743 } 5744 5745 /** 5746 * Sets the secondary progress for the progress bar in the title. This 5747 * progress is drawn between the primary progress (set via 5748 * {@link #setProgress(int)} and the background. It can be ideal for media 5749 * scenarios such as showing the buffering progress while the default 5750 * progress shows the play progress. 5751 * <p> 5752 * In order for the progress bar to be shown, the feature must be requested 5753 * via {@link #requestWindowFeature(int)}. 5754 * 5755 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from 5756 * 0 to 10000 (both inclusive). 5757 * @deprecated No longer supported starting in API 21. 5758 */ 5759 @Deprecated 5760 public final void setSecondaryProgress(int secondaryProgress) { 5761 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, 5762 secondaryProgress + Window.PROGRESS_SECONDARY_START); 5763 } 5764 5765 /** 5766 * Suggests an audio stream whose volume should be changed by the hardware 5767 * volume controls. 5768 * <p> 5769 * The suggested audio stream will be tied to the window of this Activity. 5770 * Volume requests which are received while the Activity is in the 5771 * foreground will affect this stream. 5772 * <p> 5773 * It is not guaranteed that the hardware volume controls will always change 5774 * this stream's volume (for example, if a call is in progress, its stream's 5775 * volume may be changed instead). To reset back to the default, use 5776 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}. 5777 * 5778 * @param streamType The type of the audio stream whose volume should be 5779 * changed by the hardware volume controls. 5780 */ 5781 public final void setVolumeControlStream(int streamType) { 5782 getWindow().setVolumeControlStream(streamType); 5783 } 5784 5785 /** 5786 * Gets the suggested audio stream whose volume should be changed by the 5787 * hardware volume controls. 5788 * 5789 * @return The suggested audio stream type whose volume should be changed by 5790 * the hardware volume controls. 5791 * @see #setVolumeControlStream(int) 5792 */ 5793 public final int getVolumeControlStream() { 5794 return getWindow().getVolumeControlStream(); 5795 } 5796 5797 /** 5798 * Sets a {@link MediaController} to send media keys and volume changes to. 5799 * <p> 5800 * The controller will be tied to the window of this Activity. Media key and 5801 * volume events which are received while the Activity is in the foreground 5802 * will be forwarded to the controller and used to invoke transport controls 5803 * or adjust the volume. This may be used instead of or in addition to 5804 * {@link #setVolumeControlStream} to affect a specific session instead of a 5805 * specific stream. 5806 * <p> 5807 * It is not guaranteed that the hardware volume controls will always change 5808 * this session's volume (for example, if a call is in progress, its 5809 * stream's volume may be changed instead). To reset back to the default use 5810 * null as the controller. 5811 * 5812 * @param controller The controller for the session which should receive 5813 * media keys and volume changes. 5814 */ 5815 public final void setMediaController(MediaController controller) { 5816 getWindow().setMediaController(controller); 5817 } 5818 5819 /** 5820 * Gets the controller which should be receiving media key and volume events 5821 * while this activity is in the foreground. 5822 * 5823 * @return The controller which should receive events. 5824 * @see #setMediaController(android.media.session.MediaController) 5825 */ 5826 public final MediaController getMediaController() { 5827 return getWindow().getMediaController(); 5828 } 5829 5830 /** 5831 * Runs the specified action on the UI thread. If the current thread is the UI 5832 * thread, then the action is executed immediately. If the current thread is 5833 * not the UI thread, the action is posted to the event queue of the UI thread. 5834 * 5835 * @param action the action to run on the UI thread 5836 */ 5837 public final void runOnUiThread(Runnable action) { 5838 if (Thread.currentThread() != mUiThread) { 5839 mHandler.post(action); 5840 } else { 5841 action.run(); 5842 } 5843 } 5844 5845 /** 5846 * Standard implementation of 5847 * {@link android.view.LayoutInflater.Factory#onCreateView} used when 5848 * inflating with the LayoutInflater returned by {@link #getSystemService}. 5849 * This implementation does nothing and is for 5850 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps 5851 * should use {@link #onCreateView(View, String, Context, AttributeSet)}. 5852 * 5853 * @see android.view.LayoutInflater#createView 5854 * @see android.view.Window#getLayoutInflater 5855 */ 5856 @Nullable 5857 public View onCreateView(String name, Context context, AttributeSet attrs) { 5858 return null; 5859 } 5860 5861 /** 5862 * Standard implementation of 5863 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)} 5864 * used when inflating with the LayoutInflater returned by {@link #getSystemService}. 5865 * This implementation handles <fragment> tags to embed fragments inside 5866 * of the activity. 5867 * 5868 * @see android.view.LayoutInflater#createView 5869 * @see android.view.Window#getLayoutInflater 5870 */ 5871 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { 5872 if (!"fragment".equals(name)) { 5873 return onCreateView(name, context, attrs); 5874 } 5875 5876 return mFragments.onCreateView(parent, name, context, attrs); 5877 } 5878 5879 /** 5880 * Print the Activity's state into the given stream. This gets invoked if 5881 * you run "adb shell dumpsys activity <activity_component_name>". 5882 * 5883 * @param prefix Desired prefix to prepend at each line of output. 5884 * @param fd The raw file descriptor that the dump is being sent to. 5885 * @param writer The PrintWriter to which you should dump your state. This will be 5886 * closed for you after you return. 5887 * @param args additional arguments to the dump request. 5888 */ 5889 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 5890 dumpInner(prefix, fd, writer, args); 5891 } 5892 5893 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 5894 writer.print(prefix); writer.print("Local Activity "); 5895 writer.print(Integer.toHexString(System.identityHashCode(this))); 5896 writer.println(" State:"); 5897 String innerPrefix = prefix + " "; 5898 writer.print(innerPrefix); writer.print("mResumed="); 5899 writer.print(mResumed); writer.print(" mStopped="); 5900 writer.print(mStopped); writer.print(" mFinished="); 5901 writer.println(mFinished); 5902 writer.print(innerPrefix); writer.print("mChangingConfigurations="); 5903 writer.println(mChangingConfigurations); 5904 writer.print(innerPrefix); writer.print("mCurrentConfig="); 5905 writer.println(mCurrentConfig); 5906 5907 mFragments.dumpLoaders(innerPrefix, fd, writer, args); 5908 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args); 5909 if (mVoiceInteractor != null) { 5910 mVoiceInteractor.dump(innerPrefix, fd, writer, args); 5911 } 5912 5913 if (getWindow() != null && 5914 getWindow().peekDecorView() != null && 5915 getWindow().peekDecorView().getViewRootImpl() != null) { 5916 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args); 5917 } 5918 5919 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix); 5920 } 5921 5922 /** 5923 * Bit indicating that this activity is "immersive" and should not be 5924 * interrupted by notifications if possible. 5925 * 5926 * This value is initially set by the manifest property 5927 * <code>android:immersive</code> but may be changed at runtime by 5928 * {@link #setImmersive}. 5929 * 5930 * @see #setImmersive(boolean) 5931 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE 5932 */ 5933 public boolean isImmersive() { 5934 try { 5935 return ActivityManagerNative.getDefault().isImmersive(mToken); 5936 } catch (RemoteException e) { 5937 return false; 5938 } 5939 } 5940 5941 /** 5942 * Indication of whether this is the highest level activity in this task. Can be used to 5943 * determine whether an activity launched by this activity was placed in the same task or 5944 * another task. 5945 * 5946 * @return true if this is the topmost, non-finishing activity in its task. 5947 */ 5948 private boolean isTopOfTask() { 5949 if (mToken == null || mWindow == null || !mWindowAdded) { 5950 return false; 5951 } 5952 try { 5953 return ActivityManagerNative.getDefault().isTopOfTask(mToken); 5954 } catch (RemoteException e) { 5955 return false; 5956 } 5957 } 5958 5959 /** 5960 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a 5961 * fullscreen opaque Activity. 5962 * <p> 5963 * Call this whenever the background of a translucent Activity has changed to become opaque. 5964 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released. 5965 * <p> 5966 * This call has no effect on non-translucent activities or on activities with the 5967 * {@link android.R.attr#windowIsFloating} attribute. 5968 * 5969 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener, 5970 * ActivityOptions) 5971 * @see TranslucentConversionListener 5972 * 5973 * @hide 5974 */ 5975 @SystemApi 5976 public void convertFromTranslucent() { 5977 try { 5978 mTranslucentCallback = null; 5979 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) { 5980 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true); 5981 } 5982 } catch (RemoteException e) { 5983 // pass 5984 } 5985 } 5986 5987 /** 5988 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from 5989 * opaque to translucent following a call to {@link #convertFromTranslucent()}. 5990 * <p> 5991 * Calling this allows the Activity behind this one to be seen again. Once all such Activities 5992 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will 5993 * be called indicating that it is safe to make this activity translucent again. Until 5994 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image 5995 * behind the frontmost Activity will be indeterminate. 5996 * <p> 5997 * This call has no effect on non-translucent activities or on activities with the 5998 * {@link android.R.attr#windowIsFloating} attribute. 5999 * 6000 * @param callback the method to call when all visible Activities behind this one have been 6001 * drawn and it is safe to make this Activity translucent again. 6002 * @param options activity options delivered to the activity below this one. The options 6003 * are retrieved using {@link #getActivityOptions}. 6004 * @return <code>true</code> if Window was opaque and will become translucent or 6005 * <code>false</code> if window was translucent and no change needed to be made. 6006 * 6007 * @see #convertFromTranslucent() 6008 * @see TranslucentConversionListener 6009 * 6010 * @hide 6011 */ 6012 @SystemApi 6013 public boolean convertToTranslucent(TranslucentConversionListener callback, 6014 ActivityOptions options) { 6015 boolean drawComplete; 6016 try { 6017 mTranslucentCallback = callback; 6018 mChangeCanvasToTranslucent = 6019 ActivityManagerNative.getDefault().convertToTranslucent(mToken, options); 6020 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false); 6021 drawComplete = true; 6022 } catch (RemoteException e) { 6023 // Make callback return as though it timed out. 6024 mChangeCanvasToTranslucent = false; 6025 drawComplete = false; 6026 } 6027 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) { 6028 // Window is already translucent. 6029 mTranslucentCallback.onTranslucentConversionComplete(drawComplete); 6030 } 6031 return mChangeCanvasToTranslucent; 6032 } 6033 6034 /** @hide */ 6035 void onTranslucentConversionComplete(boolean drawComplete) { 6036 if (mTranslucentCallback != null) { 6037 mTranslucentCallback.onTranslucentConversionComplete(drawComplete); 6038 mTranslucentCallback = null; 6039 } 6040 if (mChangeCanvasToTranslucent) { 6041 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false); 6042 } 6043 } 6044 6045 /** @hide */ 6046 public void onNewActivityOptions(ActivityOptions options) { 6047 mActivityTransitionState.setEnterActivityOptions(this, options); 6048 if (!mStopped) { 6049 mActivityTransitionState.enterReady(this); 6050 } 6051 } 6052 6053 /** 6054 * Retrieve the ActivityOptions passed in from the launching activity or passed back 6055 * from an activity launched by this activity in its call to {@link 6056 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)} 6057 * 6058 * @return The ActivityOptions passed to {@link #convertToTranslucent}. 6059 * @hide 6060 */ 6061 ActivityOptions getActivityOptions() { 6062 try { 6063 return ActivityManagerNative.getDefault().getActivityOptions(mToken); 6064 } catch (RemoteException e) { 6065 } 6066 return null; 6067 } 6068 6069 /** 6070 * Activities that want to remain visible behind a translucent activity above them must call 6071 * this method anytime between the start of {@link #onResume()} and the return from 6072 * {@link #onPause()}. If this call is successful then the activity will remain visible after 6073 * {@link #onPause()} is called, and is allowed to continue playing media in the background. 6074 * 6075 * <p>The actions of this call are reset each time that this activity is brought to the 6076 * front. That is, every time {@link #onResume()} is called the activity will be assumed 6077 * to not have requested visible behind. Therefore, if you want this activity to continue to 6078 * be visible in the background you must call this method again. 6079 * 6080 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop 6081 * for dialog and translucent activities. 6082 * 6083 * <p>Under all circumstances, the activity must stop playing and release resources prior to or 6084 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false. 6085 * 6086 * <p>False will be returned any time this method is called between the return of onPause and 6087 * the next call to onResume. 6088 * 6089 * @param visible true to notify the system that the activity wishes to be visible behind other 6090 * translucent activities, false to indicate otherwise. Resources must be 6091 * released when passing false to this method. 6092 * @return the resulting visibiity state. If true the activity will remain visible beyond 6093 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false 6094 * then the activity may not count on being visible behind other translucent activities, 6095 * and must stop any media playback and release resources. 6096 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so 6097 * the return value must be checked. 6098 * 6099 * @see #onVisibleBehindCanceled() 6100 * @see #onBackgroundVisibleBehindChanged(boolean) 6101 */ 6102 public boolean requestVisibleBehind(boolean visible) { 6103 if (!mResumed) { 6104 // Do not permit paused or stopped activities to do this. 6105 visible = false; 6106 } 6107 try { 6108 mVisibleBehind = ActivityManagerNative.getDefault() 6109 .requestVisibleBehind(mToken, visible) && visible; 6110 } catch (RemoteException e) { 6111 mVisibleBehind = false; 6112 } 6113 return mVisibleBehind; 6114 } 6115 6116 /** 6117 * Called when a translucent activity over this activity is becoming opaque or another 6118 * activity is being launched. Activities that override this method must call 6119 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown. 6120 * 6121 * <p>When this method is called the activity has 500 msec to release any resources it may be 6122 * using while visible in the background. 6123 * If the activity has not returned from this method in 500 msec the system will destroy 6124 * the activity and kill the process in order to recover the resources for another 6125 * process. Otherwise {@link #onStop()} will be called following return. 6126 * 6127 * @see #requestVisibleBehind(boolean) 6128 * @see #onBackgroundVisibleBehindChanged(boolean) 6129 */ 6130 @CallSuper 6131 public void onVisibleBehindCanceled() { 6132 mCalled = true; 6133 } 6134 6135 /** 6136 * Translucent activities may call this to determine if there is an activity below them that 6137 * is currently set to be visible in the background. 6138 * 6139 * @return true if an activity below is set to visible according to the most recent call to 6140 * {@link #requestVisibleBehind(boolean)}, false otherwise. 6141 * 6142 * @see #requestVisibleBehind(boolean) 6143 * @see #onVisibleBehindCanceled() 6144 * @see #onBackgroundVisibleBehindChanged(boolean) 6145 * @hide 6146 */ 6147 @SystemApi 6148 public boolean isBackgroundVisibleBehind() { 6149 try { 6150 return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken); 6151 } catch (RemoteException e) { 6152 } 6153 return false; 6154 } 6155 6156 /** 6157 * The topmost foreground activity will receive this call when the background visibility state 6158 * of the activity below it changes. 6159 * 6160 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be 6161 * due to a background activity finishing itself. 6162 * 6163 * @param visible true if a background activity is visible, false otherwise. 6164 * 6165 * @see #requestVisibleBehind(boolean) 6166 * @see #onVisibleBehindCanceled() 6167 * @hide 6168 */ 6169 @SystemApi 6170 public void onBackgroundVisibleBehindChanged(boolean visible) { 6171 } 6172 6173 /** 6174 * Activities cannot draw during the period that their windows are animating in. In order 6175 * to know when it is safe to begin drawing they can override this method which will be 6176 * called when the entering animation has completed. 6177 */ 6178 public void onEnterAnimationComplete() { 6179 } 6180 6181 /** 6182 * @hide 6183 */ 6184 public void dispatchEnterAnimationComplete() { 6185 onEnterAnimationComplete(); 6186 if (getWindow() != null && getWindow().getDecorView() != null) { 6187 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete(); 6188 } 6189 } 6190 6191 /** 6192 * Adjust the current immersive mode setting. 6193 * 6194 * Note that changing this value will have no effect on the activity's 6195 * {@link android.content.pm.ActivityInfo} structure; that is, if 6196 * <code>android:immersive</code> is set to <code>true</code> 6197 * in the application's manifest entry for this activity, the {@link 6198 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will 6199 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE 6200 * FLAG_IMMERSIVE} bit set. 6201 * 6202 * @see #isImmersive() 6203 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE 6204 */ 6205 public void setImmersive(boolean i) { 6206 try { 6207 ActivityManagerNative.getDefault().setImmersive(mToken, i); 6208 } catch (RemoteException e) { 6209 // pass 6210 } 6211 } 6212 6213 /** 6214 * Enable or disable virtual reality (VR) mode. 6215 * 6216 * <p>VR mode is a hint to Android system services to switch to a mode optimized for 6217 * high-performance stereoscopic rendering. This mode will be enabled while this Activity has 6218 * focus.</p> 6219 * 6220 * @param enabled {@code true} to enable this mode. 6221 * @param requestedComponent the name of the component to use as a 6222 * {@link android.service.vr.VrListenerService} while VR mode is enabled. 6223 * 6224 * @throws android.content.pm.PackageManager.NameNotFoundException; 6225 */ 6226 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent) 6227 throws PackageManager.NameNotFoundException { 6228 try { 6229 if (ActivityManagerNative.getDefault().setVrMode(mToken, enabled, requestedComponent) 6230 != 0) { 6231 throw new PackageManager.NameNotFoundException( 6232 requestedComponent.flattenToString()); 6233 } 6234 } catch (RemoteException e) { 6235 // pass 6236 } 6237 } 6238 6239 /** 6240 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}. 6241 * 6242 * @param callback Callback that will manage lifecycle events for this action mode 6243 * @return The ActionMode that was started, or null if it was canceled 6244 * 6245 * @see ActionMode 6246 */ 6247 @Nullable 6248 public ActionMode startActionMode(ActionMode.Callback callback) { 6249 return mWindow.getDecorView().startActionMode(callback); 6250 } 6251 6252 /** 6253 * Start an action mode of the given type. 6254 * 6255 * @param callback Callback that will manage lifecycle events for this action mode 6256 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 6257 * @return The ActionMode that was started, or null if it was canceled 6258 * 6259 * @see ActionMode 6260 */ 6261 @Nullable 6262 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 6263 return mWindow.getDecorView().startActionMode(callback, type); 6264 } 6265 6266 /** 6267 * Give the Activity a chance to control the UI for an action mode requested 6268 * by the system. 6269 * 6270 * <p>Note: If you are looking for a notification callback that an action mode 6271 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p> 6272 * 6273 * @param callback The callback that should control the new action mode 6274 * @return The new action mode, or <code>null</code> if the activity does not want to 6275 * provide special handling for this action mode. (It will be handled by the system.) 6276 */ 6277 @Nullable 6278 @Override 6279 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) { 6280 // Only Primary ActionModes are represented in the ActionBar. 6281 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) { 6282 initWindowDecorActionBar(); 6283 if (mActionBar != null) { 6284 return mActionBar.startActionMode(callback); 6285 } 6286 } 6287 return null; 6288 } 6289 6290 /** 6291 * {@inheritDoc} 6292 */ 6293 @Nullable 6294 @Override 6295 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) { 6296 try { 6297 mActionModeTypeStarting = type; 6298 return onWindowStartingActionMode(callback); 6299 } finally { 6300 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY; 6301 } 6302 } 6303 6304 /** 6305 * Notifies the Activity that an action mode has been started. 6306 * Activity subclasses overriding this method should call the superclass implementation. 6307 * 6308 * @param mode The new action mode. 6309 */ 6310 @CallSuper 6311 @Override 6312 public void onActionModeStarted(ActionMode mode) { 6313 } 6314 6315 /** 6316 * Notifies the activity that an action mode has finished. 6317 * Activity subclasses overriding this method should call the superclass implementation. 6318 * 6319 * @param mode The action mode that just finished. 6320 */ 6321 @CallSuper 6322 @Override 6323 public void onActionModeFinished(ActionMode mode) { 6324 } 6325 6326 /** 6327 * Returns true if the app should recreate the task when navigating 'up' from this activity 6328 * by using targetIntent. 6329 * 6330 * <p>If this method returns false the app can trivially call 6331 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform 6332 * up navigation. If this method returns false, the app should synthesize a new task stack 6333 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p> 6334 * 6335 * @param targetIntent An intent representing the target destination for up navigation 6336 * @return true if navigating up should recreate a new task stack, false if the same task 6337 * should be used for the destination 6338 */ 6339 public boolean shouldUpRecreateTask(Intent targetIntent) { 6340 try { 6341 PackageManager pm = getPackageManager(); 6342 ComponentName cn = targetIntent.getComponent(); 6343 if (cn == null) { 6344 cn = targetIntent.resolveActivity(pm); 6345 } 6346 ActivityInfo info = pm.getActivityInfo(cn, 0); 6347 if (info.taskAffinity == null) { 6348 return false; 6349 } 6350 return ActivityManagerNative.getDefault() 6351 .shouldUpRecreateTask(mToken, info.taskAffinity); 6352 } catch (RemoteException e) { 6353 return false; 6354 } catch (NameNotFoundException e) { 6355 return false; 6356 } 6357 } 6358 6359 /** 6360 * Navigate from this activity to the activity specified by upIntent, finishing this activity 6361 * in the process. If the activity indicated by upIntent already exists in the task's history, 6362 * this activity and all others before the indicated activity in the history stack will be 6363 * finished. 6364 * 6365 * <p>If the indicated activity does not appear in the history stack, this will finish 6366 * each activity in this task until the root activity of the task is reached, resulting in 6367 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy 6368 * when an activity may be reached by a path not passing through a canonical parent 6369 * activity.</p> 6370 * 6371 * <p>This method should be used when performing up navigation from within the same task 6372 * as the destination. If up navigation should cross tasks in some cases, see 6373 * {@link #shouldUpRecreateTask(Intent)}.</p> 6374 * 6375 * @param upIntent An intent representing the target destination for up navigation 6376 * 6377 * @return true if up navigation successfully reached the activity indicated by upIntent and 6378 * upIntent was delivered to it. false if an instance of the indicated activity could 6379 * not be found and this activity was simply finished normally. 6380 */ 6381 public boolean navigateUpTo(Intent upIntent) { 6382 if (mParent == null) { 6383 ComponentName destInfo = upIntent.getComponent(); 6384 if (destInfo == null) { 6385 destInfo = upIntent.resolveActivity(getPackageManager()); 6386 if (destInfo == null) { 6387 return false; 6388 } 6389 upIntent = new Intent(upIntent); 6390 upIntent.setComponent(destInfo); 6391 } 6392 int resultCode; 6393 Intent resultData; 6394 synchronized (this) { 6395 resultCode = mResultCode; 6396 resultData = mResultData; 6397 } 6398 if (resultData != null) { 6399 resultData.prepareToLeaveProcess(this); 6400 } 6401 try { 6402 upIntent.prepareToLeaveProcess(this); 6403 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent, 6404 resultCode, resultData); 6405 } catch (RemoteException e) { 6406 return false; 6407 } 6408 } else { 6409 return mParent.navigateUpToFromChild(this, upIntent); 6410 } 6411 } 6412 6413 /** 6414 * This is called when a child activity of this one calls its 6415 * {@link #navigateUpTo} method. The default implementation simply calls 6416 * navigateUpTo(upIntent) on this activity (the parent). 6417 * 6418 * @param child The activity making the call. 6419 * @param upIntent An intent representing the target destination for up navigation 6420 * 6421 * @return true if up navigation successfully reached the activity indicated by upIntent and 6422 * upIntent was delivered to it. false if an instance of the indicated activity could 6423 * not be found and this activity was simply finished normally. 6424 */ 6425 public boolean navigateUpToFromChild(Activity child, Intent upIntent) { 6426 return navigateUpTo(upIntent); 6427 } 6428 6429 /** 6430 * Obtain an {@link Intent} that will launch an explicit target activity specified by 6431 * this activity's logical parent. The logical parent is named in the application's manifest 6432 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute. 6433 * Activity subclasses may override this method to modify the Intent returned by 6434 * super.getParentActivityIntent() or to implement a different mechanism of retrieving 6435 * the parent intent entirely. 6436 * 6437 * @return a new Intent targeting the defined parent of this activity or null if 6438 * there is no valid parent. 6439 */ 6440 @Nullable 6441 public Intent getParentActivityIntent() { 6442 final String parentName = mActivityInfo.parentActivityName; 6443 if (TextUtils.isEmpty(parentName)) { 6444 return null; 6445 } 6446 6447 // If the parent itself has no parent, generate a main activity intent. 6448 final ComponentName target = new ComponentName(this, parentName); 6449 try { 6450 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0); 6451 final String parentActivity = parentInfo.parentActivityName; 6452 final Intent parentIntent = parentActivity == null 6453 ? Intent.makeMainActivity(target) 6454 : new Intent().setComponent(target); 6455 return parentIntent; 6456 } catch (NameNotFoundException e) { 6457 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName + 6458 "' in manifest"); 6459 return null; 6460 } 6461 } 6462 6463 /** 6464 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 6465 * android.view.View, String)} was used to start an Activity, <var>callback</var> 6466 * will be called to handle shared elements on the <i>launched</i> Activity. This requires 6467 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}. 6468 * 6469 * @param callback Used to manipulate shared element transitions on the launched Activity. 6470 */ 6471 public void setEnterSharedElementCallback(SharedElementCallback callback) { 6472 if (callback == null) { 6473 callback = SharedElementCallback.NULL_CALLBACK; 6474 } 6475 mEnterTransitionListener = callback; 6476 } 6477 6478 /** 6479 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 6480 * android.view.View, String)} was used to start an Activity, <var>callback</var> 6481 * will be called to handle shared elements on the <i>launching</i> Activity. Most 6482 * calls will only come when returning from the started Activity. 6483 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}. 6484 * 6485 * @param callback Used to manipulate shared element transitions on the launching Activity. 6486 */ 6487 public void setExitSharedElementCallback(SharedElementCallback callback) { 6488 if (callback == null) { 6489 callback = SharedElementCallback.NULL_CALLBACK; 6490 } 6491 mExitTransitionListener = callback; 6492 } 6493 6494 /** 6495 * Postpone the entering activity transition when Activity was started with 6496 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 6497 * android.util.Pair[])}. 6498 * <p>This method gives the Activity the ability to delay starting the entering and 6499 * shared element transitions until all data is loaded. Until then, the Activity won't 6500 * draw into its window, leaving the window transparent. This may also cause the 6501 * returning animation to be delayed until data is ready. This method should be 6502 * called in {@link #onCreate(android.os.Bundle)} or in 6503 * {@link #onActivityReenter(int, android.content.Intent)}. 6504 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to 6505 * start the transitions. If the Activity did not use 6506 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, 6507 * android.util.Pair[])}, then this method does nothing.</p> 6508 */ 6509 public void postponeEnterTransition() { 6510 mActivityTransitionState.postponeEnterTransition(); 6511 } 6512 6513 /** 6514 * Begin postponed transitions after {@link #postponeEnterTransition()} was called. 6515 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition() 6516 * to have your Activity start drawing. 6517 */ 6518 public void startPostponedEnterTransition() { 6519 mActivityTransitionState.startPostponedEnterTransition(); 6520 } 6521 6522 /** 6523 * Create {@link DropPermissions} object bound to this activity and controlling the access 6524 * permissions for content URIs associated with the {@link DragEvent}. 6525 * @param event Drag event 6526 * @return The DropPermissions object used to control access to the content URIs. Null if 6527 * no content URIs are associated with the event or if permissions could not be granted. 6528 */ 6529 public DropPermissions requestDropPermissions(DragEvent event) { 6530 DropPermissions dropPermissions = DropPermissions.obtain(event); 6531 if (dropPermissions != null && dropPermissions.take(getActivityToken())) { 6532 return dropPermissions; 6533 } 6534 return null; 6535 } 6536 6537 // ------------------ Internal API ------------------ 6538 6539 final void setParent(Activity parent) { 6540 mParent = parent; 6541 } 6542 6543 final void attach(Context context, ActivityThread aThread, 6544 Instrumentation instr, IBinder token, int ident, 6545 Application application, Intent intent, ActivityInfo info, 6546 CharSequence title, Activity parent, String id, 6547 NonConfigurationInstances lastNonConfigurationInstances, 6548 Configuration config, String referrer, IVoiceInteractor voiceInteractor, 6549 Window window) { 6550 attachBaseContext(context); 6551 6552 mFragments.attachHost(null /*parent*/); 6553 6554 mWindow = new PhoneWindow(this, window); 6555 mWindow.setWindowControllerCallback(this); 6556 mWindow.setCallback(this); 6557 mWindow.setOnWindowDismissedCallback(this); 6558 mWindow.getLayoutInflater().setPrivateFactory(this); 6559 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) { 6560 mWindow.setSoftInputMode(info.softInputMode); 6561 } 6562 if (info.uiOptions != 0) { 6563 mWindow.setUiOptions(info.uiOptions); 6564 } 6565 mUiThread = Thread.currentThread(); 6566 6567 mMainThread = aThread; 6568 mInstrumentation = instr; 6569 mToken = token; 6570 mIdent = ident; 6571 mApplication = application; 6572 mIntent = intent; 6573 mReferrer = referrer; 6574 mComponent = intent.getComponent(); 6575 mActivityInfo = info; 6576 mTitle = title; 6577 mParent = parent; 6578 mEmbeddedID = id; 6579 mLastNonConfigurationInstances = lastNonConfigurationInstances; 6580 if (voiceInteractor != null) { 6581 if (lastNonConfigurationInstances != null) { 6582 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor; 6583 } else { 6584 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this, 6585 Looper.myLooper()); 6586 } 6587 } 6588 6589 mWindow.setWindowManager( 6590 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE), 6591 mToken, mComponent.flattenToString(), 6592 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0); 6593 if (mParent != null) { 6594 mWindow.setContainer(mParent.getWindow()); 6595 } 6596 mWindowManager = mWindow.getWindowManager(); 6597 mCurrentConfig = config; 6598 } 6599 6600 /** @hide */ 6601 public final IBinder getActivityToken() { 6602 return mParent != null ? mParent.getActivityToken() : mToken; 6603 } 6604 6605 final void performCreateCommon() { 6606 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean( 6607 com.android.internal.R.styleable.Window_windowNoDisplay, false); 6608 mFragments.dispatchActivityCreated(); 6609 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions()); 6610 } 6611 6612 final void performCreate(Bundle icicle) { 6613 restoreHasCurrentPermissionRequest(icicle); 6614 onCreate(icicle); 6615 mActivityTransitionState.readState(icicle); 6616 performCreateCommon(); 6617 } 6618 6619 final void performCreate(Bundle icicle, PersistableBundle persistentState) { 6620 restoreHasCurrentPermissionRequest(icicle); 6621 onCreate(icicle, persistentState); 6622 mActivityTransitionState.readState(icicle); 6623 performCreateCommon(); 6624 } 6625 6626 final void performStart() { 6627 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions()); 6628 mFragments.noteStateNotSaved(); 6629 mCalled = false; 6630 mFragments.execPendingActions(); 6631 mInstrumentation.callActivityOnStart(this); 6632 if (!mCalled) { 6633 throw new SuperNotCalledException( 6634 "Activity " + mComponent.toShortString() + 6635 " did not call through to super.onStart()"); 6636 } 6637 mFragments.dispatchStart(); 6638 mFragments.reportLoaderStart(); 6639 6640 // This property is set for all builds except final release 6641 boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1; 6642 boolean isAppDebuggable = 6643 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 6644 6645 if (isAppDebuggable || isDlwarningEnabled) { 6646 String dlwarning = getDlWarning(); 6647 if (dlwarning != null) { 6648 String appName = getApplicationInfo().loadLabel(getPackageManager()) 6649 .toString(); 6650 String warning = "Detected problems with app native libraries\n" + 6651 "(please consult log for detail):\n" + dlwarning; 6652 if (isAppDebuggable) { 6653 new AlertDialog.Builder(this). 6654 setTitle(appName). 6655 setMessage(warning). 6656 setPositiveButton(android.R.string.ok, null). 6657 setCancelable(false). 6658 show(); 6659 } else { 6660 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show(); 6661 } 6662 } 6663 } 6664 6665 mActivityTransitionState.enterReady(this); 6666 } 6667 6668 final void performRestart() { 6669 mFragments.noteStateNotSaved(); 6670 6671 if (mToken != null && mParent == null) { 6672 // No need to check mStopped, the roots will check if they were actually stopped. 6673 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */); 6674 } 6675 6676 if (mStopped) { 6677 mStopped = false; 6678 6679 synchronized (mManagedCursors) { 6680 final int N = mManagedCursors.size(); 6681 for (int i=0; i<N; i++) { 6682 ManagedCursor mc = mManagedCursors.get(i); 6683 if (mc.mReleased || mc.mUpdated) { 6684 if (!mc.mCursor.requery()) { 6685 if (getApplicationInfo().targetSdkVersion 6686 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 6687 throw new IllegalStateException( 6688 "trying to requery an already closed cursor " 6689 + mc.mCursor); 6690 } 6691 } 6692 mc.mReleased = false; 6693 mc.mUpdated = false; 6694 } 6695 } 6696 } 6697 6698 mCalled = false; 6699 mInstrumentation.callActivityOnRestart(this); 6700 if (!mCalled) { 6701 throw new SuperNotCalledException( 6702 "Activity " + mComponent.toShortString() + 6703 " did not call through to super.onRestart()"); 6704 } 6705 performStart(); 6706 } 6707 } 6708 6709 final void performResume() { 6710 performRestart(); 6711 6712 mFragments.execPendingActions(); 6713 6714 mLastNonConfigurationInstances = null; 6715 6716 mCalled = false; 6717 // mResumed is set by the instrumentation 6718 mInstrumentation.callActivityOnResume(this); 6719 if (!mCalled) { 6720 throw new SuperNotCalledException( 6721 "Activity " + mComponent.toShortString() + 6722 " did not call through to super.onResume()"); 6723 } 6724 6725 // invisible activities must be finished before onResume() completes 6726 if (!mVisibleFromClient && !mFinished) { 6727 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes"); 6728 if (getApplicationInfo().targetSdkVersion 6729 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { 6730 throw new IllegalStateException( 6731 "Activity " + mComponent.toShortString() + 6732 " did not call finish() prior to onResume() completing"); 6733 } 6734 } 6735 6736 // Now really resume, and install the current status bar and menu. 6737 mCalled = false; 6738 6739 mFragments.dispatchResume(); 6740 mFragments.execPendingActions(); 6741 6742 onPostResume(); 6743 if (!mCalled) { 6744 throw new SuperNotCalledException( 6745 "Activity " + mComponent.toShortString() + 6746 " did not call through to super.onPostResume()"); 6747 } 6748 } 6749 6750 final void performPause() { 6751 mDoReportFullyDrawn = false; 6752 mFragments.dispatchPause(); 6753 mCalled = false; 6754 onPause(); 6755 mResumed = false; 6756 if (!mCalled && getApplicationInfo().targetSdkVersion 6757 >= android.os.Build.VERSION_CODES.GINGERBREAD) { 6758 throw new SuperNotCalledException( 6759 "Activity " + mComponent.toShortString() + 6760 " did not call through to super.onPause()"); 6761 } 6762 mResumed = false; 6763 } 6764 6765 final void performUserLeaving() { 6766 onUserInteraction(); 6767 onUserLeaveHint(); 6768 } 6769 6770 final void performStop(boolean preserveWindow) { 6771 mDoReportFullyDrawn = false; 6772 mFragments.doLoaderStop(mChangingConfigurations /*retain*/); 6773 6774 if (!mStopped) { 6775 if (mWindow != null) { 6776 mWindow.closeAllPanels(); 6777 } 6778 6779 // If we're preserving the window, don't setStoppedState to true, since we 6780 // need the window started immediately again. Stopping the window will 6781 // destroys hardware resources and causes flicker. 6782 if (!preserveWindow && mToken != null && mParent == null) { 6783 WindowManagerGlobal.getInstance().setStoppedState(mToken, true); 6784 } 6785 6786 mFragments.dispatchStop(); 6787 6788 mCalled = false; 6789 mInstrumentation.callActivityOnStop(this); 6790 if (!mCalled) { 6791 throw new SuperNotCalledException( 6792 "Activity " + mComponent.toShortString() + 6793 " did not call through to super.onStop()"); 6794 } 6795 6796 synchronized (mManagedCursors) { 6797 final int N = mManagedCursors.size(); 6798 for (int i=0; i<N; i++) { 6799 ManagedCursor mc = mManagedCursors.get(i); 6800 if (!mc.mReleased) { 6801 mc.mCursor.deactivate(); 6802 mc.mReleased = true; 6803 } 6804 } 6805 } 6806 6807 mStopped = true; 6808 } 6809 mResumed = false; 6810 } 6811 6812 final void performDestroy() { 6813 mDestroyed = true; 6814 mWindow.destroy(); 6815 mFragments.dispatchDestroy(); 6816 onDestroy(); 6817 mFragments.doLoaderDestroy(); 6818 if (mVoiceInteractor != null) { 6819 mVoiceInteractor.detachActivity(); 6820 } 6821 } 6822 6823 /** 6824 * @hide 6825 */ 6826 public final boolean isResumed() { 6827 return mResumed; 6828 } 6829 6830 private void storeHasCurrentPermissionRequest(Bundle bundle) { 6831 if (bundle != null && mHasCurrentPermissionsRequest) { 6832 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true); 6833 } 6834 } 6835 6836 private void restoreHasCurrentPermissionRequest(Bundle bundle) { 6837 if (bundle != null) { 6838 mHasCurrentPermissionsRequest = bundle.getBoolean( 6839 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false); 6840 } 6841 } 6842 6843 void dispatchActivityResult(String who, int requestCode, 6844 int resultCode, Intent data) { 6845 if (false) Log.v( 6846 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode 6847 + ", resCode=" + resultCode + ", data=" + data); 6848 mFragments.noteStateNotSaved(); 6849 if (who == null) { 6850 onActivityResult(requestCode, resultCode, data); 6851 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) { 6852 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length()); 6853 if (TextUtils.isEmpty(who)) { 6854 dispatchRequestPermissionsResult(requestCode, data); 6855 } else { 6856 Fragment frag = mFragments.findFragmentByWho(who); 6857 if (frag != null) { 6858 dispatchRequestPermissionsResultToFragment(requestCode, data, frag); 6859 } 6860 } 6861 } else if (who.startsWith("@android:view:")) { 6862 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews( 6863 getActivityToken()); 6864 for (ViewRootImpl viewRoot : views) { 6865 if (viewRoot.getView() != null 6866 && viewRoot.getView().dispatchActivityResult( 6867 who, requestCode, resultCode, data)) { 6868 return; 6869 } 6870 } 6871 } else { 6872 Fragment frag = mFragments.findFragmentByWho(who); 6873 if (frag != null) { 6874 frag.onActivityResult(requestCode, resultCode, data); 6875 } 6876 } 6877 } 6878 6879 /** 6880 * Request to put this Activity in a mode where the user is locked to the 6881 * current task. 6882 * 6883 * This will prevent the user from launching other apps, going to settings, or reaching the 6884 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode} 6885 * values permit launching while locked. 6886 * 6887 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or 6888 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into 6889 * Lock Task mode. The user will not be able to exit this mode until 6890 * {@link Activity#stopLockTask()} is called. 6891 * 6892 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false 6893 * then the system will prompt the user with a dialog requesting permission to enter 6894 * this mode. When entered through this method the user can exit at any time through 6895 * an action described by the request dialog. Calling stopLockTask will also exit the 6896 * mode. 6897 * 6898 * @see android.R.attr#lockTaskMode 6899 */ 6900 public void startLockTask() { 6901 try { 6902 ActivityManagerNative.getDefault().startLockTaskMode(mToken); 6903 } catch (RemoteException e) { 6904 } 6905 } 6906 6907 /** 6908 * Allow the user to switch away from the current task. 6909 * 6910 * Called to end the mode started by {@link Activity#startLockTask}. This 6911 * can only be called by activities that have successfully called 6912 * startLockTask previously. 6913 * 6914 * This will allow the user to exit this app and move onto other activities. 6915 * <p>Note: This method should only be called when the activity is user-facing. That is, 6916 * between onResume() and onPause(). 6917 * <p>Note: If there are other tasks below this one that are also locked then calling this 6918 * method will immediately finish this task and resume the previous locked one, remaining in 6919 * lockTask mode. 6920 * 6921 * @see android.R.attr#lockTaskMode 6922 * @see ActivityManager#getLockTaskModeState() 6923 */ 6924 public void stopLockTask() { 6925 try { 6926 ActivityManagerNative.getDefault().stopLockTaskMode(); 6927 } catch (RemoteException e) { 6928 } 6929 } 6930 6931 /** 6932 * Shows the user the system defined message for telling the user how to exit 6933 * lock task mode. The task containing this activity must be in lock task mode at the time 6934 * of this call for the message to be displayed. 6935 */ 6936 public void showLockTaskEscapeMessage() { 6937 try { 6938 ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken); 6939 } catch (RemoteException e) { 6940 } 6941 } 6942 6943 /** 6944 * Check whether the caption on freeform windows is displayed directly on the content. 6945 * 6946 * @return True if caption is displayed on content, false if it pushes the content down. 6947 * 6948 * @see {@link #setOverlayWithDecorCaptionEnabled(boolean)} 6949 */ 6950 public boolean isOverlayWithDecorCaptionEnabled() { 6951 return mWindow.isOverlayWithDecorCaptionEnabled(); 6952 } 6953 6954 /** 6955 * Set whether the caption should displayed directly on the content rather than push it down. 6956 * 6957 * This affects only freeform windows since they display the caption and only the main 6958 * window of the activity. The caption is used to drag the window around and also shows 6959 * maximize and close action buttons. 6960 */ 6961 public void setOverlayWithDecorCaptionEnabled(boolean enabled) { 6962 mWindow.setOverlayWithDecorCaptionEnabled(enabled); 6963 } 6964 6965 /** 6966 * Interface for informing a translucent {@link Activity} once all visible activities below it 6967 * have completed drawing. This is necessary only after an {@link Activity} has been made 6968 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn 6969 * translucent again following a call to {@link 6970 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener, 6971 * ActivityOptions)} 6972 * 6973 * @hide 6974 */ 6975 @SystemApi 6976 public interface TranslucentConversionListener { 6977 /** 6978 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities 6979 * below the top one have been redrawn. Following this callback it is safe to make the top 6980 * Activity translucent because the underlying Activity has been drawn. 6981 * 6982 * @param drawComplete True if the background Activity has drawn itself. False if a timeout 6983 * occurred waiting for the Activity to complete drawing. 6984 * 6985 * @see Activity#convertFromTranslucent() 6986 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions) 6987 */ 6988 public void onTranslucentConversionComplete(boolean drawComplete); 6989 } 6990 6991 private void dispatchRequestPermissionsResult(int requestCode, Intent data) { 6992 mHasCurrentPermissionsRequest = false; 6993 // If the package installer crashed we may have not data - best effort. 6994 String[] permissions = (data != null) ? data.getStringArrayExtra( 6995 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0]; 6996 final int[] grantResults = (data != null) ? data.getIntArrayExtra( 6997 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0]; 6998 onRequestPermissionsResult(requestCode, permissions, grantResults); 6999 } 7000 7001 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data, 7002 Fragment fragment) { 7003 // If the package installer crashed we may have not data - best effort. 7004 String[] permissions = (data != null) ? data.getStringArrayExtra( 7005 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0]; 7006 final int[] grantResults = (data != null) ? data.getIntArrayExtra( 7007 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0]; 7008 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults); 7009 } 7010 7011 class HostCallbacks extends FragmentHostCallback<Activity> { 7012 public HostCallbacks() { 7013 super(Activity.this /*activity*/); 7014 } 7015 7016 @Override 7017 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { 7018 Activity.this.dump(prefix, fd, writer, args); 7019 } 7020 7021 @Override 7022 public boolean onShouldSaveFragmentState(Fragment fragment) { 7023 return !isFinishing(); 7024 } 7025 7026 @Override 7027 public LayoutInflater onGetLayoutInflater() { 7028 final LayoutInflater result = Activity.this.getLayoutInflater(); 7029 if (onUseFragmentManagerInflaterFactory()) { 7030 return result.cloneInContext(Activity.this); 7031 } 7032 return result; 7033 } 7034 7035 @Override 7036 public boolean onUseFragmentManagerInflaterFactory() { 7037 // Newer platform versions use the child fragment manager's LayoutInflaterFactory. 7038 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP; 7039 } 7040 7041 @Override 7042 public Activity onGetHost() { 7043 return Activity.this; 7044 } 7045 7046 @Override 7047 public void onInvalidateOptionsMenu() { 7048 Activity.this.invalidateOptionsMenu(); 7049 } 7050 7051 @Override 7052 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode, 7053 Bundle options) { 7054 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options); 7055 } 7056 7057 @Override 7058 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent, 7059 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, 7060 int extraFlags, Bundle options) throws IntentSender.SendIntentException { 7061 if (mParent == null) { 7062 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent, 7063 flagsMask, flagsValues, options); 7064 } else if (options != null) { 7065 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode, 7066 fillInIntent, flagsMask, flagsValues, extraFlags, options); 7067 } 7068 } 7069 7070 @Override 7071 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions, 7072 int requestCode) { 7073 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho; 7074 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions); 7075 startActivityForResult(who, intent, requestCode, null); 7076 } 7077 7078 @Override 7079 public boolean onHasWindowAnimations() { 7080 return getWindow() != null; 7081 } 7082 7083 @Override 7084 public int onGetWindowAnimations() { 7085 final Window w = getWindow(); 7086 return (w == null) ? 0 : w.getAttributes().windowAnimations; 7087 } 7088 7089 @Override 7090 public void onAttachFragment(Fragment fragment) { 7091 Activity.this.onAttachFragment(fragment); 7092 } 7093 7094 @Nullable 7095 @Override 7096 public View onFindViewById(int id) { 7097 return Activity.this.findViewById(id); 7098 } 7099 7100 @Override 7101 public boolean onHasView() { 7102 final Window w = getWindow(); 7103 return (w != null && w.peekDecorView() != null); 7104 } 7105 } 7106} 7107