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