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