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