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