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