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