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