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