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