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