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