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