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