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