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