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