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