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