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