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