2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import static java.lang.Character.MIN_VALUE;
21 import android.annotation.CallSuper;
22 import android.annotation.DrawableRes;
23 import android.annotation.IdRes;
24 import android.annotation.IntDef;
25 import android.annotation.LayoutRes;
26 import android.annotation.MainThread;
27 import android.annotation.NonNull;
28 import android.annotation.Nullable;
29 import android.annotation.RequiresPermission;
30 import android.annotation.StyleRes;
31 import android.annotation.SystemApi;
32 import android.app.VoiceInteractor.Request;
33 import android.app.admin.DevicePolicyManager;
34 import android.app.assist.AssistContent;
35 import android.content.ComponentCallbacks2;
36 import android.content.ComponentName;
37 import android.content.ContentResolver;
38 import android.content.Context;
39 import android.content.CursorLoader;
40 import android.content.IIntentSender;
41 import android.content.Intent;
42 import android.content.IntentSender;
43 import android.content.SharedPreferences;
44 import android.content.pm.ActivityInfo;
45 import android.content.pm.ApplicationInfo;
46 import android.content.pm.PackageManager;
47 import android.content.pm.PackageManager.NameNotFoundException;
48 import android.content.res.Configuration;
49 import android.content.res.Resources;
50 import android.content.res.TypedArray;
51 import android.database.Cursor;
52 import android.graphics.Bitmap;
53 import android.graphics.Canvas;
54 import android.graphics.Color;
55 import android.graphics.drawable.Drawable;
56 import android.hardware.input.InputManager;
57 import android.media.AudioManager;
58 import android.media.session.MediaController;
59 import android.net.Uri;
60 import android.os.BadParcelableException;
61 import android.os.Build;
62 import android.os.Bundle;
63 import android.os.Handler;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.Parcelable;
67 import android.os.PersistableBundle;
68 import android.os.RemoteException;
69 import android.os.StrictMode;
70 import android.os.SystemProperties;
71 import android.os.UserHandle;
72 import android.text.Selection;
73 import android.text.SpannableStringBuilder;
74 import android.text.TextUtils;
75 import android.text.method.TextKeyListener;
76 import android.transition.Scene;
77 import android.transition.TransitionManager;
78 import android.util.ArrayMap;
79 import android.util.AttributeSet;
80 import android.util.EventLog;
81 import android.util.Log;
82 import android.util.PrintWriterPrinter;
83 import android.util.Slog;
84 import android.util.SparseArray;
85 import android.util.SuperNotCalledException;
86 import android.view.ActionMode;
87 import android.view.ContextMenu;
88 import android.view.ContextMenu.ContextMenuInfo;
89 import android.view.ContextThemeWrapper;
90 import android.view.DragAndDropPermissions;
91 import android.view.DragEvent;
92 import android.view.InputDevice;
93 import android.view.KeyCharacterMap;
94 import android.view.KeyEvent;
95 import android.view.KeyboardShortcutGroup;
96 import android.view.KeyboardShortcutInfo;
97 import android.view.LayoutInflater;
98 import android.view.Menu;
99 import android.view.MenuInflater;
100 import android.view.MenuItem;
101 import android.view.MotionEvent;
102 import android.view.SearchEvent;
103 import android.view.View;
104 import android.view.View.OnCreateContextMenuListener;
105 import android.view.ViewGroup;
106 import android.view.ViewGroup.LayoutParams;
107 import android.view.ViewManager;
108 import android.view.ViewRootImpl;
109 import android.view.Window;
110 import android.view.Window.WindowControllerCallback;
111 import android.view.WindowManager;
112 import android.view.WindowManagerGlobal;
113 import android.view.accessibility.AccessibilityEvent;
114 import android.widget.AdapterView;
115 import android.widget.Toast;
116 import android.widget.Toolbar;
118 import com.android.internal.app.IVoiceInteractor;
119 import com.android.internal.app.ToolbarActionBar;
120 import com.android.internal.app.WindowDecorActionBar;
121 import com.android.internal.policy.PhoneWindow;
123 import java.io.FileDescriptor;
124 import java.io.PrintWriter;
125 import java.lang.annotation.Retention;
126 import java.lang.annotation.RetentionPolicy;
127 import java.util.ArrayList;
128 import java.util.HashMap;
129 import java.util.List;
132 * An activity is a single, focused thing that the user can do. Almost all
133 * activities interact with the user, so the Activity class takes care of
134 * creating a window for you in which you can place your UI with
135 * {@link #setContentView}. While activities are often presented to the user
136 * as full-screen windows, they can also be used in other ways: as floating
137 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
138 * or embedded inside of another activity (using {@link ActivityGroup}).
140 * There are two methods almost all subclasses of Activity will implement:
143 * <li> {@link #onCreate} is where you initialize your activity. Most
144 * importantly, here you will usually call {@link #setContentView(int)}
145 * with a layout resource defining your UI, and using {@link #findViewById}
146 * to retrieve the widgets in that UI that you need to interact with
149 * <li> {@link #onPause} is where you deal with the user leaving your
150 * activity. Most importantly, any changes made by the user should at this
151 * point be committed (usually to the
152 * {@link android.content.ContentProvider} holding the data).
155 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
156 * activity classes must have a corresponding
157 * {@link android.R.styleable#AndroidManifestActivity <activity>}
158 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
160 * <p>Topics covered here:
162 * <li><a href="#Fragments">Fragments</a>
163 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
164 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
165 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
166 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
167 * <li><a href="#Permissions">Permissions</a>
168 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
171 * <div class="special reference">
172 * <h3>Developer Guides</h3>
173 * <p>The Activity class is an important part of an application's overall lifecycle,
174 * and the way activities are launched and put together is a fundamental
175 * part of the platform's application model. For a detailed perspective on the structure of an
176 * Android application and how activities behave, please read the
177 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
178 * <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
179 * developer guides.</p>
181 * <p>You can also find a detailed discussion about how to create activities in the
182 * <a href="{@docRoot}guide/components/activities.html">Activities</a>
183 * developer guide.</p>
186 * <a name="Fragments"></a>
189 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
190 * implementations can make use of the {@link Fragment} class to better
191 * modularize their code, build more sophisticated user interfaces for larger
192 * screens, and help scale their application between small and large screens.
194 * <a name="ActivityLifecycle"></a>
195 * <h3>Activity Lifecycle</h3>
197 * <p>Activities in the system are managed as an <em>activity stack</em>.
198 * When a new activity is started, it is placed on the top of the stack
199 * and becomes the running activity -- the previous activity always remains
200 * below it in the stack, and will not come to the foreground again until
201 * the new activity exits.</p>
203 * <p>An activity has essentially four states:</p>
205 * <li> If an activity is in the foreground of the screen (at the top of
207 * it is <em>active</em> or <em>running</em>. </li>
208 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
209 * or transparent activity has focus on top of your activity), it
210 * is <em>paused</em>. A paused activity is completely alive (it
211 * maintains all state and member information and remains attached to
212 * the window manager), but can be killed by the system in extreme
213 * low memory situations.
214 * <li>If an activity is completely obscured by another activity,
215 * it is <em>stopped</em>. It still retains all state and member information,
216 * however, it is no longer visible to the user so its window is hidden
217 * and it will often be killed by the system when memory is needed
219 * <li>If an activity is paused or stopped, the system can drop the activity
220 * from memory by either asking it to finish, or simply killing its
221 * process. When it is displayed again to the user, it must be
222 * completely restarted and restored to its previous state.</li>
225 * <p>The following diagram shows the important state paths of an Activity.
226 * The square rectangles represent callback methods you can implement to
227 * perform operations when the Activity moves between states. The colored
228 * ovals are major states the Activity can be in.</p>
230 * <p><img src="../../../images/activity_lifecycle.png"
231 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
233 * <p>There are three key loops you may be interested in monitoring within your
237 * <li>The <b>entire lifetime</b> of an activity happens between the first call
238 * to {@link android.app.Activity#onCreate} through to a single final call
239 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
240 * of "global" state in onCreate(), and release all remaining resources in
241 * onDestroy(). For example, if it has a thread running in the background
242 * to download data from the network, it may create that thread in onCreate()
243 * and then stop the thread in onDestroy().
245 * <li>The <b>visible lifetime</b> of an activity happens between a call to
246 * {@link android.app.Activity#onStart} until a corresponding call to
247 * {@link android.app.Activity#onStop}. During this time the user can see the
248 * activity on-screen, though it may not be in the foreground and interacting
249 * with the user. Between these two methods you can maintain resources that
250 * are needed to show the activity to the user. For example, you can register
251 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
252 * that impact your UI, and unregister it in onStop() when the user no
253 * longer sees what you are displaying. The onStart() and onStop() methods
254 * can be called multiple times, as the activity becomes visible and hidden
257 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
258 * {@link android.app.Activity#onResume} until a corresponding call to
259 * {@link android.app.Activity#onPause}. During this time the activity is
260 * in front of all other activities and interacting with the user. An activity
261 * can frequently go between the resumed and paused states -- for example when
262 * the device goes to sleep, when an activity result is delivered, when a new
263 * intent is delivered -- so the code in these methods should be fairly
267 * <p>The entire lifecycle of an activity is defined by the following
268 * Activity methods. All of these are hooks that you can override
269 * to do appropriate work when the activity changes state. All
270 * activities will implement {@link android.app.Activity#onCreate}
271 * to do their initial setup; many will also implement
272 * {@link android.app.Activity#onPause} to commit changes to data and
273 * otherwise prepare to stop interacting with the user. You should always
274 * call up to your superclass when implementing these methods.</p>
277 * <pre class="prettyprint">
278 * public class Activity extends ApplicationContext {
279 * protected void onCreate(Bundle savedInstanceState);
281 * protected void onStart();
283 * protected void onRestart();
285 * protected void onResume();
287 * protected void onPause();
289 * protected void onStop();
291 * protected void onDestroy();
295 * <p>In general the movement through an activity's lifecycle looks like
298 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
299 * <colgroup align="left" span="3" />
300 * <colgroup align="left" />
301 * <colgroup align="center" />
302 * <colgroup align="center" />
305 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
309 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</td>
310 * <td>Called when the activity is first created.
311 * This is where you should do all of your normal static set up:
312 * create views, bind data to lists, etc. This method also
313 * provides you with a Bundle containing the activity's previously
314 * frozen state, if there was one.
315 * <p>Always followed by <code>onStart()</code>.</td>
316 * <td align="center">No</td>
317 * <td align="center"><code>onStart()</code></td>
320 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
321 * <td colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</td>
322 * <td>Called after your activity has been stopped, prior to it being
324 * <p>Always followed by <code>onStart()</code></td>
325 * <td align="center">No</td>
326 * <td align="center"><code>onStart()</code></td>
329 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</td>
330 * <td>Called when the activity is becoming visible to the user.
331 * <p>Followed by <code>onResume()</code> if the activity comes
332 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
333 * <td align="center">No</td>
334 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
337 * <tr><td rowspan="2" style="border-left: none;"> </td>
338 * <td align="left" border="0">{@link android.app.Activity#onResume onResume()}</td>
339 * <td>Called when the activity will start
340 * interacting with the user. At this point your activity is at
341 * the top of the activity stack, with user input going to it.
342 * <p>Always followed by <code>onPause()</code>.</td>
343 * <td align="center">No</td>
344 * <td align="center"><code>onPause()</code></td>
347 * <tr><td align="left" border="0">{@link android.app.Activity#onPause onPause()}</td>
348 * <td>Called when the system is about to start resuming a previous
349 * activity. This is typically used to commit unsaved changes to
350 * persistent data, stop animations and other things that may be consuming
351 * CPU, etc. Implementations of this method must be very quick because
352 * the next activity will not be resumed until this method returns.
353 * <p>Followed by either <code>onResume()</code> if the activity
354 * returns back to the front, or <code>onStop()</code> if it becomes
355 * invisible to the user.</td>
356 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
357 * <td align="center"><code>onResume()</code> or<br>
358 * <code>onStop()</code></td>
361 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</td>
362 * <td>Called when the activity is no longer visible to the user, because
363 * another activity has been resumed and is covering this one. This
364 * may happen either because a new activity is being started, an existing
365 * one is being brought in front of this one, or this one is being
367 * <p>Followed by either <code>onRestart()</code> if
368 * this activity is coming back to interact with the user, or
369 * <code>onDestroy()</code> if this activity is going away.</td>
370 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
371 * <td align="center"><code>onRestart()</code> or<br>
372 * <code>onDestroy()</code></td>
375 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</td>
376 * <td>The final call you receive before your
377 * activity is destroyed. This can happen either because the
378 * activity is finishing (someone called {@link Activity#finish} on
379 * it, or because the system is temporarily destroying this
380 * instance of the activity to save space. You can distinguish
381 * between these two scenarios with the {@link
382 * Activity#isFinishing} method.</td>
383 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
384 * <td align="center"><em>nothing</em></td>
389 * <p>Note the "Killable" column in the above table -- for those methods that
390 * are marked as being killable, after that method returns the process hosting the
391 * activity may be killed by the system <em>at any time</em> without another line
392 * of its code being executed. Because of this, you should use the
393 * {@link #onPause} method to write any persistent data (such as user edits)
394 * to storage. In addition, the method
395 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
396 * in such a background state, allowing you to save away any dynamic instance
397 * state in your activity into the given Bundle, to be later received in
398 * {@link #onCreate} if the activity needs to be re-created.
399 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
400 * section for more information on how the lifecycle of a process is tied
401 * to the activities it is hosting. Note that it is important to save
402 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
403 * because the latter is not part of the lifecycle callbacks, so will not
404 * be called in every situation as described in its documentation.</p>
406 * <p class="note">Be aware that these semantics will change slightly between
407 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
408 * vs. those targeting prior platforms. Starting with Honeycomb, an application
409 * is not in the killable state until its {@link #onStop} has returned. This
410 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
411 * safely called after {@link #onPause()} and allows and application to safely
412 * wait until {@link #onStop()} to save persistent state.</p>
414 * <p>For those methods that are not marked as being killable, the activity's
415 * process will not be killed by the system starting from the time the method
416 * is called and continuing after it returns. Thus an activity is in the killable
417 * state, for example, between after <code>onPause()</code> to the start of
418 * <code>onResume()</code>.</p>
420 * <a name="ConfigurationChanges"></a>
421 * <h3>Configuration Changes</h3>
423 * <p>If the configuration of the device (as defined by the
424 * {@link Configuration Resources.Configuration} class) changes,
425 * then anything displaying a user interface will need to update to match that
426 * configuration. Because Activity is the primary mechanism for interacting
427 * with the user, it includes special support for handling configuration
430 * <p>Unless you specify otherwise, a configuration change (such as a change
431 * in screen orientation, language, input devices, etc) will cause your
432 * current activity to be <em>destroyed</em>, going through the normal activity
433 * lifecycle process of {@link #onPause},
434 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
435 * had been in the foreground or visible to the user, once {@link #onDestroy} is
436 * called in that instance then a new instance of the activity will be
437 * created, with whatever savedInstanceState the previous instance had generated
438 * from {@link #onSaveInstanceState}.</p>
440 * <p>This is done because any application resource,
441 * including layout files, can change based on any configuration value. Thus
442 * the only safe way to handle a configuration change is to re-retrieve all
443 * resources, including layouts, drawables, and strings. Because activities
444 * must already know how to save their state and re-create themselves from
445 * that state, this is a convenient way to have an activity restart itself
446 * with a new configuration.</p>
448 * <p>In some special cases, you may want to bypass restarting of your
449 * activity based on one or more types of configuration changes. This is
450 * done with the {@link android.R.attr#configChanges android:configChanges}
451 * attribute in its manifest. For any types of configuration changes you say
452 * that you handle there, you will receive a call to your current activity's
453 * {@link #onConfigurationChanged} method instead of being restarted. If
454 * a configuration change involves any that you do not handle, however, the
455 * activity will still be restarted and {@link #onConfigurationChanged}
456 * will not be called.</p>
458 * <a name="StartingActivities"></a>
459 * <h3>Starting Activities and Getting Results</h3>
461 * <p>The {@link android.app.Activity#startActivity}
462 * method is used to start a
463 * new activity, which will be placed at the top of the activity stack. It
464 * takes a single argument, an {@link android.content.Intent Intent},
465 * which describes the activity
466 * to be executed.</p>
468 * <p>Sometimes you want to get a result back from an activity when it
469 * ends. For example, you may start an activity that lets the user pick
470 * a person in a list of contacts; when it ends, it returns the person
471 * that was selected. To do this, you call the
472 * {@link android.app.Activity#startActivityForResult(Intent, int)}
473 * version with a second integer parameter identifying the call. The result
474 * will come back through your {@link android.app.Activity#onActivityResult}
477 * <p>When an activity exits, it can call
478 * {@link android.app.Activity#setResult(int)}
479 * to return data back to its parent. It must always supply a result code,
480 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
481 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
482 * return back an Intent containing any additional data it wants. All of this
483 * information appears back on the
484 * parent's <code>Activity.onActivityResult()</code>, along with the integer
485 * identifier it originally supplied.</p>
487 * <p>If a child activity fails for any reason (such as crashing), the parent
488 * activity will receive a result with the code RESULT_CANCELED.</p>
490 * <pre class="prettyprint">
491 * public class MyActivity extends Activity {
494 * static final int PICK_CONTACT_REQUEST = 0;
496 * public boolean onKeyDown(int keyCode, KeyEvent event) {
497 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
498 * // When the user center presses, let them pick a contact.
499 * startActivityForResult(
500 * new Intent(Intent.ACTION_PICK,
501 * new Uri("content://contacts")),
502 * PICK_CONTACT_REQUEST);
508 * protected void onActivityResult(int requestCode, int resultCode,
510 * if (requestCode == PICK_CONTACT_REQUEST) {
511 * if (resultCode == RESULT_OK) {
512 * // A contact was picked. Here we will just display it
514 * startActivity(new Intent(Intent.ACTION_VIEW, data));
521 * <a name="SavingPersistentState"></a>
522 * <h3>Saving Persistent State</h3>
524 * <p>There are generally two kinds of persistent state than an activity
525 * will deal with: shared document-like data (typically stored in a SQLite
526 * database using a {@linkplain android.content.ContentProvider content provider})
527 * and internal state such as user preferences.</p>
529 * <p>For content provider data, we suggest that activities use a
530 * "edit in place" user model. That is, any edits a user makes are effectively
531 * made immediately without requiring an additional confirmation step.
532 * Supporting this model is generally a simple matter of following two rules:</p>
535 * <li> <p>When creating a new document, the backing database entry or file for
536 * it is created immediately. For example, if the user chooses to write
537 * a new e-mail, a new entry for that e-mail is created as soon as they
538 * start entering data, so that if they go to any other activity after
539 * that point this e-mail will now appear in the list of drafts.</p>
540 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
541 * commit to the backing content provider or file any changes the user
542 * has made. This ensures that those changes will be seen by any other
543 * activity that is about to run. You will probably want to commit
544 * your data even more aggressively at key times during your
545 * activity's lifecycle: for example before starting a new
546 * activity, before finishing your own activity, when the user
547 * switches between input fields, etc.</p>
550 * <p>This model is designed to prevent data loss when a user is navigating
551 * between activities, and allows the system to safely kill an activity (because
552 * system resources are needed somewhere else) at any time after it has been
553 * paused. Note this implies
554 * that the user pressing BACK from your activity does <em>not</em>
555 * mean "cancel" -- it means to leave the activity with its current contents
556 * saved away. Canceling edits in an activity must be provided through
557 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
559 * <p>See the {@linkplain android.content.ContentProvider content package} for
560 * more information about content providers. These are a key aspect of how
561 * different activities invoke and propagate data between themselves.</p>
563 * <p>The Activity class also provides an API for managing internal persistent state
564 * associated with an activity. This can be used, for example, to remember
565 * the user's preferred initial display in a calendar (day view or week view)
566 * or the user's default home page in a web browser.</p>
568 * <p>Activity persistent state is managed
569 * with the method {@link #getPreferences},
570 * allowing you to retrieve and
571 * modify a set of name/value pairs associated with the activity. To use
572 * preferences that are shared across multiple application components
573 * (activities, receivers, services, providers), you can use the underlying
574 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
575 * to retrieve a preferences
576 * object stored under a specific name.
577 * (Note that it is not possible to share settings data across application
578 * packages -- for that you will need a content provider.)</p>
580 * <p>Here is an excerpt from a calendar activity that stores the user's
581 * preferred view mode in its persistent settings:</p>
583 * <pre class="prettyprint">
584 * public class CalendarActivity extends Activity {
587 * static final int DAY_VIEW_MODE = 0;
588 * static final int WEEK_VIEW_MODE = 1;
590 * private SharedPreferences mPrefs;
591 * private int mCurViewMode;
593 * protected void onCreate(Bundle savedInstanceState) {
594 * super.onCreate(savedInstanceState);
596 * SharedPreferences mPrefs = getSharedPreferences();
597 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
600 * protected void onPause() {
603 * SharedPreferences.Editor ed = mPrefs.edit();
604 * ed.putInt("view_mode", mCurViewMode);
610 * <a name="Permissions"></a>
611 * <h3>Permissions</h3>
613 * <p>The ability to start a particular Activity can be enforced when it is
615 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
616 * tag. By doing so, other applications will need to declare a corresponding
617 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
618 * element in their own manifest to be able to start that activity.
620 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
621 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
622 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
623 * Activity access to the specific URIs in the Intent. Access will remain
624 * until the Activity has finished (it will remain across the hosting
625 * process being killed and other temporary destruction). As of
626 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
627 * was already created and a new Intent is being delivered to
628 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
629 * to the existing ones it holds.
631 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
632 * document for more information on permissions and security in general.
634 * <a name="ProcessLifecycle"></a>
635 * <h3>Process Lifecycle</h3>
637 * <p>The Android system attempts to keep application process around for as
638 * long as possible, but eventually will need to remove old processes when
639 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
640 * Lifecycle</a>, the decision about which process to remove is intimately
641 * tied to the state of the user's interaction with it. In general, there
642 * are four states a process can be in based on the activities running in it,
643 * listed here in order of importance. The system will kill less important
644 * processes (the last ones) before it resorts to killing more important
645 * processes (the first ones).
648 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
649 * that the user is currently interacting with) is considered the most important.
650 * Its process will only be killed as a last resort, if it uses more memory
651 * than is available on the device. Generally at this point the device has
652 * reached a memory paging state, so this is required in order to keep the user
653 * interface responsive.
654 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
655 * but not in the foreground, such as one sitting behind a foreground dialog)
656 * is considered extremely important and will not be killed unless that is
657 * required to keep the foreground activity running.
658 * <li> <p>A <b>background activity</b> (an activity that is not visible to
659 * the user and has been paused) is no longer critical, so the system may
660 * safely kill its process to reclaim memory for other foreground or
661 * visible processes. If its process needs to be killed, when the user navigates
662 * back to the activity (making it visible on the screen again), its
663 * {@link #onCreate} method will be called with the savedInstanceState it had previously
664 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
665 * state as the user last left it.
666 * <li> <p>An <b>empty process</b> is one hosting no activities or other
667 * application components (such as {@link Service} or
668 * {@link android.content.BroadcastReceiver} classes). These are killed very
669 * quickly by the system as memory becomes low. For this reason, any
670 * background operation you do outside of an activity must be executed in the
671 * context of an activity BroadcastReceiver or Service to ensure that the system
672 * knows it needs to keep your process around.
675 * <p>Sometimes an Activity may need to do a long-running operation that exists
676 * independently of the activity lifecycle itself. An example may be a camera
677 * application that allows you to upload a picture to a web site. The upload
678 * may take a long time, and the application should allow the user to leave
679 * the application while it is executing. To accomplish this, your Activity
680 * should start a {@link Service} in which the upload takes place. This allows
681 * the system to properly prioritize your process (considering it to be more
682 * important than other non-visible applications) for the duration of the
683 * upload, independent of whether the original activity is paused, stopped,
686 public class Activity extends ContextThemeWrapper
687 implements LayoutInflater.Factory2,
688 Window.Callback, KeyEvent.Callback,
689 OnCreateContextMenuListener, ComponentCallbacks2,
690 Window.OnWindowDismissedCallback, WindowControllerCallback {
691 private static final String TAG = "Activity";
692 private static final boolean DEBUG_LIFECYCLE = false;
694 /** Standard activity result: operation canceled. */
695 public static final int RESULT_CANCELED = 0;
696 /** Standard activity result: operation succeeded. */
697 public static final int RESULT_OK = -1;
698 /** Start of user-defined activity results. */
699 public static final int RESULT_FIRST_USER = 1;
701 /** @hide Task isn't finished when activity is finished */
702 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0;
704 * @hide Task is finished if the finishing activity is the root of the task. To preserve the
705 * past behavior the task is also removed from recents.
707 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1;
709 * @hide Task is finished along with the finishing activity, but it is not removed from
712 public static final int FINISH_TASK_WITH_ACTIVITY = 2;
714 static final String FRAGMENTS_TAG = "android:fragments";
716 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
717 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
718 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
719 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
720 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
721 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
722 "android:hasCurrentPermissionsRequest";
724 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
726 private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
727 private static final String KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME =
728 "com.android.systemui.statusbar.KeyboardShortcutsReceiver";
730 private static class ManagedDialog {
734 private SparseArray<ManagedDialog> mManagedDialogs;
736 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
737 private Instrumentation mInstrumentation;
738 private IBinder mToken;
740 /*package*/ String mEmbeddedID;
741 private Application mApplication;
742 /*package*/ Intent mIntent;
743 /*package*/ String mReferrer;
744 private ComponentName mComponent;
745 /*package*/ ActivityInfo mActivityInfo;
746 /*package*/ ActivityThread mMainThread;
749 /*package*/ boolean mResumed;
750 /*package*/ boolean mStopped;
752 boolean mStartedActivity;
753 private boolean mDestroyed;
754 private boolean mDoReportFullyDrawn = true;
755 /** true if the activity is going through a transient pause */
756 /*package*/ boolean mTemporaryPause = false;
757 /** true if the activity is being destroyed in order to recreate it with a new configuration */
758 /*package*/ boolean mChangingConfigurations = false;
759 /*package*/ int mConfigChangeFlags;
760 /*package*/ Configuration mCurrentConfig;
761 private SearchManager mSearchManager;
762 private MenuInflater mMenuInflater;
764 static final class NonConfigurationInstances {
766 HashMap<String, Object> children;
767 FragmentManagerNonConfig fragments;
768 ArrayMap<String, LoaderManager> loaders;
769 VoiceInteractor voiceInteractor;
771 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
773 private Window mWindow;
775 private WindowManager mWindowManager;
776 /*package*/ View mDecor = null;
777 /*package*/ boolean mWindowAdded = false;
778 /*package*/ boolean mVisibleFromServer = false;
779 /*package*/ boolean mVisibleFromClient = true;
780 /*package*/ ActionBar mActionBar = null;
781 private boolean mEnableDefaultActionBarUp;
783 private VoiceInteractor mVoiceInteractor;
785 private CharSequence mTitle;
786 private int mTitleColor = 0;
788 // we must have a handler before the FragmentController is constructed
789 final Handler mHandler = new Handler();
790 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
792 // Most recent call to requestVisibleBehind().
793 boolean mVisibleBehind;
795 private static final class ManagedCursor {
796 ManagedCursor(Cursor cursor) {
802 private final Cursor mCursor;
803 private boolean mReleased;
804 private boolean mUpdated;
806 private final ArrayList<ManagedCursor> mManagedCursors =
807 new ArrayList<ManagedCursor>();
809 // protected by synchronized (this)
810 int mResultCode = RESULT_CANCELED;
811 Intent mResultData = null;
813 private TranslucentConversionListener mTranslucentCallback;
814 private boolean mChangeCanvasToTranslucent;
816 private SearchEvent mSearchEvent;
818 private boolean mTitleReady = false;
819 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
821 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
822 private SpannableStringBuilder mDefaultKeySsb = null;
824 private ActivityManager.TaskDescription mTaskDescription =
825 new ActivityManager.TaskDescription();
827 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
829 @SuppressWarnings("unused")
830 private final Object mInstanceTracker = StrictMode.trackActivity(this);
832 private Thread mUiThread;
834 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
835 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
836 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
838 private boolean mHasCurrentPermissionsRequest;
839 private boolean mEatKeyUpEvent;
841 private static native String getDlWarning();
843 /** Return the intent that started this activity. */
844 public Intent getIntent() {
849 * Change the intent returned by {@link #getIntent}. This holds a
850 * reference to the given intent; it does not copy it. Often used in
851 * conjunction with {@link #onNewIntent}.
853 * @param newIntent The new Intent object to return from getIntent
858 public void setIntent(Intent newIntent) {
862 /** Return the application that owns this activity. */
863 public final Application getApplication() {
867 /** Is this activity embedded inside of another activity? */
868 public final boolean isChild() {
869 return mParent != null;
872 /** Return the parent activity if this view is an embedded child. */
873 public final Activity getParent() {
877 /** Retrieve the window manager for showing custom windows. */
878 public WindowManager getWindowManager() {
879 return mWindowManager;
883 * Retrieve the current {@link android.view.Window} for the activity.
884 * This can be used to directly access parts of the Window API that
885 * are not available through Activity/Screen.
887 * @return Window The current window, or null if the activity is not
890 public Window getWindow() {
895 * Return the LoaderManager for this activity, creating it if needed.
897 public LoaderManager getLoaderManager() {
898 return mFragments.getLoaderManager();
902 * Calls {@link android.view.Window#getCurrentFocus} on the
903 * Window of this Activity to return the currently focused view.
905 * @return View The current View with focus or null.
908 * @see android.view.Window#getCurrentFocus
911 public View getCurrentFocus() {
912 return mWindow != null ? mWindow.getCurrentFocus() : null;
916 * Called when the activity is starting. This is where most initialization
917 * should go: calling {@link #setContentView(int)} to inflate the
918 * activity's UI, using {@link #findViewById} to programmatically interact
919 * with widgets in the UI, calling
920 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
921 * cursors for data being displayed, etc.
923 * <p>You can call {@link #finish} from within this function, in
924 * which case onDestroy() will be immediately called without any of the rest
925 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
926 * {@link #onPause}, etc) executing.
928 * <p><em>Derived classes must call through to the super class's
929 * implementation of this method. If they do not, an exception will be
932 * @param savedInstanceState If the activity is being re-initialized after
933 * previously being shut down then this Bundle contains the data it most
934 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
937 * @see #onSaveInstanceState
938 * @see #onRestoreInstanceState
943 protected void onCreate(@Nullable Bundle savedInstanceState) {
944 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
945 if (mLastNonConfigurationInstances != null) {
946 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
948 if (mActivityInfo.parentActivityName != null) {
949 if (mActionBar == null) {
950 mEnableDefaultActionBarUp = true;
952 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
955 if (savedInstanceState != null) {
956 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
957 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
958 ? mLastNonConfigurationInstances.fragments : null);
960 mFragments.dispatchCreate();
961 getApplication().dispatchActivityCreated(this, savedInstanceState);
962 if (mVoiceInteractor != null) {
963 mVoiceInteractor.attachActivity(this);
969 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
970 * the attribute {@link android.R.attr#persistableMode} set to
971 * <code>persistAcrossReboots</code>.
973 * @param savedInstanceState if the activity is being re-initialized after
974 * previously being shut down then this Bundle contains the data it most
975 * recently supplied in {@link #onSaveInstanceState}.
976 * <b><i>Note: Otherwise it is null.</i></b>
977 * @param persistentState if the activity is being re-initialized after
978 * previously being shut down or powered off then this Bundle contains the data it most
979 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
980 * <b><i>Note: Otherwise it is null.</i></b>
982 * @see #onCreate(android.os.Bundle)
984 * @see #onSaveInstanceState
985 * @see #onRestoreInstanceState
988 public void onCreate(@Nullable Bundle savedInstanceState,
989 @Nullable PersistableBundle persistentState) {
990 onCreate(savedInstanceState);
994 * The hook for {@link ActivityThread} to restore the state of this activity.
996 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
997 * {@link #restoreManagedDialogs(android.os.Bundle)}.
999 * @param savedInstanceState contains the saved state
1001 final void performRestoreInstanceState(Bundle savedInstanceState) {
1002 onRestoreInstanceState(savedInstanceState);
1003 restoreManagedDialogs(savedInstanceState);
1007 * The hook for {@link ActivityThread} to restore the state of this activity.
1009 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1010 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1012 * @param savedInstanceState contains the saved state
1013 * @param persistentState contains the persistable saved state
1015 final void performRestoreInstanceState(Bundle savedInstanceState,
1016 PersistableBundle persistentState) {
1017 onRestoreInstanceState(savedInstanceState, persistentState);
1018 if (savedInstanceState != null) {
1019 restoreManagedDialogs(savedInstanceState);
1024 * This method is called after {@link #onStart} when the activity is
1025 * being re-initialized from a previously saved state, given here in
1026 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
1027 * to restore their state, but it is sometimes convenient to do it here
1028 * after all of the initialization has been done or to allow subclasses to
1029 * decide whether to use your default implementation. The default
1030 * implementation of this method performs a restore of any view state that
1031 * had previously been frozen by {@link #onSaveInstanceState}.
1033 * <p>This method is called between {@link #onStart} and
1034 * {@link #onPostCreate}.
1036 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1039 * @see #onPostCreate
1041 * @see #onSaveInstanceState
1043 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1044 if (mWindow != null) {
1045 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1046 if (windowState != null) {
1047 mWindow.restoreHierarchyState(windowState);
1053 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1054 * created with the attribute {@link android.R.attr#persistableMode} set to
1055 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1056 * came from the restored PersistableBundle first
1057 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1059 * <p>This method is called between {@link #onStart} and
1060 * {@link #onPostCreate}.
1062 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1064 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1065 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1067 * @see #onRestoreInstanceState(Bundle)
1069 * @see #onPostCreate
1071 * @see #onSaveInstanceState
1073 public void onRestoreInstanceState(Bundle savedInstanceState,
1074 PersistableBundle persistentState) {
1075 if (savedInstanceState != null) {
1076 onRestoreInstanceState(savedInstanceState);
1081 * Restore the state of any saved managed dialogs.
1083 * @param savedInstanceState The bundle to restore from.
1085 private void restoreManagedDialogs(Bundle savedInstanceState) {
1086 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1091 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1092 final int numDialogs = ids.length;
1093 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1094 for (int i = 0; i < numDialogs; i++) {
1095 final Integer dialogId = ids[i];
1096 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1097 if (dialogState != null) {
1098 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1099 // so tell createDialog() not to do it, otherwise we get an exception
1100 final ManagedDialog md = new ManagedDialog();
1101 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1102 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1103 if (md.mDialog != null) {
1104 mManagedDialogs.put(dialogId, md);
1105 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1106 md.mDialog.onRestoreInstanceState(dialogState);
1112 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1113 final Dialog dialog = onCreateDialog(dialogId, args);
1114 if (dialog == null) {
1117 dialog.dispatchOnCreate(state);
1121 private static String savedDialogKeyFor(int key) {
1122 return SAVED_DIALOG_KEY_PREFIX + key;
1125 private static String savedDialogArgsKeyFor(int key) {
1126 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1130 * Called when activity start-up is complete (after {@link #onStart}
1131 * and {@link #onRestoreInstanceState} have been called). Applications will
1132 * generally not implement this method; it is intended for system
1133 * classes to do final initialization after application code has run.
1135 * <p><em>Derived classes must call through to the super class's
1136 * implementation of this method. If they do not, an exception will be
1139 * @param savedInstanceState If the activity is being re-initialized after
1140 * previously being shut down then this Bundle contains the data it most
1141 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1145 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1148 onTitleChanged(getTitle(), getTitleColor());
1155 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1156 * created with the attribute {@link android.R.attr#persistableMode} set to
1157 * <code>persistAcrossReboots</code>.
1159 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1160 * @param persistentState The data caming from the PersistableBundle first
1161 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1165 public void onPostCreate(@Nullable Bundle savedInstanceState,
1166 @Nullable PersistableBundle persistentState) {
1167 onPostCreate(savedInstanceState);
1171 * Called after {@link #onCreate} — or after {@link #onRestart} when
1172 * the activity had been stopped, but is now again being displayed to the
1173 * user. It will be followed by {@link #onResume}.
1175 * <p><em>Derived classes must call through to the super class's
1176 * implementation of this method. If they do not, an exception will be
1184 protected void onStart() {
1185 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1188 mFragments.doLoaderStart();
1190 getApplication().dispatchActivityStarted(this);
1194 * Called after {@link #onStop} when the current activity is being
1195 * re-displayed to the user (the user has navigated back to it). It will
1196 * be followed by {@link #onStart} and then {@link #onResume}.
1198 * <p>For activities that are using raw {@link Cursor} objects (instead of
1199 * creating them through
1200 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1201 * this is usually the place
1202 * where the cursor should be requeried (because you had deactivated it in
1205 * <p><em>Derived classes must call through to the super class's
1206 * implementation of this method. If they do not, an exception will be
1214 protected void onRestart() {
1219 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1220 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1221 * to give the activity a hint that its state is no longer saved -- it will generally
1222 * be called after {@link #onSaveInstanceState} and prior to the activity being
1223 * resumed/started again.
1225 public void onStateNotSaved() {
1229 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1230 * {@link #onPause}, for your activity to start interacting with the user.
1231 * This is a good place to begin animations, open exclusive-access devices
1232 * (such as the camera), etc.
1234 * <p>Keep in mind that onResume is not the best indicator that your activity
1235 * is visible to the user; a system window such as the keyguard may be in
1236 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1237 * activity is visible to the user (for example, to resume a game).
1239 * <p><em>Derived classes must call through to the super class's
1240 * implementation of this method. If they do not, an exception will be
1243 * @see #onRestoreInstanceState
1245 * @see #onPostResume
1249 protected void onResume() {
1250 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1251 getApplication().dispatchActivityResumed(this);
1252 mActivityTransitionState.onResume(this, isTopOfTask());
1257 * Called when activity resume is complete (after {@link #onResume} has
1258 * been called). Applications will generally not implement this method;
1259 * it is intended for system classes to do final setup after application
1260 * resume code has run.
1262 * <p><em>Derived classes must call through to the super class's
1263 * implementation of this method. If they do not, an exception will be
1269 protected void onPostResume() {
1270 final Window win = getWindow();
1271 if (win != null) win.makeActive();
1272 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1276 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
1277 if (mVoiceInteractor != null) {
1278 for (Request activeRequest: mVoiceInteractor.getActiveRequests()) {
1279 activeRequest.cancel();
1280 activeRequest.clear();
1283 if (voiceInteractor == null) {
1284 mVoiceInteractor = null;
1286 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
1292 * Check whether this activity is running as part of a voice interaction with the user.
1293 * If true, it should perform its interaction with the user through the
1294 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1296 public boolean isVoiceInteraction() {
1297 return mVoiceInteractor != null;
1301 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1302 * of a voice interaction. That is, returns true if this activity was directly
1303 * started by the voice interaction service as the initiation of a voice interaction.
1304 * Otherwise, for example if it was started by another activity while under voice
1305 * interaction, returns false.
1307 public boolean isVoiceInteractionRoot() {
1309 return mVoiceInteractor != null
1310 && ActivityManagerNative.getDefault().isRootVoiceInteraction(mToken);
1311 } catch (RemoteException e) {
1317 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1318 * interact with this activity.
1320 public VoiceInteractor getVoiceInteractor() {
1321 return mVoiceInteractor;
1325 * Queries whether the currently enabled voice interaction service supports returning
1326 * a voice interactor for use by the activity. This is valid only for the duration of the
1329 * @return whether the current voice interaction service supports local voice interaction
1331 public boolean isLocalVoiceInteractionSupported() {
1333 return ActivityManagerNative.getDefault().supportsLocalVoiceInteraction();
1334 } catch (RemoteException re) {
1340 * Starts a local voice interaction session. When ready,
1341 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
1342 * to the registered voice interaction service.
1343 * @param privateOptions a Bundle of private arguments to the current voice interaction service
1345 public void startLocalVoiceInteraction(Bundle privateOptions) {
1347 ActivityManagerNative.getDefault().startLocalVoiceInteraction(mToken, privateOptions);
1348 } catch (RemoteException re) {
1353 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
1354 * voice interaction session being started. You can now retrieve a voice interactor using
1355 * {@link #getVoiceInteractor()}.
1357 public void onLocalVoiceInteractionStarted() {
1361 * Callback to indicate that the local voice interaction has stopped either
1362 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
1363 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
1364 * is no longer valid after this.
1366 public void onLocalVoiceInteractionStopped() {
1370 * Request to terminate the current voice interaction that was previously started
1371 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
1372 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
1374 public void stopLocalVoiceInteraction() {
1376 ActivityManagerNative.getDefault().stopLocalVoiceInteraction(mToken);
1377 } catch (RemoteException re) {
1382 * This is called for activities that set launchMode to "singleTop" in
1383 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1384 * flag when calling {@link #startActivity}. In either case, when the
1385 * activity is re-launched while at the top of the activity stack instead
1386 * of a new instance of the activity being started, onNewIntent() will be
1387 * called on the existing instance with the Intent that was used to
1390 * <p>An activity will always be paused before receiving a new intent, so
1391 * you can count on {@link #onResume} being called after this method.
1393 * <p>Note that {@link #getIntent} still returns the original Intent. You
1394 * can use {@link #setIntent} to update it to this new Intent.
1396 * @param intent The new intent that was started for the activity.
1402 protected void onNewIntent(Intent intent) {
1406 * The hook for {@link ActivityThread} to save the state of this activity.
1408 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1409 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1411 * @param outState The bundle to save the state to.
1413 final void performSaveInstanceState(Bundle outState) {
1414 onSaveInstanceState(outState);
1415 saveManagedDialogs(outState);
1416 mActivityTransitionState.saveState(outState);
1417 storeHasCurrentPermissionRequest(outState);
1418 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1422 * The hook for {@link ActivityThread} to save the state of this activity.
1424 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1425 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1427 * @param outState The bundle to save the state to.
1428 * @param outPersistentState The bundle to save persistent state to.
1430 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1431 onSaveInstanceState(outState, outPersistentState);
1432 saveManagedDialogs(outState);
1433 storeHasCurrentPermissionRequest(outState);
1434 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1435 ", " + outPersistentState);
1439 * Called to retrieve per-instance state from an activity before being killed
1440 * so that the state can be restored in {@link #onCreate} or
1441 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1442 * will be passed to both).
1444 * <p>This method is called before an activity may be killed so that when it
1445 * comes back some time in the future it can restore its state. For example,
1446 * if activity B is launched in front of activity A, and at some point activity
1447 * A is killed to reclaim resources, activity A will have a chance to save the
1448 * current state of its user interface via this method so that when the user
1449 * returns to activity A, the state of the user interface can be restored
1450 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1452 * <p>Do not confuse this method with activity lifecycle callbacks such as
1453 * {@link #onPause}, which is always called when an activity is being placed
1454 * in the background or on its way to destruction, or {@link #onStop} which
1455 * is called before destruction. One example of when {@link #onPause} and
1456 * {@link #onStop} is called and not this method is when a user navigates back
1457 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1458 * on B because that particular instance will never be restored, so the
1459 * system avoids calling it. An example when {@link #onPause} is called and
1460 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1461 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1462 * killed during the lifetime of B since the state of the user interface of
1463 * A will stay intact.
1465 * <p>The default implementation takes care of most of the UI per-instance
1466 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1467 * view in the hierarchy that has an id, and by saving the id of the currently
1468 * focused view (all of which is restored by the default implementation of
1469 * {@link #onRestoreInstanceState}). If you override this method to save additional
1470 * information not captured by each individual view, you will likely want to
1471 * call through to the default implementation, otherwise be prepared to save
1472 * all of the state of each view yourself.
1474 * <p>If called, this method will occur before {@link #onStop}. There are
1475 * no guarantees about whether it will occur before or after {@link #onPause}.
1477 * @param outState Bundle in which to place your saved state.
1480 * @see #onRestoreInstanceState
1483 protected void onSaveInstanceState(Bundle outState) {
1484 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1485 Parcelable p = mFragments.saveAllState();
1487 outState.putParcelable(FRAGMENTS_TAG, p);
1489 getApplication().dispatchActivitySaveInstanceState(this, outState);
1493 * This is the same as {@link #onSaveInstanceState} but is called for activities
1494 * created with the attribute {@link android.R.attr#persistableMode} set to
1495 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1496 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1497 * the first time that this activity is restarted following the next device reboot.
1499 * @param outState Bundle in which to place your saved state.
1500 * @param outPersistentState State which will be saved across reboots.
1502 * @see #onSaveInstanceState(Bundle)
1504 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1507 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1508 onSaveInstanceState(outState);
1512 * Save the state of any managed dialogs.
1514 * @param outState place to store the saved state.
1516 private void saveManagedDialogs(Bundle outState) {
1517 if (mManagedDialogs == null) {
1521 final int numDialogs = mManagedDialogs.size();
1522 if (numDialogs == 0) {
1526 Bundle dialogState = new Bundle();
1528 int[] ids = new int[mManagedDialogs.size()];
1530 // save each dialog's bundle, gather the ids
1531 for (int i = 0; i < numDialogs; i++) {
1532 final int key = mManagedDialogs.keyAt(i);
1534 final ManagedDialog md = mManagedDialogs.valueAt(i);
1535 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1536 if (md.mArgs != null) {
1537 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1541 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1542 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1547 * Called as part of the activity lifecycle when an activity is going into
1548 * the background, but has not (yet) been killed. The counterpart to
1549 * {@link #onResume}.
1551 * <p>When activity B is launched in front of activity A, this callback will
1552 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1553 * so be sure to not do anything lengthy here.
1555 * <p>This callback is mostly used for saving any persistent state the
1556 * activity is editing, to present a "edit in place" model to the user and
1557 * making sure nothing is lost if there are not enough resources to start
1558 * the new activity without first killing this one. This is also a good
1559 * place to do things like stop animations and other things that consume a
1560 * noticeable amount of CPU in order to make the switch to the next activity
1561 * as fast as possible, or to close resources that are exclusive access
1562 * such as the camera.
1564 * <p>In situations where the system needs more memory it may kill paused
1565 * processes to reclaim resources. Because of this, you should be sure
1566 * that all of your state is saved by the time you return from
1567 * this function. In general {@link #onSaveInstanceState} is used to save
1568 * per-instance state in the activity and this method is used to store
1569 * global persistent data (in content providers, files, etc.)
1571 * <p>After receiving this call you will usually receive a following call
1572 * to {@link #onStop} (after the next activity has been resumed and
1573 * displayed), however in some cases there will be a direct call back to
1574 * {@link #onResume} without going through the stopped state.
1576 * <p><em>Derived classes must call through to the super class's
1577 * implementation of this method. If they do not, an exception will be
1581 * @see #onSaveInstanceState
1585 protected void onPause() {
1586 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1587 getApplication().dispatchActivityPaused(this);
1592 * Called as part of the activity lifecycle when an activity is about to go
1593 * into the background as the result of user choice. For example, when the
1594 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1595 * when an incoming phone call causes the in-call Activity to be automatically
1596 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1597 * the activity being interrupted. In cases when it is invoked, this method
1598 * is called right before the activity's {@link #onPause} callback.
1600 * <p>This callback and {@link #onUserInteraction} are intended to help
1601 * activities manage status bar notifications intelligently; specifically,
1602 * for helping activities determine the proper time to cancel a notfication.
1604 * @see #onUserInteraction()
1606 protected void onUserLeaveHint() {
1610 * Generate a new thumbnail for this activity. This method is called before
1611 * pausing the activity, and should draw into <var>outBitmap</var> the
1612 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1613 * can use the given <var>canvas</var>, which is configured to draw into the
1614 * bitmap, for rendering if desired.
1616 * <p>The default implementation returns fails and does not draw a thumbnail;
1617 * this will result in the platform creating its own thumbnail if needed.
1619 * @param outBitmap The bitmap to contain the thumbnail.
1620 * @param canvas Can be used to render into the bitmap.
1622 * @return Return true if you have drawn into the bitmap; otherwise after
1623 * you return it will be filled with a default thumbnail.
1625 * @see #onCreateDescription
1626 * @see #onSaveInstanceState
1629 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1634 * Generate a new description for this activity. This method is called
1635 * before pausing the activity and can, if desired, return some textual
1636 * description of its current state to be displayed to the user.
1638 * <p>The default implementation returns null, which will cause you to
1639 * inherit the description from the previous activity. If all activities
1640 * return null, generally the label of the top activity will be used as the
1643 * @return A description of what the user is doing. It should be short and
1644 * sweet (only a few words).
1646 * @see #onCreateThumbnail
1647 * @see #onSaveInstanceState
1651 public CharSequence onCreateDescription() {
1656 * This is called when the user is requesting an assist, to build a full
1657 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1658 * application. You can override this method to place into the bundle anything
1659 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1660 * of the assist Intent.
1662 * <p>This function will be called after any global assist callbacks that had
1663 * been registered with {@link Application#registerOnProvideAssistDataListener
1664 * Application.registerOnProvideAssistDataListener}.
1666 public void onProvideAssistData(Bundle data) {
1670 * This is called when the user is requesting an assist, to provide references
1671 * to content related to the current activity. Before being called, the
1672 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1673 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1674 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1675 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1676 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1678 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1679 * context of the activity, and fill in its ClipData with additional content of
1680 * interest that the user is currently viewing. For example, an image gallery application
1681 * that has launched in to an activity allowing the user to swipe through pictures should
1682 * modify the intent to reference the current image they are looking it; such an
1683 * application when showing a list of pictures should add a ClipData that has
1684 * references to all of the pictures currently visible on screen.</p>
1686 * @param outContent The assist content to return.
1688 public void onProvideAssistContent(AssistContent outContent) {
1692 * Request the Keyboard Shortcuts screen to show up. This will trigger
1693 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
1695 public final void requestShowKeyboardShortcuts() {
1696 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
1697 intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
1698 KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
1699 sendBroadcast(intent);
1703 * Dismiss the Keyboard Shortcuts screen.
1705 public final void dismissKeyboardShortcutsHelper() {
1706 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
1707 intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
1708 KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
1709 sendBroadcast(intent);
1713 public void onProvideKeyboardShortcuts(
1714 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
1718 KeyboardShortcutGroup group = null;
1719 int menuSize = menu.size();
1720 for (int i = 0; i < menuSize; ++i) {
1721 final MenuItem item = menu.getItem(i);
1722 final CharSequence title = item.getTitle();
1723 final char alphaShortcut = item.getAlphabeticShortcut();
1724 if (title != null && alphaShortcut != MIN_VALUE) {
1725 if (group == null) {
1726 final int resource = mApplication.getApplicationInfo().labelRes;
1727 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
1729 group.addItem(new KeyboardShortcutInfo(
1730 title, alphaShortcut, KeyEvent.META_CTRL_ON));
1733 if (group != null) {
1739 * Ask to have the current assistant shown to the user. This only works if the calling
1740 * activity is the current foreground activity. It is the same as calling
1741 * {@link android.service.voice.VoiceInteractionService#showSession
1742 * VoiceInteractionService.showSession} and requesting all of the possible context.
1743 * The receiver will always see
1744 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1745 * @return Returns true if the assistant was successfully invoked, else false. For example
1746 * false will be returned if the caller is not the current top activity.
1748 public boolean showAssist(Bundle args) {
1750 return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args);
1751 } catch (RemoteException e) {
1757 * Called when you are no longer visible to the user. You will next
1758 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1759 * depending on later user activity.
1761 * <p><em>Derived classes must call through to the super class's
1762 * implementation of this method. If they do not, an exception will be
1767 * @see #onSaveInstanceState
1771 protected void onStop() {
1772 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1773 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1774 mActivityTransitionState.onStop();
1775 getApplication().dispatchActivityStopped(this);
1776 mTranslucentCallback = null;
1781 * Perform any final cleanup before an activity is destroyed. This can
1782 * happen either because the activity is finishing (someone called
1783 * {@link #finish} on it, or because the system is temporarily destroying
1784 * this instance of the activity to save space. You can distinguish
1785 * between these two scenarios with the {@link #isFinishing} method.
1787 * <p><em>Note: do not count on this method being called as a place for
1788 * saving data! For example, if an activity is editing data in a content
1789 * provider, those edits should be committed in either {@link #onPause} or
1790 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1791 * free resources like threads that are associated with an activity, so
1792 * that a destroyed activity does not leave such things around while the
1793 * rest of its application is still running. There are situations where
1794 * the system will simply kill the activity's hosting process without
1795 * calling this method (or any others) in it, so it should not be used to
1796 * do things that are intended to remain around after the process goes
1799 * <p><em>Derived classes must call through to the super class's
1800 * implementation of this method. If they do not, an exception will be
1809 protected void onDestroy() {
1810 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1813 // dismiss any dialogs we are managing.
1814 if (mManagedDialogs != null) {
1815 final int numDialogs = mManagedDialogs.size();
1816 for (int i = 0; i < numDialogs; i++) {
1817 final ManagedDialog md = mManagedDialogs.valueAt(i);
1818 if (md.mDialog.isShowing()) {
1819 md.mDialog.dismiss();
1822 mManagedDialogs = null;
1825 // close any cursors we are managing.
1826 synchronized (mManagedCursors) {
1827 int numCursors = mManagedCursors.size();
1828 for (int i = 0; i < numCursors; i++) {
1829 ManagedCursor c = mManagedCursors.get(i);
1834 mManagedCursors.clear();
1837 // Close any open search dialog
1838 if (mSearchManager != null) {
1839 mSearchManager.stopSearch();
1842 if (mActionBar != null) {
1843 mActionBar.onDestroy();
1846 getApplication().dispatchActivityDestroyed(this);
1850 * Report to the system that your app is now fully drawn, purely for diagnostic
1851 * purposes (calling it does not impact the visible behavior of the activity).
1852 * This is only used to help instrument application launch times, so that the
1853 * app can report when it is fully in a usable state; without this, the only thing
1854 * the system itself can determine is the point at which the activity's window
1855 * is <em>first</em> drawn and displayed. To participate in app launch time
1856 * measurement, you should always call this method after first launch (when
1857 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1858 * entirely drawn your UI and populated with all of the significant data. You
1859 * can safely call this method any time after first launch as well, in which case
1860 * it will simply be ignored.
1862 public void reportFullyDrawn() {
1863 if (mDoReportFullyDrawn) {
1864 mDoReportFullyDrawn = false;
1866 ActivityManagerNative.getDefault().reportActivityFullyDrawn(mToken);
1867 } catch (RemoteException e) {
1873 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
1875 * @see android.R.attr#resizeableActivity
1877 * @param isInMultiWindowMode True if the activity is in multi-window mode.
1879 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
1880 // Left deliberately empty. There should be no side effects if a direct
1881 // subclass of Activity does not call super.
1885 * Returns true if the activity is currently in multi-window mode.
1886 * @see android.R.attr#resizeableActivity
1888 * @return True if the activity is in multi-window mode.
1890 public boolean isInMultiWindowMode() {
1892 return ActivityManagerNative.getDefault().isInMultiWindowMode(mToken);
1893 } catch (RemoteException e) {
1899 * Called by the system when the activity changes to and from picture-in-picture mode.
1900 * @see android.R.attr#supportsPictureInPicture
1902 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
1904 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
1905 // Left deliberately empty. There should be no side effects if a direct
1906 // subclass of Activity does not call super.
1910 * Returns true if the activity is currently in picture-in-picture mode.
1911 * @see android.R.attr#supportsPictureInPicture
1913 * @return True if the activity is in picture-in-picture mode.
1915 public boolean isInPictureInPictureMode() {
1917 return ActivityManagerNative.getDefault().isInPictureInPictureMode(mToken);
1918 } catch (RemoteException e) {
1924 * Puts the activity in picture-in-picture mode.
1925 * @see android.R.attr#supportsPictureInPicture
1927 public void enterPictureInPictureMode() {
1929 ActivityManagerNative.getDefault().enterPictureInPictureMode(mToken);
1930 } catch (RemoteException e) {
1935 * Called by the system when the device configuration changes while your
1936 * activity is running. Note that this will <em>only</em> be called if
1937 * you have selected configurations you would like to handle with the
1938 * {@link android.R.attr#configChanges} attribute in your manifest. If
1939 * any configuration change occurs that is not selected to be reported
1940 * by that attribute, then instead of reporting it the system will stop
1941 * and restart the activity (to have it launched with the new
1944 * <p>At the time that this function has been called, your Resources
1945 * object will have been updated to return resource values matching the
1946 * new configuration.
1948 * @param newConfig The new device configuration.
1950 public void onConfigurationChanged(Configuration newConfig) {
1951 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
1954 mFragments.dispatchConfigurationChanged(newConfig);
1956 if (mWindow != null) {
1957 // Pass the configuration changed event to the window
1958 mWindow.onConfigurationChanged(newConfig);
1961 if (mActionBar != null) {
1962 // Do this last; the action bar will need to access
1963 // view changes from above.
1964 mActionBar.onConfigurationChanged(newConfig);
1969 * If this activity is being destroyed because it can not handle a
1970 * configuration parameter being changed (and thus its
1971 * {@link #onConfigurationChanged(Configuration)} method is
1972 * <em>not</em> being called), then you can use this method to discover
1973 * the set of changes that have occurred while in the process of being
1974 * destroyed. Note that there is no guarantee that these will be
1975 * accurate (other changes could have happened at any time), so you should
1976 * only use this as an optimization hint.
1978 * @return Returns a bit field of the configuration parameters that are
1979 * changing, as defined by the {@link android.content.res.Configuration}
1982 public int getChangingConfigurations() {
1983 return mConfigChangeFlags;
1987 * Retrieve the non-configuration instance data that was previously
1988 * returned by {@link #onRetainNonConfigurationInstance()}. This will
1989 * be available from the initial {@link #onCreate} and
1990 * {@link #onStart} calls to the new instance, allowing you to extract
1991 * any useful dynamic state from the previous instance.
1993 * <p>Note that the data you retrieve here should <em>only</em> be used
1994 * as an optimization for handling configuration changes. You should always
1995 * be able to handle getting a null pointer back, and an activity must
1996 * still be able to restore itself to its previous state (through the
1997 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
1998 * function returns null.
2000 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2001 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2002 * available on older platforms through the Android support libraries.
2004 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
2007 public Object getLastNonConfigurationInstance() {
2008 return mLastNonConfigurationInstances != null
2009 ? mLastNonConfigurationInstances.activity : null;
2013 * Called by the system, as part of destroying an
2014 * activity due to a configuration change, when it is known that a new
2015 * instance will immediately be created for the new configuration. You
2016 * can return any object you like here, including the activity instance
2017 * itself, which can later be retrieved by calling
2018 * {@link #getLastNonConfigurationInstance()} in the new activity
2021 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2022 * or later, consider instead using a {@link Fragment} with
2023 * {@link Fragment#setRetainInstance(boolean)
2024 * Fragment.setRetainInstance(boolean}.</em>
2026 * <p>This function is called purely as an optimization, and you must
2027 * not rely on it being called. When it is called, a number of guarantees
2028 * will be made to help optimize configuration switching:
2030 * <li> The function will be called between {@link #onStop} and
2031 * {@link #onDestroy}.
2032 * <li> A new instance of the activity will <em>always</em> be immediately
2033 * created after this one's {@link #onDestroy()} is called. In particular,
2034 * <em>no</em> messages will be dispatched during this time (when the returned
2035 * object does not have an activity to be associated with).
2036 * <li> The object you return here will <em>always</em> be available from
2037 * the {@link #getLastNonConfigurationInstance()} method of the following
2038 * activity instance as described there.
2041 * <p>These guarantees are designed so that an activity can use this API
2042 * to propagate extensive state from the old to new activity instance, from
2043 * loaded bitmaps, to network connections, to evenly actively running
2044 * threads. Note that you should <em>not</em> propagate any data that
2045 * may change based on the configuration, including any data loaded from
2046 * resources such as strings, layouts, or drawables.
2048 * <p>The guarantee of no message handling during the switch to the next
2049 * activity simplifies use with active objects. For example if your retained
2050 * state is an {@link android.os.AsyncTask} you are guaranteed that its
2051 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
2052 * not be called from the call here until you execute the next instance's
2053 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
2054 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
2055 * running in a separate thread.)
2057 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2058 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2059 * available on older platforms through the Android support libraries.
2061 * @return any Object holding the desired state to propagate to the
2062 * next activity instance
2064 public Object onRetainNonConfigurationInstance() {
2069 * Retrieve the non-configuration instance data that was previously
2070 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
2071 * be available from the initial {@link #onCreate} and
2072 * {@link #onStart} calls to the new instance, allowing you to extract
2073 * any useful dynamic state from the previous instance.
2075 * <p>Note that the data you retrieve here should <em>only</em> be used
2076 * as an optimization for handling configuration changes. You should always
2077 * be able to handle getting a null pointer back, and an activity must
2078 * still be able to restore itself to its previous state (through the
2079 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2080 * function returns null.
2082 * @return Returns the object previously returned by
2083 * {@link #onRetainNonConfigurationChildInstances()}
2086 HashMap<String, Object> getLastNonConfigurationChildInstances() {
2087 return mLastNonConfigurationInstances != null
2088 ? mLastNonConfigurationInstances.children : null;
2092 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
2093 * it should return either a mapping from child activity id strings to arbitrary objects,
2094 * or null. This method is intended to be used by Activity framework subclasses that control a
2095 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
2096 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
2099 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
2103 NonConfigurationInstances retainNonConfigurationInstances() {
2104 Object activity = onRetainNonConfigurationInstance();
2105 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
2106 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
2108 // We're already stopped but we've been asked to retain.
2109 // Our fragments are taken care of but we need to mark the loaders for retention.
2110 // In order to do this correctly we need to restart the loaders first before
2111 // handing them off to the next activity.
2112 mFragments.doLoaderStart();
2113 mFragments.doLoaderStop(true);
2114 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
2116 if (activity == null && children == null && fragments == null && loaders == null
2117 && mVoiceInteractor == null) {
2121 NonConfigurationInstances nci = new NonConfigurationInstances();
2122 nci.activity = activity;
2123 nci.children = children;
2124 nci.fragments = fragments;
2125 nci.loaders = loaders;
2126 if (mVoiceInteractor != null) {
2127 mVoiceInteractor.retainInstance();
2128 nci.voiceInteractor = mVoiceInteractor;
2133 public void onLowMemory() {
2134 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
2136 mFragments.dispatchLowMemory();
2139 public void onTrimMemory(int level) {
2140 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
2142 mFragments.dispatchTrimMemory(level);
2146 * Return the FragmentManager for interacting with fragments associated
2147 * with this activity.
2149 public FragmentManager getFragmentManager() {
2150 return mFragments.getFragmentManager();
2154 * Called when a Fragment is being attached to this activity, immediately
2155 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
2156 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
2158 public void onAttachFragment(Fragment fragment) {
2163 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2164 * that gives the resulting {@link Cursor} to call
2165 * {@link #startManagingCursor} so that the activity will manage its
2166 * lifecycle for you.
2168 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2169 * or later, consider instead using {@link LoaderManager} instead, available
2170 * via {@link #getLoaderManager()}.</em>
2172 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2173 * this method, because the activity will do that for you at the appropriate time. However, if
2174 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2175 * not</em> automatically close the cursor and, in that case, you must call
2176 * {@link Cursor#close()}.</p>
2178 * @param uri The URI of the content provider to query.
2179 * @param projection List of columns to return.
2180 * @param selection SQL WHERE clause.
2181 * @param sortOrder SQL ORDER BY clause.
2183 * @return The Cursor that was returned by query().
2185 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2186 * @see #startManagingCursor
2189 * @deprecated Use {@link CursorLoader} instead.
2192 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2194 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
2196 startManagingCursor(c);
2203 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2204 * that gives the resulting {@link Cursor} to call
2205 * {@link #startManagingCursor} so that the activity will manage its
2206 * lifecycle for you.
2208 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2209 * or later, consider instead using {@link LoaderManager} instead, available
2210 * via {@link #getLoaderManager()}.</em>
2212 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2213 * this method, because the activity will do that for you at the appropriate time. However, if
2214 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2215 * not</em> automatically close the cursor and, in that case, you must call
2216 * {@link Cursor#close()}.</p>
2218 * @param uri The URI of the content provider to query.
2219 * @param projection List of columns to return.
2220 * @param selection SQL WHERE clause.
2221 * @param selectionArgs The arguments to selection, if any ?s are pesent
2222 * @param sortOrder SQL ORDER BY clause.
2224 * @return The Cursor that was returned by query().
2226 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2227 * @see #startManagingCursor
2229 * @deprecated Use {@link CursorLoader} instead.
2232 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2233 String[] selectionArgs, String sortOrder) {
2234 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2236 startManagingCursor(c);
2242 * This method allows the activity to take care of managing the given
2243 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2244 * That is, when the activity is stopped it will automatically call
2245 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2246 * it will call {@link Cursor#requery} for you. When the activity is
2247 * destroyed, all managed Cursors will be closed automatically.
2249 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2250 * or later, consider instead using {@link LoaderManager} instead, available
2251 * via {@link #getLoaderManager()}.</em>
2253 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2254 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2255 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2256 * <em>will not</em> automatically close the cursor and, in that case, you must call
2257 * {@link Cursor#close()}.</p>
2259 * @param c The Cursor to be managed.
2261 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2262 * @see #stopManagingCursor
2264 * @deprecated Use the new {@link android.content.CursorLoader} class with
2265 * {@link LoaderManager} instead; this is also
2266 * available on older platforms through the Android compatibility package.
2269 public void startManagingCursor(Cursor c) {
2270 synchronized (mManagedCursors) {
2271 mManagedCursors.add(new ManagedCursor(c));
2276 * Given a Cursor that was previously given to
2277 * {@link #startManagingCursor}, stop the activity's management of that
2280 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2281 * the system <em>will not</em> automatically close the cursor and you must call
2282 * {@link Cursor#close()}.</p>
2284 * @param c The Cursor that was being managed.
2286 * @see #startManagingCursor
2288 * @deprecated Use the new {@link android.content.CursorLoader} class with
2289 * {@link LoaderManager} instead; this is also
2290 * available on older platforms through the Android compatibility package.
2293 public void stopManagingCursor(Cursor c) {
2294 synchronized (mManagedCursors) {
2295 final int N = mManagedCursors.size();
2296 for (int i=0; i<N; i++) {
2297 ManagedCursor mc = mManagedCursors.get(i);
2298 if (mc.mCursor == c) {
2299 mManagedCursors.remove(i);
2307 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2312 public void setPersistent(boolean isPersistent) {
2316 * Finds a view that was identified by the id attribute from the XML that
2317 * was processed in {@link #onCreate}.
2319 * @return The view if found or null otherwise.
2322 public View findViewById(@IdRes int id) {
2323 return getWindow().findViewById(id);
2327 * Retrieve a reference to this activity's ActionBar.
2329 * @return The Activity's ActionBar, or null if it does not have one.
2332 public ActionBar getActionBar() {
2333 initWindowDecorActionBar();
2338 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2341 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2342 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2343 * a traditional window decor action bar. The toolbar's menu will be populated with the
2344 * Activity's options menu and the navigation button will be wired through the standard
2345 * {@link android.R.id#home home} menu select action.</p>
2347 * <p>In order to use a Toolbar within the Activity's window content the application
2348 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2350 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
2352 public void setActionBar(@Nullable Toolbar toolbar) {
2353 final ActionBar ab = getActionBar();
2354 if (ab instanceof WindowDecorActionBar) {
2355 throw new IllegalStateException("This Activity already has an action bar supplied " +
2356 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2357 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2360 // If we reach here then we're setting a new action bar
2361 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
2362 mMenuInflater = null;
2364 // If we have an action bar currently, destroy it
2369 if (toolbar != null) {
2370 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2372 mWindow.setCallback(tbab.getWrappedWindowCallback());
2375 // Re-set the original window callback since we may have already set a Toolbar wrapper
2376 mWindow.setCallback(this);
2379 invalidateOptionsMenu();
2383 * Creates a new ActionBar, locates the inflated ActionBarView,
2384 * initializes the ActionBar with the view, and sets mActionBar.
2386 private void initWindowDecorActionBar() {
2387 Window window = getWindow();
2389 // Initializing the window decor can change window feature flags.
2390 // Make sure that we have the correct set before performing the test below.
2391 window.getDecorView();
2393 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2397 mActionBar = new WindowDecorActionBar(this);
2398 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2400 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2401 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2405 * Set the activity content from a layout resource. The resource will be
2406 * inflated, adding all top-level views to the activity.
2408 * @param layoutResID Resource ID to be inflated.
2410 * @see #setContentView(android.view.View)
2411 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2413 public void setContentView(@LayoutRes int layoutResID) {
2414 getWindow().setContentView(layoutResID);
2415 initWindowDecorActionBar();
2419 * Set the activity content to an explicit view. This view is placed
2420 * directly into the activity's view hierarchy. It can itself be a complex
2421 * view hierarchy. When calling this method, the layout parameters of the
2422 * specified view are ignored. Both the width and the height of the view are
2423 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2424 * your own layout parameters, invoke
2425 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2428 * @param view The desired content to display.
2430 * @see #setContentView(int)
2431 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2433 public void setContentView(View view) {
2434 getWindow().setContentView(view);
2435 initWindowDecorActionBar();
2439 * Set the activity content to an explicit view. This view is placed
2440 * directly into the activity's view hierarchy. It can itself be a complex
2443 * @param view The desired content to display.
2444 * @param params Layout parameters for the view.
2446 * @see #setContentView(android.view.View)
2447 * @see #setContentView(int)
2449 public void setContentView(View view, ViewGroup.LayoutParams params) {
2450 getWindow().setContentView(view, params);
2451 initWindowDecorActionBar();
2455 * Add an additional content view to the activity. Added after any existing
2456 * ones in the activity -- existing views are NOT removed.
2458 * @param view The desired content to display.
2459 * @param params Layout parameters for the view.
2461 public void addContentView(View view, ViewGroup.LayoutParams params) {
2462 getWindow().addContentView(view, params);
2463 initWindowDecorActionBar();
2467 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2468 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2470 * <p>This method will return non-null after content has been initialized (e.g. by using
2471 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2473 * @return This window's content TransitionManager or null if none is set.
2475 public TransitionManager getContentTransitionManager() {
2476 return getWindow().getTransitionManager();
2480 * Set the {@link TransitionManager} to use for default transitions in this window.
2481 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2483 * @param tm The TransitionManager to use for scene changes.
2485 public void setContentTransitionManager(TransitionManager tm) {
2486 getWindow().setTransitionManager(tm);
2490 * Retrieve the {@link Scene} representing this window's current content.
2491 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2493 * <p>This method will return null if the current content is not represented by a Scene.</p>
2495 * @return Current Scene being shown or null
2497 public Scene getContentScene() {
2498 return getWindow().getContentScene();
2502 * Sets whether this activity is finished when touched outside its window's
2505 public void setFinishOnTouchOutside(boolean finish) {
2506 mWindow.setCloseOnTouchOutside(finish);
2511 DEFAULT_KEYS_DISABLE,
2512 DEFAULT_KEYS_DIALER,
2513 DEFAULT_KEYS_SHORTCUT,
2514 DEFAULT_KEYS_SEARCH_LOCAL,
2515 DEFAULT_KEYS_SEARCH_GLOBAL})
2516 @Retention(RetentionPolicy.SOURCE)
2517 @interface DefaultKeyMode {}
2520 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2523 * @see #setDefaultKeyMode
2525 static public final int DEFAULT_KEYS_DISABLE = 0;
2527 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2530 * @see #setDefaultKeyMode
2532 static public final int DEFAULT_KEYS_DIALER = 1;
2534 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2535 * default key handling.
2537 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2539 * @see #setDefaultKeyMode
2541 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2543 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2544 * will start an application-defined search. (If the application or activity does not
2545 * actually define a search, the the keys will be ignored.)
2547 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2549 * @see #setDefaultKeyMode
2551 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2554 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2555 * will start a global search (typically web search, but some platforms may define alternate
2556 * methods for global search)
2558 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2560 * @see #setDefaultKeyMode
2562 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2565 * Select the default key handling for this activity. This controls what
2566 * will happen to key events that are not otherwise handled. The default
2567 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2568 * floor. Other modes allow you to launch the dialer
2569 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2570 * menu without requiring the menu key be held down
2571 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2572 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2574 * <p>Note that the mode selected here does not impact the default
2575 * handling of system keys, such as the "back" and "menu" keys, and your
2576 * activity and its views always get a first chance to receive and handle
2577 * all application keys.
2579 * @param mode The desired default key mode constant.
2581 * @see #DEFAULT_KEYS_DISABLE
2582 * @see #DEFAULT_KEYS_DIALER
2583 * @see #DEFAULT_KEYS_SHORTCUT
2584 * @see #DEFAULT_KEYS_SEARCH_LOCAL
2585 * @see #DEFAULT_KEYS_SEARCH_GLOBAL
2588 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2589 mDefaultKeyMode = mode;
2591 // Some modes use a SpannableStringBuilder to track & dispatch input events
2592 // This list must remain in sync with the switch in onKeyDown()
2594 case DEFAULT_KEYS_DISABLE:
2595 case DEFAULT_KEYS_SHORTCUT:
2596 mDefaultKeySsb = null; // not used in these modes
2598 case DEFAULT_KEYS_DIALER:
2599 case DEFAULT_KEYS_SEARCH_LOCAL:
2600 case DEFAULT_KEYS_SEARCH_GLOBAL:
2601 mDefaultKeySsb = new SpannableStringBuilder();
2602 Selection.setSelection(mDefaultKeySsb,0);
2605 throw new IllegalArgumentException();
2610 * Called when a key was pressed down and not handled by any of the views
2611 * inside of the activity. So, for example, key presses while the cursor
2612 * is inside a TextView will not trigger the event (unless it is a navigation
2613 * to another object) because TextView handles its own key presses.
2615 * <p>If the focused view didn't want this event, this method is called.
2617 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2618 * by calling {@link #onBackPressed()}, though the behavior varies based
2619 * on the application compatibility mode: for
2620 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2621 * it will set up the dispatch to call {@link #onKeyUp} where the action
2622 * will be performed; for earlier applications, it will perform the
2623 * action immediately in on-down, as those versions of the platform
2626 * <p>Other additional default key handling may be performed
2627 * if configured with {@link #setDefaultKeyMode}.
2629 * @return Return <code>true</code> to prevent this event from being propagated
2630 * further, or <code>false</code> to indicate that you have not handled
2631 * this event and it should continue to be propagated.
2633 * @see android.view.KeyEvent
2635 public boolean onKeyDown(int keyCode, KeyEvent event) {
2636 if (keyCode == KeyEvent.KEYCODE_BACK) {
2637 if (getApplicationInfo().targetSdkVersion
2638 >= Build.VERSION_CODES.ECLAIR) {
2639 event.startTracking();
2646 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2648 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2649 Window w = getWindow();
2650 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2651 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2652 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2657 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2658 boolean clearSpannable = false;
2660 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2661 clearSpannable = true;
2664 handled = TextKeyListener.getInstance().onKeyDown(
2665 null, mDefaultKeySsb, keyCode, event);
2666 if (handled && mDefaultKeySsb.length() > 0) {
2667 // something useable has been typed - dispatch it now.
2669 final String str = mDefaultKeySsb.toString();
2670 clearSpannable = true;
2672 switch (mDefaultKeyMode) {
2673 case DEFAULT_KEYS_DIALER:
2674 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2675 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2676 startActivity(intent);
2678 case DEFAULT_KEYS_SEARCH_LOCAL:
2679 startSearch(str, false, null, false);
2681 case DEFAULT_KEYS_SEARCH_GLOBAL:
2682 startSearch(str, false, null, true);
2687 if (clearSpannable) {
2688 mDefaultKeySsb.clear();
2689 mDefaultKeySsb.clearSpans();
2690 Selection.setSelection(mDefaultKeySsb,0);
2697 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2698 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2701 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2706 * Called when a key was released and not handled by any of the views
2707 * inside of the activity. So, for example, key presses while the cursor
2708 * is inside a TextView will not trigger the event (unless it is a navigation
2709 * to another object) because TextView handles its own key presses.
2711 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2714 * @return Return <code>true</code> to prevent this event from being propagated
2715 * further, or <code>false</code> to indicate that you have not handled
2716 * this event and it should continue to be propagated.
2720 public boolean onKeyUp(int keyCode, KeyEvent event) {
2721 if (getApplicationInfo().targetSdkVersion
2722 >= Build.VERSION_CODES.ECLAIR) {
2723 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2724 && !event.isCanceled()) {
2733 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2734 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2737 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2742 * Called when the activity has detected the user's press of the back
2743 * key. The default implementation simply finishes the current activity,
2744 * but you can override this to do whatever you want.
2746 public void onBackPressed() {
2747 if (mActionBar != null && mActionBar.collapseActionView()) {
2751 if (!mFragments.getFragmentManager().popBackStackImmediate()) {
2752 finishAfterTransition();
2757 * Called when a key shortcut event is not handled by any of the views in the Activity.
2758 * Override this method to implement global key shortcuts for the Activity.
2759 * Key shortcuts can also be implemented by setting the
2760 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
2762 * @param keyCode The value in event.getKeyCode().
2763 * @param event Description of the key event.
2764 * @return True if the key shortcut was handled.
2766 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
2767 // Let the Action Bar have a chance at handling the shortcut.
2768 ActionBar actionBar = getActionBar();
2769 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
2773 * Called when a touch screen event was not handled by any of the views
2774 * under it. This is most useful to process touch events that happen
2775 * outside of your window bounds, where there is no view to receive it.
2777 * @param event The touch screen event being processed.
2779 * @return Return true if you have consumed the event, false if you haven't.
2780 * The default implementation always returns false.
2782 public boolean onTouchEvent(MotionEvent event) {
2783 if (mWindow.shouldCloseOnTouch(this, event)) {
2792 * Called when the trackball was moved and not handled by any of the
2793 * views inside of the activity. So, for example, if the trackball moves
2794 * while focus is on a button, you will receive a call here because
2795 * buttons do not normally do anything with trackball events. The call
2796 * here happens <em>before</em> trackball movements are converted to
2797 * DPAD key events, which then get sent back to the view hierarchy, and
2798 * will be processed at the point for things like focus navigation.
2800 * @param event The trackball event being processed.
2802 * @return Return true if you have consumed the event, false if you haven't.
2803 * The default implementation always returns false.
2805 public boolean onTrackballEvent(MotionEvent event) {
2810 * Called when a generic motion event was not handled by any of the
2811 * views inside of the activity.
2813 * Generic motion events describe joystick movements, mouse hovers, track pad
2814 * touches, scroll wheel movements and other input events. The
2815 * {@link MotionEvent#getSource() source} of the motion event specifies
2816 * the class of input that was received. Implementations of this method
2817 * must examine the bits in the source before processing the event.
2818 * The following code example shows how this is done.
2820 * Generic motion events with source class
2821 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
2822 * are delivered to the view under the pointer. All other generic motion events are
2823 * delivered to the focused view.
2825 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
2826 * handle this event.
2829 * @param event The generic motion event being processed.
2831 * @return Return true if you have consumed the event, false if you haven't.
2832 * The default implementation always returns false.
2834 public boolean onGenericMotionEvent(MotionEvent event) {
2839 * Called whenever a key, touch, or trackball event is dispatched to the
2840 * activity. Implement this method if you wish to know that the user has
2841 * interacted with the device in some way while your activity is running.
2842 * This callback and {@link #onUserLeaveHint} are intended to help
2843 * activities manage status bar notifications intelligently; specifically,
2844 * for helping activities determine the proper time to cancel a notfication.
2846 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
2847 * be accompanied by calls to {@link #onUserInteraction}. This
2848 * ensures that your activity will be told of relevant user activity such
2849 * as pulling down the notification pane and touching an item there.
2851 * <p>Note that this callback will be invoked for the touch down action
2852 * that begins a touch gesture, but may not be invoked for the touch-moved
2853 * and touch-up actions that follow.
2855 * @see #onUserLeaveHint()
2857 public void onUserInteraction() {
2860 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
2861 // Update window manager if: we have a view, that view is
2862 // attached to its parent (which will be a RootView), and
2863 // this activity is not embedded.
2864 if (mParent == null) {
2865 View decor = mDecor;
2866 if (decor != null && decor.getParent() != null) {
2867 getWindowManager().updateViewLayout(decor, params);
2872 public void onContentChanged() {
2876 * Called when the current {@link Window} of the activity gains or loses
2877 * focus. This is the best indicator of whether this activity is visible
2878 * to the user. The default implementation clears the key tracking
2879 * state, so should always be called.
2881 * <p>Note that this provides information about global focus state, which
2882 * is managed independently of activity lifecycles. As such, while focus
2883 * changes will generally have some relation to lifecycle changes (an
2884 * activity that is stopped will not generally get window focus), you
2885 * should not rely on any particular order between the callbacks here and
2886 * those in the other lifecycle methods such as {@link #onResume}.
2888 * <p>As a general rule, however, a resumed activity will have window
2889 * focus... unless it has displayed other dialogs or popups that take
2890 * input focus, in which case the activity itself will not have focus
2891 * when the other windows have it. Likewise, the system may display
2892 * system-level windows (such as the status bar notification panel or
2893 * a system alert) which will temporarily take window input focus without
2894 * pausing the foreground activity.
2896 * @param hasFocus Whether the window of this activity has focus.
2898 * @see #hasWindowFocus()
2900 * @see View#onWindowFocusChanged(boolean)
2902 public void onWindowFocusChanged(boolean hasFocus) {
2906 * Called when the main window associated with the activity has been
2907 * attached to the window manager.
2908 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
2909 * for more information.
2910 * @see View#onAttachedToWindow
2912 public void onAttachedToWindow() {
2916 * Called when the main window associated with the activity has been
2917 * detached from the window manager.
2918 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
2919 * for more information.
2920 * @see View#onDetachedFromWindow
2922 public void onDetachedFromWindow() {
2926 * Returns true if this activity's <em>main</em> window currently has window focus.
2927 * Note that this is not the same as the view itself having focus.
2929 * @return True if this activity's main window currently has window focus.
2931 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
2933 public boolean hasWindowFocus() {
2934 Window w = getWindow();
2936 View d = w.getDecorView();
2938 return d.hasWindowFocus();
2945 * Called when the main window associated with the activity has been dismissed.
2949 public void onWindowDismissed(boolean finishTask) {
2950 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
2955 * Moves the activity from
2956 * {@link android.app.ActivityManager.StackId#FREEFORM_WORKSPACE_STACK_ID} to
2957 * {@link android.app.ActivityManager.StackId#FULLSCREEN_WORKSPACE_STACK_ID} stack.
2962 public void exitFreeformMode() throws RemoteException {
2963 ActivityManagerNative.getDefault().exitFreeformMode(mToken);
2966 /** Returns the current stack Id for the window.
2970 public int getWindowStackId() throws RemoteException {
2971 return ActivityManagerNative.getDefault().getActivityStackId(mToken);
2975 * Puts the activity in picture-in-picture mode if the activity supports.
2976 * @see android.R.attr#supportsPictureInPicture
2980 public void enterPictureInPictureModeIfPossible() {
2981 if (mActivityInfo.resizeMode == ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE) {
2982 enterPictureInPictureMode();
2987 * Called to process key events. You can override this to intercept all
2988 * key events before they are dispatched to the window. Be sure to call
2989 * this implementation for key events that should be handled normally.
2991 * @param event The key event.
2993 * @return boolean Return true if this event was consumed.
2995 public boolean dispatchKeyEvent(KeyEvent event) {
2996 onUserInteraction();
2998 // Let action bars open menus in response to the menu key prioritized over
2999 // the window handling it
3000 final int keyCode = event.getKeyCode();
3001 if (keyCode == KeyEvent.KEYCODE_MENU &&
3002 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
3004 } else if (event.isCtrlPressed() &&
3005 event.getUnicodeChar(event.getMetaState() & ~KeyEvent.META_CTRL_MASK) == '<') {
3006 // Capture the Control-< and send focus to the ActionBar
3007 final int action = event.getAction();
3008 if (action == KeyEvent.ACTION_DOWN) {
3009 final ActionBar actionBar = getActionBar();
3010 if (actionBar != null && actionBar.isShowing() && actionBar.requestFocus()) {
3011 mEatKeyUpEvent = true;
3014 } else if (action == KeyEvent.ACTION_UP && mEatKeyUpEvent) {
3015 mEatKeyUpEvent = false;
3020 Window win = getWindow();
3021 if (win.superDispatchKeyEvent(event)) {
3024 View decor = mDecor;
3025 if (decor == null) decor = win.getDecorView();
3026 return event.dispatch(this, decor != null
3027 ? decor.getKeyDispatcherState() : null, this);
3031 * Called to process a key shortcut event.
3032 * You can override this to intercept all key shortcut events before they are
3033 * dispatched to the window. Be sure to call this implementation for key shortcut
3034 * events that should be handled normally.
3036 * @param event The key shortcut event.
3037 * @return True if this event was consumed.
3039 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3040 onUserInteraction();
3041 if (getWindow().superDispatchKeyShortcutEvent(event)) {
3044 return onKeyShortcut(event.getKeyCode(), event);
3048 * Called to process touch screen events. You can override this to
3049 * intercept all touch screen events before they are dispatched to the
3050 * window. Be sure to call this implementation for touch screen events
3051 * that should be handled normally.
3053 * @param ev The touch screen event.
3055 * @return boolean Return true if this event was consumed.
3057 public boolean dispatchTouchEvent(MotionEvent ev) {
3058 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
3059 onUserInteraction();
3061 if (getWindow().superDispatchTouchEvent(ev)) {
3064 return onTouchEvent(ev);
3068 * Called to process trackball events. You can override this to
3069 * intercept all trackball events before they are dispatched to the
3070 * window. Be sure to call this implementation for trackball events
3071 * that should be handled normally.
3073 * @param ev The trackball event.
3075 * @return boolean Return true if this event was consumed.
3077 public boolean dispatchTrackballEvent(MotionEvent ev) {
3078 onUserInteraction();
3079 if (getWindow().superDispatchTrackballEvent(ev)) {
3082 return onTrackballEvent(ev);
3086 * Called to process generic motion events. You can override this to
3087 * intercept all generic motion events before they are dispatched to the
3088 * window. Be sure to call this implementation for generic motion events
3089 * that should be handled normally.
3091 * @param ev The generic motion event.
3093 * @return boolean Return true if this event was consumed.
3095 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3096 onUserInteraction();
3097 if (getWindow().superDispatchGenericMotionEvent(ev)) {
3100 return onGenericMotionEvent(ev);
3103 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3104 event.setClassName(getClass().getName());
3105 event.setPackageName(getPackageName());
3107 LayoutParams params = getWindow().getAttributes();
3108 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
3109 (params.height == LayoutParams.MATCH_PARENT);
3110 event.setFullScreen(isFullScreen);
3112 CharSequence title = getTitle();
3113 if (!TextUtils.isEmpty(title)) {
3114 event.getText().add(title);
3121 * Default implementation of
3122 * {@link android.view.Window.Callback#onCreatePanelView}
3123 * for activities. This
3124 * simply returns null so that all panel sub-windows will have the default
3128 public View onCreatePanelView(int featureId) {
3133 * Default implementation of
3134 * {@link android.view.Window.Callback#onCreatePanelMenu}
3135 * for activities. This calls through to the new
3136 * {@link #onCreateOptionsMenu} method for the
3137 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3138 * so that subclasses of Activity don't need to deal with feature codes.
3140 public boolean onCreatePanelMenu(int featureId, Menu menu) {
3141 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
3142 boolean show = onCreateOptionsMenu(menu);
3143 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
3150 * Default implementation of
3151 * {@link android.view.Window.Callback#onPreparePanel}
3152 * for activities. This
3153 * calls through to the new {@link #onPrepareOptionsMenu} method for the
3154 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3155 * panel, so that subclasses of
3156 * Activity don't need to deal with feature codes.
3158 public boolean onPreparePanel(int featureId, View view, Menu menu) {
3159 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
3160 boolean goforit = onPrepareOptionsMenu(menu);
3161 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
3170 * @return The default implementation returns true.
3172 public boolean onMenuOpened(int featureId, Menu menu) {
3173 if (featureId == Window.FEATURE_ACTION_BAR) {
3174 initWindowDecorActionBar();
3175 if (mActionBar != null) {
3176 mActionBar.dispatchMenuVisibilityChanged(true);
3178 Log.e(TAG, "Tried to open action bar menu with no action bar");
3185 * Default implementation of
3186 * {@link android.view.Window.Callback#onMenuItemSelected}
3187 * for activities. This calls through to the new
3188 * {@link #onOptionsItemSelected} method for the
3189 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3190 * panel, so that subclasses of
3191 * Activity don't need to deal with feature codes.
3193 public boolean onMenuItemSelected(int featureId, MenuItem item) {
3194 CharSequence titleCondensed = item.getTitleCondensed();
3196 switch (featureId) {
3197 case Window.FEATURE_OPTIONS_PANEL:
3198 // Put event logging here so it gets called even if subclass
3199 // doesn't call through to superclass's implmeentation of each
3200 // of these methods below
3201 if(titleCondensed != null) {
3202 EventLog.writeEvent(50000, 0, titleCondensed.toString());
3204 if (onOptionsItemSelected(item)) {
3207 if (mFragments.dispatchOptionsItemSelected(item)) {
3210 if (item.getItemId() == android.R.id.home && mActionBar != null &&
3211 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
3212 if (mParent == null) {
3213 return onNavigateUp();
3215 return mParent.onNavigateUpFromChild(this);
3220 case Window.FEATURE_CONTEXT_MENU:
3221 if(titleCondensed != null) {
3222 EventLog.writeEvent(50000, 1, titleCondensed.toString());
3224 if (onContextItemSelected(item)) {
3227 return mFragments.dispatchContextItemSelected(item);
3235 * Default implementation of
3236 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
3237 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
3238 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3239 * so that subclasses of Activity don't need to deal with feature codes.
3240 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
3241 * {@link #onContextMenuClosed(Menu)} will be called.
3243 public void onPanelClosed(int featureId, Menu menu) {
3244 switch (featureId) {
3245 case Window.FEATURE_OPTIONS_PANEL:
3246 mFragments.dispatchOptionsMenuClosed(menu);
3247 onOptionsMenuClosed(menu);
3250 case Window.FEATURE_CONTEXT_MENU:
3251 onContextMenuClosed(menu);
3254 case Window.FEATURE_ACTION_BAR:
3255 initWindowDecorActionBar();
3256 mActionBar.dispatchMenuVisibilityChanged(false);
3262 * Declare that the options menu has changed, so should be recreated.
3263 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
3264 * time it needs to be displayed.
3266 public void invalidateOptionsMenu() {
3267 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3268 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
3269 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
3274 * Initialize the contents of the Activity's standard options menu. You
3275 * should place your menu items in to <var>menu</var>.
3277 * <p>This is only called once, the first time the options menu is
3278 * displayed. To update the menu every time it is displayed, see
3279 * {@link #onPrepareOptionsMenu}.
3281 * <p>The default implementation populates the menu with standard system
3282 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
3283 * they will be correctly ordered with application-defined menu items.
3284 * Deriving classes should always call through to the base implementation.
3286 * <p>You can safely hold on to <var>menu</var> (and any items created
3287 * from it), making modifications to it as desired, until the next
3288 * time onCreateOptionsMenu() is called.
3290 * <p>When you add items to the menu, you can implement the Activity's
3291 * {@link #onOptionsItemSelected} method to handle them there.
3293 * @param menu The options menu in which you place your items.
3295 * @return You must return true for the menu to be displayed;
3296 * if you return false it will not be shown.
3298 * @see #onPrepareOptionsMenu
3299 * @see #onOptionsItemSelected
3301 public boolean onCreateOptionsMenu(Menu menu) {
3302 if (mParent != null) {
3303 return mParent.onCreateOptionsMenu(menu);
3309 * Prepare the Screen's standard options menu to be displayed. This is
3310 * called right before the menu is shown, every time it is shown. You can
3311 * use this method to efficiently enable/disable items or otherwise
3312 * dynamically modify the contents.
3314 * <p>The default implementation updates the system menu items based on the
3315 * activity's state. Deriving classes should always call through to the
3316 * base class implementation.
3318 * @param menu The options menu as last shown or first initialized by
3319 * onCreateOptionsMenu().
3321 * @return You must return true for the menu to be displayed;
3322 * if you return false it will not be shown.
3324 * @see #onCreateOptionsMenu
3326 public boolean onPrepareOptionsMenu(Menu menu) {
3327 if (mParent != null) {
3328 return mParent.onPrepareOptionsMenu(menu);
3334 * This hook is called whenever an item in your options menu is selected.
3335 * The default implementation simply returns false to have the normal
3336 * processing happen (calling the item's Runnable or sending a message to
3337 * its Handler as appropriate). You can use this method for any items
3338 * for which you would like to do processing without those other
3341 * <p>Derived classes should call through to the base class for it to
3342 * perform the default menu handling.</p>
3344 * @param item The menu item that was selected.
3346 * @return boolean Return false to allow normal menu processing to
3347 * proceed, true to consume it here.
3349 * @see #onCreateOptionsMenu
3351 public boolean onOptionsItemSelected(MenuItem item) {
3352 if (mParent != null) {
3353 return mParent.onOptionsItemSelected(item);
3359 * This method is called whenever the user chooses to navigate Up within your application's
3360 * activity hierarchy from the action bar.
3362 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3363 * was specified in the manifest for this activity or an activity-alias to it,
3364 * default Up navigation will be handled automatically. If any activity
3365 * along the parent chain requires extra Intent arguments, the Activity subclass
3366 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3367 * to supply those arguments.</p>
3369 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
3370 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3371 * from the design guide for more information about navigating within your app.</p>
3373 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3374 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3375 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3376 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3378 * @return true if Up navigation completed successfully and this Activity was finished,
3381 public boolean onNavigateUp() {
3382 // Automatically handle hierarchical Up navigation if the proper
3383 // metadata is available.
3384 Intent upIntent = getParentActivityIntent();
3385 if (upIntent != null) {
3386 if (mActivityInfo.taskAffinity == null) {
3387 // Activities with a null affinity are special; they really shouldn't
3388 // specify a parent activity intent in the first place. Just finish
3389 // the current activity and call it a day.
3391 } else if (shouldUpRecreateTask(upIntent)) {
3392 TaskStackBuilder b = TaskStackBuilder.create(this);
3393 onCreateNavigateUpTaskStack(b);
3394 onPrepareNavigateUpTaskStack(b);
3395 b.startActivities();
3397 // We can't finishAffinity if we have a result.
3398 // Fall back and simply finish the current activity instead.
3399 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3400 // Tell the developer what's going on to avoid hair-pulling.
3401 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3407 navigateUpTo(upIntent);
3415 * This is called when a child activity of this one attempts to navigate up.
3416 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3418 * @param child The activity making the call.
3420 public boolean onNavigateUpFromChild(Activity child) {
3421 return onNavigateUp();
3425 * Define the synthetic task stack that will be generated during Up navigation from
3428 * <p>The default implementation of this method adds the parent chain of this activity
3429 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3430 * may choose to override this method to construct the desired task stack in a different
3433 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3434 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3435 * returned by {@link #getParentActivityIntent()}.</p>
3437 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3438 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3440 * @param builder An empty TaskStackBuilder - the application should add intents representing
3441 * the desired task stack
3443 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3444 builder.addParentStack(this);
3448 * Prepare the synthetic task stack that will be generated during Up navigation
3449 * from a different task.
3451 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3452 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3453 * If any extra data should be added to these intents before launching the new task,
3454 * the application should override this method and add that data here.</p>
3456 * @param builder A TaskStackBuilder that has been populated with Intents by
3457 * onCreateNavigateUpTaskStack.
3459 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3463 * This hook is called whenever the options menu is being closed (either by the user canceling
3464 * the menu with the back/menu button, or when an item is selected).
3466 * @param menu The options menu as last shown or first initialized by
3467 * onCreateOptionsMenu().
3469 public void onOptionsMenuClosed(Menu menu) {
3470 if (mParent != null) {
3471 mParent.onOptionsMenuClosed(menu);
3476 * Programmatically opens the options menu. If the options menu is already
3477 * open, this method does nothing.
3479 public void openOptionsMenu() {
3480 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3481 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3482 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3487 * Progammatically closes the options menu. If the options menu is already
3488 * closed, this method does nothing.
3490 public void closeOptionsMenu() {
3491 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL)) {
3492 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3497 * Called when a context menu for the {@code view} is about to be shown.
3498 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3499 * time the context menu is about to be shown and should be populated for
3500 * the view (or item inside the view for {@link AdapterView} subclasses,
3501 * this can be found in the {@code menuInfo})).
3503 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3504 * item has been selected.
3506 * It is not safe to hold onto the context menu after this method returns.
3509 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3513 * Registers a context menu to be shown for the given view (multiple views
3514 * can show the context menu). This method will set the
3515 * {@link OnCreateContextMenuListener} on the view to this activity, so
3516 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3517 * called when it is time to show the context menu.
3519 * @see #unregisterForContextMenu(View)
3520 * @param view The view that should show a context menu.
3522 public void registerForContextMenu(View view) {
3523 view.setOnCreateContextMenuListener(this);
3527 * Prevents a context menu to be shown for the given view. This method will remove the
3528 * {@link OnCreateContextMenuListener} on the view.
3530 * @see #registerForContextMenu(View)
3531 * @param view The view that should stop showing a context menu.
3533 public void unregisterForContextMenu(View view) {
3534 view.setOnCreateContextMenuListener(null);
3538 * Programmatically opens the context menu for a particular {@code view}.
3539 * The {@code view} should have been added via
3540 * {@link #registerForContextMenu(View)}.
3542 * @param view The view to show the context menu for.
3544 public void openContextMenu(View view) {
3545 view.showContextMenu();
3549 * Programmatically closes the most recently opened context menu, if showing.
3551 public void closeContextMenu() {
3552 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3553 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3558 * This hook is called whenever an item in a context menu is selected. The
3559 * default implementation simply returns false to have the normal processing
3560 * happen (calling the item's Runnable or sending a message to its Handler
3561 * as appropriate). You can use this method for any items for which you
3562 * would like to do processing without those other facilities.
3564 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3565 * View that added this menu item.
3567 * Derived classes should call through to the base class for it to perform
3568 * the default menu handling.
3570 * @param item The context menu item that was selected.
3571 * @return boolean Return false to allow normal context menu processing to
3572 * proceed, true to consume it here.
3574 public boolean onContextItemSelected(MenuItem item) {
3575 if (mParent != null) {
3576 return mParent.onContextItemSelected(item);
3582 * This hook is called whenever the context menu is being closed (either by
3583 * the user canceling the menu with the back/menu button, or when an item is
3586 * @param menu The context menu that is being closed.
3588 public void onContextMenuClosed(Menu menu) {
3589 if (mParent != null) {
3590 mParent.onContextMenuClosed(menu);
3595 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3598 protected Dialog onCreateDialog(int id) {
3603 * Callback for creating dialogs that are managed (saved and restored) for you
3604 * by the activity. The default implementation calls through to
3605 * {@link #onCreateDialog(int)} for compatibility.
3607 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3608 * or later, consider instead using a {@link DialogFragment} instead.</em>
3610 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3611 * this method the first time, and hang onto it thereafter. Any dialog
3612 * that is created by this method will automatically be saved and restored
3613 * for you, including whether it is showing.
3615 * <p>If you would like the activity to manage saving and restoring dialogs
3616 * for you, you should override this method and handle any ids that are
3617 * passed to {@link #showDialog}.
3619 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3620 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3622 * @param id The id of the dialog.
3623 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3624 * @return The dialog. If you return null, the dialog will not be created.
3626 * @see #onPrepareDialog(int, Dialog, Bundle)
3627 * @see #showDialog(int, Bundle)
3628 * @see #dismissDialog(int)
3629 * @see #removeDialog(int)
3631 * @deprecated Use the new {@link DialogFragment} class with
3632 * {@link FragmentManager} instead; this is also
3633 * available on older platforms through the Android compatibility package.
3637 protected Dialog onCreateDialog(int id, Bundle args) {
3638 return onCreateDialog(id);
3642 * @deprecated Old no-arguments version of
3643 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3646 protected void onPrepareDialog(int id, Dialog dialog) {
3647 dialog.setOwnerActivity(this);
3651 * Provides an opportunity to prepare a managed dialog before it is being
3652 * shown. The default implementation calls through to
3653 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3656 * Override this if you need to update a managed dialog based on the state
3657 * of the application each time it is shown. For example, a time picker
3658 * dialog might want to be updated with the current time. You should call
3659 * through to the superclass's implementation. The default implementation
3660 * will set this Activity as the owner activity on the Dialog.
3662 * @param id The id of the managed dialog.
3663 * @param dialog The dialog.
3664 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3665 * @see #onCreateDialog(int, Bundle)
3666 * @see #showDialog(int)
3667 * @see #dismissDialog(int)
3668 * @see #removeDialog(int)
3670 * @deprecated Use the new {@link DialogFragment} class with
3671 * {@link FragmentManager} instead; this is also
3672 * available on older platforms through the Android compatibility package.
3675 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3676 onPrepareDialog(id, dialog);
3680 * Simple version of {@link #showDialog(int, Bundle)} that does not
3681 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3682 * with null arguments.
3684 * @deprecated Use the new {@link DialogFragment} class with
3685 * {@link FragmentManager} instead; this is also
3686 * available on older platforms through the Android compatibility package.
3689 public final void showDialog(int id) {
3690 showDialog(id, null);
3694 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3695 * will be made with the same id the first time this is called for a given
3696 * id. From thereafter, the dialog will be automatically saved and restored.
3698 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3699 * or later, consider instead using a {@link DialogFragment} instead.</em>
3701 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3702 * be made to provide an opportunity to do any timely preparation.
3704 * @param id The id of the managed dialog.
3705 * @param args Arguments to pass through to the dialog. These will be saved
3706 * and restored for you. Note that if the dialog is already created,
3707 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3708 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3709 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3710 * @return Returns true if the Dialog was created; false is returned if
3711 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3714 * @see #onCreateDialog(int, Bundle)
3715 * @see #onPrepareDialog(int, Dialog, Bundle)
3716 * @see #dismissDialog(int)
3717 * @see #removeDialog(int)
3719 * @deprecated Use the new {@link DialogFragment} class with
3720 * {@link FragmentManager} instead; this is also
3721 * available on older platforms through the Android compatibility package.
3725 public final boolean showDialog(int id, Bundle args) {
3726 if (mManagedDialogs == null) {
3727 mManagedDialogs = new SparseArray<ManagedDialog>();
3729 ManagedDialog md = mManagedDialogs.get(id);
3731 md = new ManagedDialog();
3732 md.mDialog = createDialog(id, null, args);
3733 if (md.mDialog == null) {
3736 mManagedDialogs.put(id, md);
3740 onPrepareDialog(id, md.mDialog, args);
3746 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3748 * @param id The id of the managed dialog.
3750 * @throws IllegalArgumentException if the id was not previously shown via
3751 * {@link #showDialog(int)}.
3753 * @see #onCreateDialog(int, Bundle)
3754 * @see #onPrepareDialog(int, Dialog, Bundle)
3755 * @see #showDialog(int)
3756 * @see #removeDialog(int)
3758 * @deprecated Use the new {@link DialogFragment} class with
3759 * {@link FragmentManager} instead; this is also
3760 * available on older platforms through the Android compatibility package.
3763 public final void dismissDialog(int id) {
3764 if (mManagedDialogs == null) {
3765 throw missingDialog(id);
3768 final ManagedDialog md = mManagedDialogs.get(id);
3770 throw missingDialog(id);
3772 md.mDialog.dismiss();
3776 * Creates an exception to throw if a user passed in a dialog id that is
3779 private IllegalArgumentException missingDialog(int id) {
3780 return new IllegalArgumentException("no dialog with id " + id + " was ever "
3781 + "shown via Activity#showDialog");
3785 * Removes any internal references to a dialog managed by this Activity.
3786 * If the dialog is showing, it will dismiss it as part of the clean up.
3788 * <p>This can be useful if you know that you will never show a dialog again and
3789 * want to avoid the overhead of saving and restoring it in the future.
3791 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
3792 * will not throw an exception if you try to remove an ID that does not
3793 * currently have an associated dialog.</p>
3795 * @param id The id of the managed dialog.
3797 * @see #onCreateDialog(int, Bundle)
3798 * @see #onPrepareDialog(int, Dialog, Bundle)
3799 * @see #showDialog(int)
3800 * @see #dismissDialog(int)
3802 * @deprecated Use the new {@link DialogFragment} class with
3803 * {@link FragmentManager} instead; this is also
3804 * available on older platforms through the Android compatibility package.
3807 public final void removeDialog(int id) {
3808 if (mManagedDialogs != null) {
3809 final ManagedDialog md = mManagedDialogs.get(id);
3811 md.mDialog.dismiss();
3812 mManagedDialogs.remove(id);
3818 * This hook is called when the user signals the desire to start a search.
3820 * <p>You can use this function as a simple way to launch the search UI, in response to a
3821 * menu item, search button, or other widgets within your activity. Unless overidden,
3822 * calling this function is the same as calling
3823 * {@link #startSearch startSearch(null, false, null, false)}, which launches
3824 * search for the current activity as specified in its manifest, see {@link SearchManager}.
3826 * <p>You can override this function to force global search, e.g. in response to a dedicated
3827 * search key, or to block search entirely (by simply returning false).
3829 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
3830 * implementation changes to simply return false and you must supply your own custom
3831 * implementation if you want to support search.</p>
3833 * @param searchEvent The {@link SearchEvent} that signaled this search.
3834 * @return Returns {@code true} if search launched, and {@code false} if the activity does
3835 * not respond to search. The default implementation always returns {@code true}, except
3836 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
3838 * @see android.app.SearchManager
3840 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
3841 mSearchEvent = searchEvent;
3842 boolean result = onSearchRequested();
3843 mSearchEvent = null;
3848 * @see #onSearchRequested(SearchEvent)
3850 public boolean onSearchRequested() {
3851 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
3852 != Configuration.UI_MODE_TYPE_TELEVISION) {
3853 startSearch(null, false, null, false);
3861 * During the onSearchRequested() callbacks, this function will return the
3862 * {@link SearchEvent} that triggered the callback, if it exists.
3864 * @return SearchEvent The SearchEvent that triggered the {@link
3865 * #onSearchRequested} callback.
3867 public final SearchEvent getSearchEvent() {
3868 return mSearchEvent;
3872 * This hook is called to launch the search UI.
3874 * <p>It is typically called from onSearchRequested(), either directly from
3875 * Activity.onSearchRequested() or from an overridden version in any given
3876 * Activity. If your goal is simply to activate search, it is preferred to call
3877 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
3878 * is to inject specific data such as context data, it is preferred to <i>override</i>
3879 * onSearchRequested(), so that any callers to it will benefit from the override.
3881 * @param initialQuery Any non-null non-empty string will be inserted as
3882 * pre-entered text in the search query box.
3883 * @param selectInitialQuery If true, the initial query will be preselected, which means that
3884 * any further typing will replace it. This is useful for cases where an entire pre-formed
3885 * query is being inserted. If false, the selection point will be placed at the end of the
3886 * inserted query. This is useful when the inserted query is text that the user entered,
3887 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
3888 * if initialQuery is a non-empty string.</i>
3889 * @param appSearchData An application can insert application-specific
3890 * context here, in order to improve quality or specificity of its own
3891 * searches. This data will be returned with SEARCH intent(s). Null if
3892 * no extra data is required.
3893 * @param globalSearch If false, this will only launch the search that has been specifically
3894 * defined by the application (which is usually defined as a local search). If no default
3895 * search is defined in the current application or activity, global search will be launched.
3896 * If true, this will always launch a platform-global (e.g. web-based) search instead.
3898 * @see android.app.SearchManager
3899 * @see #onSearchRequested
3901 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
3902 @Nullable Bundle appSearchData, boolean globalSearch) {
3903 ensureSearchManager();
3904 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
3905 appSearchData, globalSearch);
3909 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
3910 * the search dialog. Made available for testing purposes.
3912 * @param query The query to trigger. If empty, the request will be ignored.
3913 * @param appSearchData An application can insert application-specific
3914 * context here, in order to improve quality or specificity of its own
3915 * searches. This data will be returned with SEARCH intent(s). Null if
3916 * no extra data is required.
3918 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
3919 ensureSearchManager();
3920 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
3924 * Request that key events come to this activity. Use this if your
3925 * activity has no views with focus, but the activity still wants
3926 * a chance to process key events.
3928 * @see android.view.Window#takeKeyEvents
3930 public void takeKeyEvents(boolean get) {
3931 getWindow().takeKeyEvents(get);
3935 * Enable extended window features. This is a convenience for calling
3936 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
3938 * @param featureId The desired feature as defined in
3939 * {@link android.view.Window}.
3940 * @return Returns true if the requested feature is supported and now
3943 * @see android.view.Window#requestFeature
3945 public final boolean requestWindowFeature(int featureId) {
3946 return getWindow().requestFeature(featureId);
3950 * Convenience for calling
3951 * {@link android.view.Window#setFeatureDrawableResource}.
3953 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
3954 getWindow().setFeatureDrawableResource(featureId, resId);
3958 * Convenience for calling
3959 * {@link android.view.Window#setFeatureDrawableUri}.
3961 public final void setFeatureDrawableUri(int featureId, Uri uri) {
3962 getWindow().setFeatureDrawableUri(featureId, uri);
3966 * Convenience for calling
3967 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
3969 public final void setFeatureDrawable(int featureId, Drawable drawable) {
3970 getWindow().setFeatureDrawable(featureId, drawable);
3974 * Convenience for calling
3975 * {@link android.view.Window#setFeatureDrawableAlpha}.
3977 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
3978 getWindow().setFeatureDrawableAlpha(featureId, alpha);
3982 * Convenience for calling
3983 * {@link android.view.Window#getLayoutInflater}.
3986 public LayoutInflater getLayoutInflater() {
3987 return getWindow().getLayoutInflater();
3991 * Returns a {@link MenuInflater} with this context.
3994 public MenuInflater getMenuInflater() {
3995 // Make sure that action views can get an appropriate theme.
3996 if (mMenuInflater == null) {
3997 initWindowDecorActionBar();
3998 if (mActionBar != null) {
3999 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
4001 mMenuInflater = new MenuInflater(this);
4004 return mMenuInflater;
4008 public void setTheme(int resid) {
4009 super.setTheme(resid);
4010 mWindow.setTheme(resid);
4014 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
4016 if (mParent == null) {
4017 super.onApplyThemeResource(theme, resid, first);
4020 theme.setTo(mParent.getTheme());
4021 } catch (Exception e) {
4024 theme.applyStyle(resid, false);
4027 // Get the primary color and update the TaskDescription for this activity
4028 TypedArray a = theme.obtainStyledAttributes(
4029 com.android.internal.R.styleable.ActivityTaskDescription);
4030 if (mTaskDescription.getPrimaryColor() == 0) {
4031 int colorPrimary = a.getColor(
4032 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
4033 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
4034 mTaskDescription.setPrimaryColor(colorPrimary);
4037 // For dev-preview only.
4038 if (mTaskDescription.getBackgroundColor() == 0) {
4039 int colorBackground = a.getColor(
4040 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
4041 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
4042 mTaskDescription.setBackgroundColor(colorBackground);
4046 setTaskDescription(mTaskDescription);
4050 * Requests permissions to be granted to this application. These permissions
4051 * must be requested in your manifest, they should not be granted to your app,
4052 * and they should have protection level {@link android.content.pm.PermissionInfo
4053 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
4054 * the platform or a third-party app.
4056 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
4057 * are granted at install time if requested in the manifest. Signature permissions
4058 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
4059 * install time if requested in the manifest and the signature of your app matches
4060 * the signature of the app declaring the permissions.
4063 * If your app does not have the requested permissions the user will be presented
4064 * with UI for accepting them. After the user has accepted or rejected the
4065 * requested permissions you will receive a callback on {@link
4066 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
4067 * permissions were granted or not.
4070 * Note that requesting a permission does not guarantee it will be granted and
4071 * your app should be able to run without having this permission.
4074 * This method may start an activity allowing the user to choose which permissions
4075 * to grant and which to reject. Hence, you should be prepared that your activity
4076 * may be paused and resumed. Further, granting some permissions may require
4077 * a restart of you application. In such a case, the system will recreate the
4078 * activity stack before delivering the result to {@link
4079 * #onRequestPermissionsResult(int, String[], int[])}.
4082 * When checking whether you have a permission you should use {@link
4083 * #checkSelfPermission(String)}.
4086 * Calling this API for permissions already granted to your app would show UI
4087 * to the user to decide whether the app can still hold these permissions. This
4088 * can be useful if the way your app uses data guarded by the permissions
4089 * changes significantly.
4092 * You cannot request a permission if your activity sets {@link
4093 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
4094 * <code>true</code> because in this case the activity would not receive
4095 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
4098 * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html">
4099 * RuntimePermissions</a> sample app demonstrates how to use this method to
4100 * request permissions at run time.
4103 * @param permissions The requested permissions. Must me non-null and not empty.
4104 * @param requestCode Application specific request code to match with a result
4105 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
4108 * @see #onRequestPermissionsResult(int, String[], int[])
4109 * @see #checkSelfPermission(String)
4110 * @see #shouldShowRequestPermissionRationale(String)
4112 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
4113 if (mHasCurrentPermissionsRequest) {
4114 Log.w(TAG, "Can reqeust only one set of permissions at a time");
4115 // Dispatch the callback with empty arrays which means a cancellation.
4116 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
4119 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
4120 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
4121 mHasCurrentPermissionsRequest = true;
4125 * Callback for the result from requesting permissions. This method
4126 * is invoked for every call on {@link #requestPermissions(String[], int)}.
4128 * <strong>Note:</strong> It is possible that the permissions request interaction
4129 * with the user is interrupted. In this case you will receive empty permissions
4130 * and results arrays which should be treated as a cancellation.
4133 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
4134 * @param permissions The requested permissions. Never null.
4135 * @param grantResults The grant results for the corresponding permissions
4136 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
4137 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
4139 * @see #requestPermissions(String[], int)
4141 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
4142 @NonNull int[] grantResults) {
4143 /* callback - no nothing */
4147 * Gets whether you should show UI with rationale for requesting a permission.
4148 * You should do this only if you do not have the permission and the context in
4149 * which the permission is requested does not clearly communicate to the user
4150 * what would be the benefit from granting this permission.
4152 * For example, if you write a camera app, requesting the camera permission
4153 * would be expected by the user and no rationale for why it is requested is
4154 * needed. If however, the app needs location for tagging photos then a non-tech
4155 * savvy user may wonder how location is related to taking photos. In this case
4156 * you may choose to show UI with rationale of requesting this permission.
4159 * @param permission A permission your app wants to request.
4160 * @return Whether you can show permission rationale UI.
4162 * @see #checkSelfPermission(String)
4163 * @see #requestPermissions(String[], int)
4164 * @see #onRequestPermissionsResult(int, String[], int[])
4166 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
4167 return getPackageManager().shouldShowRequestPermissionRationale(permission);
4171 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
4174 * @param intent The intent to start.
4175 * @param requestCode If >= 0, this code will be returned in
4176 * onActivityResult() when the activity exits.
4178 * @throws android.content.ActivityNotFoundException
4180 * @see #startActivity
4182 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
4183 startActivityForResult(intent, requestCode, null);
4187 * Launch an activity for which you would like a result when it finished.
4188 * When this activity exits, your
4189 * onActivityResult() method will be called with the given requestCode.
4190 * Using a negative requestCode is the same as calling
4191 * {@link #startActivity} (the activity is not launched as a sub-activity).
4193 * <p>Note that this method should only be used with Intent protocols
4194 * that are defined to return a result. In other protocols (such as
4195 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
4196 * not get the result when you expect. For example, if the activity you
4197 * are launching uses the singleTask launch mode, it will not run in your
4198 * task and thus you will immediately receive a cancel result.
4200 * <p>As a special case, if you call startActivityForResult() with a requestCode
4201 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
4202 * activity, then your window will not be displayed until a result is
4203 * returned back from the started activity. This is to avoid visible
4204 * flickering when redirecting to another activity.
4206 * <p>This method throws {@link android.content.ActivityNotFoundException}
4207 * if there was no Activity found to run the given Intent.
4209 * @param intent The intent to start.
4210 * @param requestCode If >= 0, this code will be returned in
4211 * onActivityResult() when the activity exits.
4212 * @param options Additional options for how the Activity should be started.
4213 * See {@link android.content.Context#startActivity(Intent, Bundle)
4214 * Context.startActivity(Intent, Bundle)} for more details.
4216 * @throws android.content.ActivityNotFoundException
4218 * @see #startActivity
4220 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
4221 @Nullable Bundle options) {
4222 if (mParent == null) {
4223 Instrumentation.ActivityResult ar =
4224 mInstrumentation.execStartActivity(
4225 this, mMainThread.getApplicationThread(), mToken, this,
4226 intent, requestCode, options);
4228 mMainThread.sendActivityResult(
4229 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4230 ar.getResultData());
4232 if (requestCode >= 0) {
4233 // If this start is requesting a result, we can avoid making
4234 // the activity visible until the result is received. Setting
4235 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4236 // activity hidden during this time, to avoid flickering.
4237 // This can only be done when a result is requested because
4238 // that guarantees we will get information back when the
4239 // activity is finished, no matter what happens to it.
4240 mStartedActivity = true;
4243 cancelInputsAndStartExitTransition(options);
4244 // TODO Consider clearing/flushing other event sources and events for child windows.
4246 if (options != null) {
4247 mParent.startActivityFromChild(this, intent, requestCode, options);
4249 // Note we want to go through this method for compatibility with
4250 // existing applications that may have overridden it.
4251 mParent.startActivityFromChild(this, intent, requestCode);
4257 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
4259 * @param options The ActivityOptions bundle used to start an Activity.
4261 private void cancelInputsAndStartExitTransition(Bundle options) {
4262 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
4263 if (decor != null) {
4264 decor.cancelPendingInputEvents();
4266 if (options != null && !isTopOfTask()) {
4267 mActivityTransitionState.startExitOutTransition(this, options);
4272 * @hide Implement to provide correct calling token.
4274 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
4275 startActivityForResultAsUser(intent, requestCode, null, user);
4279 * @hide Implement to provide correct calling token.
4281 public void startActivityForResultAsUser(Intent intent, int requestCode,
4282 @Nullable Bundle options, UserHandle user) {
4283 if (mParent != null) {
4284 throw new RuntimeException("Can't be called from a child");
4286 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4287 this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode,
4290 mMainThread.sendActivityResult(
4291 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4293 if (requestCode >= 0) {
4294 // If this start is requesting a result, we can avoid making
4295 // the activity visible until the result is received. Setting
4296 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4297 // activity hidden during this time, to avoid flickering.
4298 // This can only be done when a result is requested because
4299 // that guarantees we will get information back when the
4300 // activity is finished, no matter what happens to it.
4301 mStartedActivity = true;
4304 cancelInputsAndStartExitTransition(options);
4308 * @hide Implement to provide correct calling token.
4310 public void startActivityAsUser(Intent intent, UserHandle user) {
4311 startActivityAsUser(intent, null, user);
4315 * @hide Implement to provide correct calling token.
4317 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4318 if (mParent != null) {
4319 throw new RuntimeException("Can't be called from a child");
4321 Instrumentation.ActivityResult ar =
4322 mInstrumentation.execStartActivity(
4323 this, mMainThread.getApplicationThread(), mToken, this,
4324 intent, -1, options, user);
4326 mMainThread.sendActivityResult(
4327 mToken, mEmbeddedID, -1, ar.getResultCode(),
4328 ar.getResultData());
4330 cancelInputsAndStartExitTransition(options);
4334 * Start a new activity as if it was started by the activity that started our
4335 * current activity. This is for the resolver and chooser activities, which operate
4336 * as intermediaries that dispatch their intent to the target the user selects -- to
4337 * do this, they must perform all security checks including permission grants as if
4338 * their launch had come from the original activity.
4339 * @param intent The Intent to start.
4340 * @param options ActivityOptions or null.
4341 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4342 * caller it is doing the start is, is actually allowed to start the target activity.
4343 * If you set this to true, you must set an explicit component in the Intent and do any
4344 * appropriate security checks yourself.
4345 * @param userId The user the new activity should run as.
4348 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4349 boolean ignoreTargetSecurity, int userId) {
4350 if (mParent != null) {
4351 throw new RuntimeException("Can't be called from a child");
4353 Instrumentation.ActivityResult ar =
4354 mInstrumentation.execStartActivityAsCaller(
4355 this, mMainThread.getApplicationThread(), mToken, this,
4356 intent, -1, options, ignoreTargetSecurity, userId);
4358 mMainThread.sendActivityResult(
4359 mToken, mEmbeddedID, -1, ar.getResultCode(),
4360 ar.getResultData());
4362 cancelInputsAndStartExitTransition(options);
4366 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4367 * Intent, int, int, int, Bundle)} with no options.
4369 * @param intent The IntentSender to launch.
4370 * @param requestCode If >= 0, this code will be returned in
4371 * onActivityResult() when the activity exits.
4372 * @param fillInIntent If non-null, this will be provided as the
4373 * intent parameter to {@link IntentSender#sendIntent}.
4374 * @param flagsMask Intent flags in the original IntentSender that you
4375 * would like to change.
4376 * @param flagsValues Desired values for any bits set in
4377 * <var>flagsMask</var>
4378 * @param extraFlags Always set to 0.
4380 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4381 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4382 throws IntentSender.SendIntentException {
4383 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4384 flagsValues, extraFlags, null);
4388 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4389 * to use a IntentSender to describe the activity to be started. If
4390 * the IntentSender is for an activity, that activity will be started
4391 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4392 * here; otherwise, its associated action will be executed (such as
4393 * sending a broadcast) as if you had called
4394 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4396 * @param intent The IntentSender to launch.
4397 * @param requestCode If >= 0, this code will be returned in
4398 * onActivityResult() when the activity exits.
4399 * @param fillInIntent If non-null, this will be provided as the
4400 * intent parameter to {@link IntentSender#sendIntent}.
4401 * @param flagsMask Intent flags in the original IntentSender that you
4402 * would like to change.
4403 * @param flagsValues Desired values for any bits set in
4404 * <var>flagsMask</var>
4405 * @param extraFlags Always set to 0.
4406 * @param options Additional options for how the Activity should be started.
4407 * See {@link android.content.Context#startActivity(Intent, Bundle)
4408 * Context.startActivity(Intent, Bundle)} for more details. If options
4409 * have also been supplied by the IntentSender, options given here will
4410 * override any that conflict with those given by the IntentSender.
4412 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4413 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4414 Bundle options) throws IntentSender.SendIntentException {
4415 if (mParent == null) {
4416 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
4417 flagsMask, flagsValues, options);
4418 } else if (options != null) {
4419 mParent.startIntentSenderFromChild(this, intent, requestCode,
4420 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4422 // Note we want to go through this call for compatibility with
4423 // existing applications that may have overridden the method.
4424 mParent.startIntentSenderFromChild(this, intent, requestCode,
4425 fillInIntent, flagsMask, flagsValues, extraFlags);
4429 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
4430 Intent fillInIntent, int flagsMask, int flagsValues,
4432 throws IntentSender.SendIntentException {
4434 String resolvedType = null;
4435 if (fillInIntent != null) {
4436 fillInIntent.migrateExtraStreamToClipData();
4437 fillInIntent.prepareToLeaveProcess(this);
4438 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4440 int result = ActivityManagerNative.getDefault()
4441 .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
4442 fillInIntent, resolvedType, mToken, who,
4443 requestCode, flagsMask, flagsValues, options);
4444 if (result == ActivityManager.START_CANCELED) {
4445 throw new IntentSender.SendIntentException();
4447 Instrumentation.checkStartActivityResult(result, null);
4448 } catch (RemoteException e) {
4450 if (requestCode >= 0) {
4451 // If this start is requesting a result, we can avoid making
4452 // the activity visible until the result is received. Setting
4453 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4454 // activity hidden during this time, to avoid flickering.
4455 // This can only be done when a result is requested because
4456 // that guarantees we will get information back when the
4457 // activity is finished, no matter what happens to it.
4458 mStartedActivity = true;
4463 * Same as {@link #startActivity(Intent, Bundle)} with no options
4466 * @param intent The intent to start.
4468 * @throws android.content.ActivityNotFoundException
4470 * @see #startActivity(Intent, Bundle)
4471 * @see #startActivityForResult
4474 public void startActivity(Intent intent) {
4475 this.startActivity(intent, null);
4479 * Launch a new activity. You will not receive any information about when
4480 * the activity exits. This implementation overrides the base version,
4481 * providing information about
4482 * the activity performing the launch. Because of this additional
4483 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4484 * required; if not specified, the new activity will be added to the
4485 * task of the caller.
4487 * <p>This method throws {@link android.content.ActivityNotFoundException}
4488 * if there was no Activity found to run the given Intent.
4490 * @param intent The intent to start.
4491 * @param options Additional options for how the Activity should be started.
4492 * See {@link android.content.Context#startActivity(Intent, Bundle)
4493 * Context.startActivity(Intent, Bundle)} for more details.
4495 * @throws android.content.ActivityNotFoundException
4497 * @see #startActivity(Intent)
4498 * @see #startActivityForResult
4501 public void startActivity(Intent intent, @Nullable Bundle options) {
4502 if (options != null) {
4503 startActivityForResult(intent, -1, options);
4505 // Note we want to go through this call for compatibility with
4506 // applications that may have overridden the method.
4507 startActivityForResult(intent, -1);
4512 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4515 * @param intents The intents to start.
4517 * @throws android.content.ActivityNotFoundException
4519 * @see #startActivities(Intent[], Bundle)
4520 * @see #startActivityForResult
4523 public void startActivities(Intent[] intents) {
4524 startActivities(intents, null);
4528 * Launch a new activity. You will not receive any information about when
4529 * the activity exits. This implementation overrides the base version,
4530 * providing information about
4531 * the activity performing the launch. Because of this additional
4532 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4533 * required; if not specified, the new activity will be added to the
4534 * task of the caller.
4536 * <p>This method throws {@link android.content.ActivityNotFoundException}
4537 * if there was no Activity found to run the given Intent.
4539 * @param intents The intents to start.
4540 * @param options Additional options for how the Activity should be started.
4541 * See {@link android.content.Context#startActivity(Intent, Bundle)
4542 * Context.startActivity(Intent, Bundle)} for more details.
4544 * @throws android.content.ActivityNotFoundException
4546 * @see #startActivities(Intent[])
4547 * @see #startActivityForResult
4550 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4551 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4552 mToken, this, intents, options);
4556 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4559 * @param intent The IntentSender to launch.
4560 * @param fillInIntent If non-null, this will be provided as the
4561 * intent parameter to {@link IntentSender#sendIntent}.
4562 * @param flagsMask Intent flags in the original IntentSender that you
4563 * would like to change.
4564 * @param flagsValues Desired values for any bits set in
4565 * <var>flagsMask</var>
4566 * @param extraFlags Always set to 0.
4568 public void startIntentSender(IntentSender intent,
4569 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4570 throws IntentSender.SendIntentException {
4571 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4576 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4578 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4579 * for more information.
4581 * @param intent The IntentSender to launch.
4582 * @param fillInIntent If non-null, this will be provided as the
4583 * intent parameter to {@link IntentSender#sendIntent}.
4584 * @param flagsMask Intent flags in the original IntentSender that you
4585 * would like to change.
4586 * @param flagsValues Desired values for any bits set in
4587 * <var>flagsMask</var>
4588 * @param extraFlags Always set to 0.
4589 * @param options Additional options for how the Activity should be started.
4590 * See {@link android.content.Context#startActivity(Intent, Bundle)
4591 * Context.startActivity(Intent, Bundle)} for more details. If options
4592 * have also been supplied by the IntentSender, options given here will
4593 * override any that conflict with those given by the IntentSender.
4595 public void startIntentSender(IntentSender intent,
4596 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4597 Bundle options) throws IntentSender.SendIntentException {
4598 if (options != null) {
4599 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4600 flagsValues, extraFlags, options);
4602 // Note we want to go through this call for compatibility with
4603 // applications that may have overridden the method.
4604 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4605 flagsValues, extraFlags);
4610 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4613 * @param intent The intent to start.
4614 * @param requestCode If >= 0, this code will be returned in
4615 * onActivityResult() when the activity exits, as described in
4616 * {@link #startActivityForResult}.
4618 * @return If a new activity was launched then true is returned; otherwise
4619 * false is returned and you must handle the Intent yourself.
4621 * @see #startActivity
4622 * @see #startActivityForResult
4624 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4626 return startActivityIfNeeded(intent, requestCode, null);
4630 * A special variation to launch an activity only if a new activity
4631 * instance is needed to handle the given Intent. In other words, this is
4632 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4633 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4634 * singleTask or singleTop
4635 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4637 * that handles <var>intent</var> is the same as your currently running
4638 * activity, then a new instance is not needed. In this case, instead of
4639 * the normal behavior of calling {@link #onNewIntent} this function will
4640 * return and you can handle the Intent yourself.
4642 * <p>This function can only be called from a top-level activity; if it is
4643 * called from a child activity, a runtime exception will be thrown.
4645 * @param intent The intent to start.
4646 * @param requestCode If >= 0, this code will be returned in
4647 * onActivityResult() when the activity exits, as described in
4648 * {@link #startActivityForResult}.
4649 * @param options Additional options for how the Activity should be started.
4650 * See {@link android.content.Context#startActivity(Intent, Bundle)
4651 * Context.startActivity(Intent, Bundle)} for more details.
4653 * @return If a new activity was launched then true is returned; otherwise
4654 * false is returned and you must handle the Intent yourself.
4656 * @see #startActivity
4657 * @see #startActivityForResult
4659 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4660 int requestCode, @Nullable Bundle options) {
4661 if (mParent == null) {
4662 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4664 Uri referrer = onProvideReferrer();
4665 if (referrer != null) {
4666 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4668 intent.migrateExtraStreamToClipData();
4669 intent.prepareToLeaveProcess(this);
4670 result = ActivityManagerNative.getDefault()
4671 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4672 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4673 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4675 } catch (RemoteException e) {
4679 Instrumentation.checkStartActivityResult(result, intent);
4681 if (requestCode >= 0) {
4682 // If this start is requesting a result, we can avoid making
4683 // the activity visible until the result is received. Setting
4684 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4685 // activity hidden during this time, to avoid flickering.
4686 // This can only be done when a result is requested because
4687 // that guarantees we will get information back when the
4688 // activity is finished, no matter what happens to it.
4689 mStartedActivity = true;
4691 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4694 throw new UnsupportedOperationException(
4695 "startActivityIfNeeded can only be called from a top-level activity");
4699 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4702 * @param intent The intent to dispatch to the next activity. For
4703 * correct behavior, this must be the same as the Intent that started
4704 * your own activity; the only changes you can make are to the extras
4707 * @return Returns a boolean indicating whether there was another Activity
4708 * to start: true if there was a next activity to start, false if there
4709 * wasn't. In general, if true is returned you will then want to call
4710 * finish() on yourself.
4712 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
4713 return startNextMatchingActivity(intent, null);
4717 * Special version of starting an activity, for use when you are replacing
4718 * other activity components. You can use this to hand the Intent off
4719 * to the next Activity that can handle it. You typically call this in
4720 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
4722 * @param intent The intent to dispatch to the next activity. For
4723 * correct behavior, this must be the same as the Intent that started
4724 * your own activity; the only changes you can make are to the extras
4726 * @param options Additional options for how the Activity should be started.
4727 * See {@link android.content.Context#startActivity(Intent, Bundle)
4728 * Context.startActivity(Intent, Bundle)} for more details.
4730 * @return Returns a boolean indicating whether there was another Activity
4731 * to start: true if there was a next activity to start, false if there
4732 * wasn't. In general, if true is returned you will then want to call
4733 * finish() on yourself.
4735 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
4736 @Nullable Bundle options) {
4737 if (mParent == null) {
4739 intent.migrateExtraStreamToClipData();
4740 intent.prepareToLeaveProcess(this);
4741 return ActivityManagerNative.getDefault()
4742 .startNextMatchingActivity(mToken, intent, options);
4743 } catch (RemoteException e) {
4749 throw new UnsupportedOperationException(
4750 "startNextMatchingActivity can only be called from a top-level activity");
4754 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
4757 * @param child The activity making the call.
4758 * @param intent The intent to start.
4759 * @param requestCode Reply request code. < 0 if reply is not requested.
4761 * @throws android.content.ActivityNotFoundException
4763 * @see #startActivity
4764 * @see #startActivityForResult
4766 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
4768 startActivityFromChild(child, intent, requestCode, null);
4772 * This is called when a child activity of this one calls its
4773 * {@link #startActivity} or {@link #startActivityForResult} method.
4775 * <p>This method throws {@link android.content.ActivityNotFoundException}
4776 * if there was no Activity found to run the given Intent.
4778 * @param child The activity making the call.
4779 * @param intent The intent to start.
4780 * @param requestCode Reply request code. < 0 if reply is not requested.
4781 * @param options Additional options for how the Activity should be started.
4782 * See {@link android.content.Context#startActivity(Intent, Bundle)
4783 * Context.startActivity(Intent, Bundle)} for more details.
4785 * @throws android.content.ActivityNotFoundException
4787 * @see #startActivity
4788 * @see #startActivityForResult
4790 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
4791 int requestCode, @Nullable Bundle options) {
4792 Instrumentation.ActivityResult ar =
4793 mInstrumentation.execStartActivity(
4794 this, mMainThread.getApplicationThread(), mToken, child,
4795 intent, requestCode, options);
4797 mMainThread.sendActivityResult(
4798 mToken, child.mEmbeddedID, requestCode,
4799 ar.getResultCode(), ar.getResultData());
4801 cancelInputsAndStartExitTransition(options);
4805 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
4808 * @param fragment The fragment making the call.
4809 * @param intent The intent to start.
4810 * @param requestCode Reply request code. < 0 if reply is not requested.
4812 * @throws android.content.ActivityNotFoundException
4814 * @see Fragment#startActivity
4815 * @see Fragment#startActivityForResult
4817 public void startActivityFromFragment(@NonNull Fragment fragment,
4818 @RequiresPermission Intent intent, int requestCode) {
4819 startActivityFromFragment(fragment, intent, requestCode, null);
4823 * This is called when a Fragment in this activity calls its
4824 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
4827 * <p>This method throws {@link android.content.ActivityNotFoundException}
4828 * if there was no Activity found to run the given Intent.
4830 * @param fragment The fragment making the call.
4831 * @param intent The intent to start.
4832 * @param requestCode Reply request code. < 0 if reply is not requested.
4833 * @param options Additional options for how the Activity should be started.
4834 * See {@link android.content.Context#startActivity(Intent, Bundle)
4835 * Context.startActivity(Intent, Bundle)} for more details.
4837 * @throws android.content.ActivityNotFoundException
4839 * @see Fragment#startActivity
4840 * @see Fragment#startActivityForResult
4842 public void startActivityFromFragment(@NonNull Fragment fragment,
4843 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
4844 startActivityForResult(fragment.mWho, intent, requestCode, options);
4851 public void startActivityForResult(
4852 String who, Intent intent, int requestCode, @Nullable Bundle options) {
4853 Uri referrer = onProvideReferrer();
4854 if (referrer != null) {
4855 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4857 Instrumentation.ActivityResult ar =
4858 mInstrumentation.execStartActivity(
4859 this, mMainThread.getApplicationThread(), mToken, who,
4860 intent, requestCode, options);
4862 mMainThread.sendActivityResult(
4863 mToken, who, requestCode,
4864 ar.getResultCode(), ar.getResultData());
4866 cancelInputsAndStartExitTransition(options);
4873 public boolean canStartActivityForResult() {
4878 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
4879 * int, Intent, int, int, int, Bundle)} with no options.
4881 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4882 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4884 throws IntentSender.SendIntentException {
4885 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
4886 flagsMask, flagsValues, extraFlags, null);
4890 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
4891 * taking a IntentSender; see
4892 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4893 * for more information.
4895 public void startIntentSenderFromChild(Activity child, IntentSender intent,
4896 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4897 int extraFlags, @Nullable Bundle options)
4898 throws IntentSender.SendIntentException {
4899 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
4900 flagsMask, flagsValues, options);
4904 * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see
4905 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
4906 * for more information.
4910 public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent,
4911 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
4912 int extraFlags, @Nullable Bundle options)
4913 throws IntentSender.SendIntentException {
4914 startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent,
4915 flagsMask, flagsValues, options);
4919 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
4920 * or {@link #finish} to specify an explicit transition animation to
4923 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
4924 * to using this with starting activities is to supply the desired animation
4925 * information through a {@link ActivityOptions} bundle to
4926 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
4927 * you to specify a custom animation even when starting an activity from
4928 * outside the context of the current top activity.
4930 * @param enterAnim A resource ID of the animation resource to use for
4931 * the incoming activity. Use 0 for no animation.
4932 * @param exitAnim A resource ID of the animation resource to use for
4933 * the outgoing activity. Use 0 for no animation.
4935 public void overridePendingTransition(int enterAnim, int exitAnim) {
4937 ActivityManagerNative.getDefault().overridePendingTransition(
4938 mToken, getPackageName(), enterAnim, exitAnim);
4939 } catch (RemoteException e) {
4944 * Call this to set the result that your activity will return to its
4947 * @param resultCode The result code to propagate back to the originating
4948 * activity, often RESULT_CANCELED or RESULT_OK
4950 * @see #RESULT_CANCELED
4952 * @see #RESULT_FIRST_USER
4953 * @see #setResult(int, Intent)
4955 public final void setResult(int resultCode) {
4956 synchronized (this) {
4957 mResultCode = resultCode;
4963 * Call this to set the result that your activity will return to its
4966 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
4967 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
4968 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4969 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
4970 * Activity receiving the result access to the specific URIs in the Intent.
4971 * Access will remain until the Activity has finished (it will remain across the hosting
4972 * process being killed and other temporary destruction) and will be added
4973 * to any existing set of URI permissions it already holds.
4975 * @param resultCode The result code to propagate back to the originating
4976 * activity, often RESULT_CANCELED or RESULT_OK
4977 * @param data The data to propagate back to the originating activity.
4979 * @see #RESULT_CANCELED
4981 * @see #RESULT_FIRST_USER
4982 * @see #setResult(int)
4984 public final void setResult(int resultCode, Intent data) {
4985 synchronized (this) {
4986 mResultCode = resultCode;
4992 * Return information about who launched this activity. If the launching Intent
4993 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
4994 * that will be returned as-is; otherwise, if known, an
4995 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
4996 * package name that started the Intent will be returned. This may return null if no
4997 * referrer can be identified -- it is neither explicitly specified, nor is it known which
4998 * application package was involved.
5000 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
5001 * return the referrer that submitted that new intent to the activity. Otherwise, it
5002 * always returns the referrer of the original Intent.</p>
5004 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
5005 * referrer information, applications can spoof it.</p>
5008 public Uri getReferrer() {
5009 Intent intent = getIntent();
5011 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
5012 if (referrer != null) {
5015 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
5016 if (referrerName != null) {
5017 return Uri.parse(referrerName);
5019 } catch (BadParcelableException e) {
5020 Log.w(TAG, "Cannot read referrer from intent;"
5021 + " intent extras contain unknown custom Parcelable objects");
5023 if (mReferrer != null) {
5024 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
5030 * Override to generate the desired referrer for the content currently being shown
5031 * by the app. The default implementation returns null, meaning the referrer will simply
5032 * be the android-app: of the package name of this activity. Return a non-null Uri to
5033 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
5035 public Uri onProvideReferrer() {
5040 * Return the name of the package that invoked this activity. This is who
5041 * the data in {@link #setResult setResult()} will be sent to. You can
5042 * use this information to validate that the recipient is allowed to
5045 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5046 * did not use the {@link #startActivityForResult}
5047 * form that includes a request code), then the calling package will be
5050 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
5051 * the result from this method was unstable. If the process hosting the calling
5052 * package was no longer running, it would return null instead of the proper package
5053 * name. You can use {@link #getCallingActivity()} and retrieve the package name
5054 * from that instead.</p>
5056 * @return The package of the activity that will receive your
5057 * reply, or null if none.
5060 public String getCallingPackage() {
5062 return ActivityManagerNative.getDefault().getCallingPackage(mToken);
5063 } catch (RemoteException e) {
5069 * Return the name of the activity that invoked this activity. This is
5070 * who the data in {@link #setResult setResult()} will be sent to. You
5071 * can use this information to validate that the recipient is allowed to
5074 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5075 * did not use the {@link #startActivityForResult}
5076 * form that includes a request code), then the calling package will be
5079 * @return The ComponentName of the activity that will receive your
5080 * reply, or null if none.
5083 public ComponentName getCallingActivity() {
5085 return ActivityManagerNative.getDefault().getCallingActivity(mToken);
5086 } catch (RemoteException e) {
5092 * Control whether this activity's main window is visible. This is intended
5093 * only for the special case of an activity that is not going to show a
5094 * UI itself, but can't just finish prior to onResume() because it needs
5095 * to wait for a service binding or such. Setting this to false allows
5096 * you to prevent your UI from being shown during that time.
5098 * <p>The default value for this is taken from the
5099 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
5101 public void setVisible(boolean visible) {
5102 if (mVisibleFromClient != visible) {
5103 mVisibleFromClient = visible;
5104 if (mVisibleFromServer) {
5105 if (visible) makeVisible();
5106 else mDecor.setVisibility(View.INVISIBLE);
5111 void makeVisible() {
5112 if (!mWindowAdded) {
5113 ViewManager wm = getWindowManager();
5114 wm.addView(mDecor, getWindow().getAttributes());
5115 mWindowAdded = true;
5117 mDecor.setVisibility(View.VISIBLE);
5121 * Check to see whether this activity is in the process of finishing,
5122 * either because you called {@link #finish} on it or someone else
5123 * has requested that it finished. This is often used in
5124 * {@link #onPause} to determine whether the activity is simply pausing or
5125 * completely finishing.
5127 * @return If the activity is finishing, returns true; else returns false.
5131 public boolean isFinishing() {
5136 * Returns true if the final {@link #onDestroy()} call has been made
5137 * on the Activity, so this instance is now dead.
5139 public boolean isDestroyed() {
5144 * Check to see whether this activity is in the process of being destroyed in order to be
5145 * recreated with a new configuration. This is often used in
5146 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
5147 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
5149 * @return If the activity is being torn down in order to be recreated with a new configuration,
5150 * returns true; else returns false.
5152 public boolean isChangingConfigurations() {
5153 return mChangingConfigurations;
5157 * Cause this Activity to be recreated with a new instance. This results
5158 * in essentially the same flow as when the Activity is created due to
5159 * a configuration change -- the current instance will go through its
5160 * lifecycle to {@link #onDestroy} and a new instance then created after it.
5162 public void recreate() {
5163 if (mParent != null) {
5164 throw new IllegalStateException("Can only be called on top-level activity");
5166 if (Looper.myLooper() != mMainThread.getLooper()) {
5167 throw new IllegalStateException("Must be called from main thread");
5169 mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, null, false,
5170 false /* preserveWindow */);
5174 * Finishes the current activity and specifies whether to remove the task associated with this
5177 private void finish(int finishTask) {
5178 if (mParent == null) {
5181 synchronized (this) {
5182 resultCode = mResultCode;
5183 resultData = mResultData;
5185 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
5187 if (resultData != null) {
5188 resultData.prepareToLeaveProcess(this);
5190 if (ActivityManagerNative.getDefault()
5191 .finishActivity(mToken, resultCode, resultData, finishTask)) {
5194 } catch (RemoteException e) {
5198 mParent.finishFromChild(this);
5203 * Call this when your activity is done and should be closed. The
5204 * ActivityResult is propagated back to whoever launched you via
5205 * onActivityResult().
5207 public void finish() {
5208 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
5212 * Finish this activity as well as all activities immediately below it
5213 * in the current task that have the same affinity. This is typically
5214 * used when an application can be launched on to another task (such as
5215 * from an ACTION_VIEW of a content type it understands) and the user
5216 * has used the up navigation to switch out of the current task and in
5217 * to its own task. In this case, if the user has navigated down into
5218 * any other activities of the second application, all of those should
5219 * be removed from the original task as part of the task switch.
5221 * <p>Note that this finish does <em>not</em> allow you to deliver results
5222 * to the previous activity, and an exception will be thrown if you are trying
5225 public void finishAffinity() {
5226 if (mParent != null) {
5227 throw new IllegalStateException("Can not be called from an embedded activity");
5229 if (mResultCode != RESULT_CANCELED || mResultData != null) {
5230 throw new IllegalStateException("Can not be called to deliver a result");
5233 if (ActivityManagerNative.getDefault().finishActivityAffinity(mToken)) {
5236 } catch (RemoteException e) {
5242 * This is called when a child activity of this one calls its
5243 * {@link #finish} method. The default implementation simply calls
5244 * finish() on this activity (the parent), finishing the entire group.
5246 * @param child The activity making the call.
5250 public void finishFromChild(Activity child) {
5255 * Reverses the Activity Scene entry Transition and triggers the calling Activity
5256 * to reverse its exit Transition. When the exit Transition completes,
5257 * {@link #finish()} is called. If no entry Transition was used, finish() is called
5258 * immediately and the Activity exit Transition is run.
5259 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
5261 public void finishAfterTransition() {
5262 if (!mActivityTransitionState.startExitBackTransition(this)) {
5268 * Force finish another activity that you had previously started with
5269 * {@link #startActivityForResult}.
5271 * @param requestCode The request code of the activity that you had
5272 * given to startActivityForResult(). If there are multiple
5273 * activities started with this request code, they
5274 * will all be finished.
5276 public void finishActivity(int requestCode) {
5277 if (mParent == null) {
5279 ActivityManagerNative.getDefault()
5280 .finishSubActivity(mToken, mEmbeddedID, requestCode);
5281 } catch (RemoteException e) {
5285 mParent.finishActivityFromChild(this, requestCode);
5290 * This is called when a child activity of this one calls its
5293 * @param child The activity making the call.
5294 * @param requestCode Request code that had been used to start the
5297 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
5299 ActivityManagerNative.getDefault()
5300 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
5301 } catch (RemoteException e) {
5307 * Call this when your activity is done and should be closed and the task should be completely
5308 * removed as a part of finishing the root activity of the task.
5310 public void finishAndRemoveTask() {
5311 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
5315 * Ask that the local app instance of this activity be released to free up its memory.
5316 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5317 * a new instance of the activity will later be re-created if needed due to the user
5318 * navigating back to it.
5320 * @return Returns true if the activity was in a state that it has started the process
5321 * of destroying its current instance; returns false if for any reason this could not
5322 * be done: it is currently visible to the user, it is already being destroyed, it is
5323 * being finished, it hasn't yet saved its state, etc.
5325 public boolean releaseInstance() {
5327 return ActivityManagerNative.getDefault().releaseActivityInstance(mToken);
5328 } catch (RemoteException e) {
5335 * Called when an activity you launched exits, giving you the requestCode
5336 * you started it with, the resultCode it returned, and any additional
5337 * data from it. The <var>resultCode</var> will be
5338 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5339 * didn't return any result, or crashed during its operation.
5341 * <p>You will receive this call immediately before onResume() when your
5342 * activity is re-starting.
5344 * <p>This method is never invoked if your activity sets
5345 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5346 * <code>true</code>.
5348 * @param requestCode The integer request code originally supplied to
5349 * startActivityForResult(), allowing you to identify who this
5351 * @param resultCode The integer result code returned by the child activity
5352 * through its setResult().
5353 * @param data An Intent, which can return result data to the caller
5354 * (various data can be attached to Intent "extras").
5356 * @see #startActivityForResult
5357 * @see #createPendingResult
5358 * @see #setResult(int)
5360 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5364 * Called when an activity you launched with an activity transition exposes this
5365 * Activity through a returning activity transition, giving you the resultCode
5366 * and any additional data from it. This method will only be called if the activity
5367 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5368 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5370 * <p>The purpose of this function is to let the called Activity send a hint about
5371 * its state so that this underlying Activity can prepare to be exposed. A call to
5372 * this method does not guarantee that the called Activity has or will be exiting soon.
5373 * It only indicates that it will expose this Activity's Window and it has
5374 * some data to pass to prepare it.</p>
5376 * @param resultCode The integer result code returned by the child activity
5377 * through its setResult().
5378 * @param data An Intent, which can return result data to the caller
5379 * (various data can be attached to Intent "extras").
5381 public void onActivityReenter(int resultCode, Intent data) {
5385 * Create a new PendingIntent object which you can hand to others
5386 * for them to use to send result data back to your
5387 * {@link #onActivityResult} callback. The created object will be either
5388 * one-shot (becoming invalid after a result is sent back) or multiple
5389 * (allowing any number of results to be sent through it).
5391 * @param requestCode Private request code for the sender that will be
5392 * associated with the result data when it is returned. The sender can not
5393 * modify this value, allowing you to identify incoming results.
5394 * @param data Default data to supply in the result, which may be modified
5396 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5397 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5398 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5399 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5400 * or any of the flags as supported by
5401 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5402 * of the intent that can be supplied when the actual send happens.
5404 * @return Returns an existing or new PendingIntent matching the given
5405 * parameters. May return null only if
5406 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5409 * @see PendingIntent
5411 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5412 @PendingIntent.Flags int flags) {
5413 String packageName = getPackageName();
5415 data.prepareToLeaveProcess(this);
5416 IIntentSender target =
5417 ActivityManagerNative.getDefault().getIntentSender(
5418 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5419 mParent == null ? mToken : mParent.mToken,
5420 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5421 UserHandle.myUserId());
5422 return target != null ? new PendingIntent(target) : null;
5423 } catch (RemoteException e) {
5430 * Change the desired orientation of this activity. If the activity
5431 * is currently in the foreground or otherwise impacting the screen
5432 * orientation, the screen will immediately be changed (possibly causing
5433 * the activity to be restarted). Otherwise, this will be used the next
5434 * time the activity is visible.
5436 * @param requestedOrientation An orientation constant as used in
5437 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5439 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5440 if (mParent == null) {
5442 ActivityManagerNative.getDefault().setRequestedOrientation(
5443 mToken, requestedOrientation);
5444 } catch (RemoteException e) {
5448 mParent.setRequestedOrientation(requestedOrientation);
5453 * Return the current requested orientation of the activity. This will
5454 * either be the orientation requested in its component's manifest, or
5455 * the last requested orientation given to
5456 * {@link #setRequestedOrientation(int)}.
5458 * @return Returns an orientation constant as used in
5459 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5461 @ActivityInfo.ScreenOrientation
5462 public int getRequestedOrientation() {
5463 if (mParent == null) {
5465 return ActivityManagerNative.getDefault()
5466 .getRequestedOrientation(mToken);
5467 } catch (RemoteException e) {
5471 return mParent.getRequestedOrientation();
5473 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5477 * Return the identifier of the task this activity is in. This identifier
5478 * will remain the same for the lifetime of the activity.
5480 * @return Task identifier, an opaque integer.
5482 public int getTaskId() {
5484 return ActivityManagerNative.getDefault()
5485 .getTaskForActivity(mToken, false);
5486 } catch (RemoteException e) {
5492 * Return whether this activity is the root of a task. The root is the
5493 * first activity in a task.
5495 * @return True if this is the root activity, else false.
5497 public boolean isTaskRoot() {
5499 return ActivityManagerNative.getDefault().getTaskForActivity(mToken, true) >= 0;
5500 } catch (RemoteException e) {
5506 * Move the task containing this activity to the back of the activity
5507 * stack. The activity's order within the task is unchanged.
5509 * @param nonRoot If false then this only works if the activity is the root
5510 * of a task; if true it will work for any activity in
5513 * @return If the task was moved (or it was already at the
5514 * back) true is returned, else false.
5516 public boolean moveTaskToBack(boolean nonRoot) {
5518 return ActivityManagerNative.getDefault().moveActivityTaskToBack(
5520 } catch (RemoteException e) {
5527 * Returns class name for this activity with the package prefix removed.
5528 * This is the default name used to read and write settings.
5530 * @return The local class name.
5533 public String getLocalClassName() {
5534 final String pkg = getPackageName();
5535 final String cls = mComponent.getClassName();
5536 int packageLen = pkg.length();
5537 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5538 || cls.charAt(packageLen) != '.') {
5541 return cls.substring(packageLen+1);
5545 * Returns complete component name of this activity.
5547 * @return Returns the complete component name for this activity
5549 public ComponentName getComponentName()
5555 * Retrieve a {@link SharedPreferences} object for accessing preferences
5556 * that are private to this activity. This simply calls the underlying
5557 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5558 * class name as the preferences name.
5560 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5563 * @return Returns the single SharedPreferences instance that can be used
5564 * to retrieve and modify the preference values.
5566 public SharedPreferences getPreferences(int mode) {
5567 return getSharedPreferences(getLocalClassName(), mode);
5570 private void ensureSearchManager() {
5571 if (mSearchManager != null) {
5575 mSearchManager = new SearchManager(this, null);
5579 public Object getSystemService(@ServiceName @NonNull String name) {
5580 if (getBaseContext() == null) {
5581 throw new IllegalStateException(
5582 "System services not available to Activities before onCreate()");
5585 if (WINDOW_SERVICE.equals(name)) {
5586 return mWindowManager;
5587 } else if (SEARCH_SERVICE.equals(name)) {
5588 ensureSearchManager();
5589 return mSearchManager;
5591 return super.getSystemService(name);
5595 * Change the title associated with this activity. If this is a
5596 * top-level activity, the title for its window will change. If it
5597 * is an embedded activity, the parent can do whatever it wants
5600 public void setTitle(CharSequence title) {
5602 onTitleChanged(title, mTitleColor);
5604 if (mParent != null) {
5605 mParent.onChildTitleChanged(this, title);
5610 * Change the title associated with this activity. If this is a
5611 * top-level activity, the title for its window will change. If it
5612 * is an embedded activity, the parent can do whatever it wants
5615 public void setTitle(int titleId) {
5616 setTitle(getText(titleId));
5620 * Change the color of the title associated with this activity.
5622 * This method is deprecated starting in API Level 11 and replaced by action
5623 * bar styles. For information on styling the Action Bar, read the <a
5624 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5627 * @deprecated Use action bar styles instead.
5630 public void setTitleColor(int textColor) {
5631 mTitleColor = textColor;
5632 onTitleChanged(mTitle, textColor);
5635 public final CharSequence getTitle() {
5639 public final int getTitleColor() {
5643 protected void onTitleChanged(CharSequence title, int color) {
5645 final Window win = getWindow();
5647 win.setTitle(title);
5649 win.setTitleColor(color);
5652 if (mActionBar != null) {
5653 mActionBar.setWindowTitle(title);
5658 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5662 * Sets information describing the task with this activity for presentation inside the Recents
5663 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5664 * are traversed in order from the topmost activity to the bottommost. The traversal continues
5665 * for each property until a suitable value is found. For each task the taskDescription will be
5666 * returned in {@link android.app.ActivityManager.TaskDescription}.
5668 * @see ActivityManager#getRecentTasks
5669 * @see android.app.ActivityManager.TaskDescription
5671 * @param taskDescription The TaskDescription properties that describe the task with this activity
5673 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5674 if (mTaskDescription != taskDescription) {
5675 mTaskDescription.copyFrom(taskDescription);
5676 // Scale the icon down to something reasonable if it is provided
5677 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5678 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5679 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
5681 mTaskDescription.setIcon(icon);
5685 ActivityManagerNative.getDefault().setTaskDescription(mToken, mTaskDescription);
5686 } catch (RemoteException e) {
5691 * Sets the visibility of the progress bar in the title.
5693 * In order for the progress bar to be shown, the feature must be requested
5694 * via {@link #requestWindowFeature(int)}.
5696 * @param visible Whether to show the progress bars in the title.
5697 * @deprecated No longer supported starting in API 21.
5700 public final void setProgressBarVisibility(boolean visible) {
5701 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
5702 Window.PROGRESS_VISIBILITY_OFF);
5706 * Sets the visibility of the indeterminate progress bar in the title.
5708 * In order for the progress bar to be shown, the feature must be requested
5709 * via {@link #requestWindowFeature(int)}.
5711 * @param visible Whether to show the progress bars in the title.
5712 * @deprecated No longer supported starting in API 21.
5715 public final void setProgressBarIndeterminateVisibility(boolean visible) {
5716 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
5717 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
5721 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
5722 * is always indeterminate).
5724 * In order for the progress bar to be shown, the feature must be requested
5725 * via {@link #requestWindowFeature(int)}.
5727 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
5728 * @deprecated No longer supported starting in API 21.
5731 public final void setProgressBarIndeterminate(boolean indeterminate) {
5732 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5733 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
5734 : Window.PROGRESS_INDETERMINATE_OFF);
5738 * Sets the progress for the progress bars in the title.
5740 * In order for the progress bar to be shown, the feature must be requested
5741 * via {@link #requestWindowFeature(int)}.
5743 * @param progress The progress for the progress bar. Valid ranges are from
5744 * 0 to 10000 (both inclusive). If 10000 is given, the progress
5745 * bar will be completely filled and will fade out.
5746 * @deprecated No longer supported starting in API 21.
5749 public final void setProgress(int progress) {
5750 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
5754 * Sets the secondary progress for the progress bar in the title. This
5755 * progress is drawn between the primary progress (set via
5756 * {@link #setProgress(int)} and the background. It can be ideal for media
5757 * scenarios such as showing the buffering progress while the default
5758 * progress shows the play progress.
5760 * In order for the progress bar to be shown, the feature must be requested
5761 * via {@link #requestWindowFeature(int)}.
5763 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
5764 * 0 to 10000 (both inclusive).
5765 * @deprecated No longer supported starting in API 21.
5768 public final void setSecondaryProgress(int secondaryProgress) {
5769 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
5770 secondaryProgress + Window.PROGRESS_SECONDARY_START);
5774 * Suggests an audio stream whose volume should be changed by the hardware
5777 * The suggested audio stream will be tied to the window of this Activity.
5778 * Volume requests which are received while the Activity is in the
5779 * foreground will affect this stream.
5781 * It is not guaranteed that the hardware volume controls will always change
5782 * this stream's volume (for example, if a call is in progress, its stream's
5783 * volume may be changed instead). To reset back to the default, use
5784 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
5786 * @param streamType The type of the audio stream whose volume should be
5787 * changed by the hardware volume controls.
5789 public final void setVolumeControlStream(int streamType) {
5790 getWindow().setVolumeControlStream(streamType);
5794 * Gets the suggested audio stream whose volume should be changed by the
5795 * hardware volume controls.
5797 * @return The suggested audio stream type whose volume should be changed by
5798 * the hardware volume controls.
5799 * @see #setVolumeControlStream(int)
5801 public final int getVolumeControlStream() {
5802 return getWindow().getVolumeControlStream();
5806 * Sets a {@link MediaController} to send media keys and volume changes to.
5808 * The controller will be tied to the window of this Activity. Media key and
5809 * volume events which are received while the Activity is in the foreground
5810 * will be forwarded to the controller and used to invoke transport controls
5811 * or adjust the volume. This may be used instead of or in addition to
5812 * {@link #setVolumeControlStream} to affect a specific session instead of a
5815 * It is not guaranteed that the hardware volume controls will always change
5816 * this session's volume (for example, if a call is in progress, its
5817 * stream's volume may be changed instead). To reset back to the default use
5818 * null as the controller.
5820 * @param controller The controller for the session which should receive
5821 * media keys and volume changes.
5823 public final void setMediaController(MediaController controller) {
5824 getWindow().setMediaController(controller);
5828 * Gets the controller which should be receiving media key and volume events
5829 * while this activity is in the foreground.
5831 * @return The controller which should receive events.
5832 * @see #setMediaController(android.media.session.MediaController)
5834 public final MediaController getMediaController() {
5835 return getWindow().getMediaController();
5839 * Runs the specified action on the UI thread. If the current thread is the UI
5840 * thread, then the action is executed immediately. If the current thread is
5841 * not the UI thread, the action is posted to the event queue of the UI thread.
5843 * @param action the action to run on the UI thread
5845 public final void runOnUiThread(Runnable action) {
5846 if (Thread.currentThread() != mUiThread) {
5847 mHandler.post(action);
5854 * Standard implementation of
5855 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
5856 * inflating with the LayoutInflater returned by {@link #getSystemService}.
5857 * This implementation does nothing and is for
5858 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
5859 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
5861 * @see android.view.LayoutInflater#createView
5862 * @see android.view.Window#getLayoutInflater
5865 public View onCreateView(String name, Context context, AttributeSet attrs) {
5870 * Standard implementation of
5871 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
5872 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
5873 * This implementation handles <fragment> tags to embed fragments inside
5876 * @see android.view.LayoutInflater#createView
5877 * @see android.view.Window#getLayoutInflater
5879 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
5880 if (!"fragment".equals(name)) {
5881 return onCreateView(name, context, attrs);
5884 return mFragments.onCreateView(parent, name, context, attrs);
5888 * Print the Activity's state into the given stream. This gets invoked if
5889 * you run "adb shell dumpsys activity <activity_component_name>".
5891 * @param prefix Desired prefix to prepend at each line of output.
5892 * @param fd The raw file descriptor that the dump is being sent to.
5893 * @param writer The PrintWriter to which you should dump your state. This will be
5894 * closed for you after you return.
5895 * @param args additional arguments to the dump request.
5897 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5898 dumpInner(prefix, fd, writer, args);
5901 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5902 writer.print(prefix); writer.print("Local Activity ");
5903 writer.print(Integer.toHexString(System.identityHashCode(this)));
5904 writer.println(" State:");
5905 String innerPrefix = prefix + " ";
5906 writer.print(innerPrefix); writer.print("mResumed=");
5907 writer.print(mResumed); writer.print(" mStopped=");
5908 writer.print(mStopped); writer.print(" mFinished=");
5909 writer.println(mFinished);
5910 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
5911 writer.println(mChangingConfigurations);
5912 writer.print(innerPrefix); writer.print("mCurrentConfig=");
5913 writer.println(mCurrentConfig);
5915 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
5916 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
5917 if (mVoiceInteractor != null) {
5918 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
5921 if (getWindow() != null &&
5922 getWindow().peekDecorView() != null &&
5923 getWindow().peekDecorView().getViewRootImpl() != null) {
5924 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
5927 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
5931 * Bit indicating that this activity is "immersive" and should not be
5932 * interrupted by notifications if possible.
5934 * This value is initially set by the manifest property
5935 * <code>android:immersive</code> but may be changed at runtime by
5936 * {@link #setImmersive}.
5938 * @see #setImmersive(boolean)
5939 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
5941 public boolean isImmersive() {
5943 return ActivityManagerNative.getDefault().isImmersive(mToken);
5944 } catch (RemoteException e) {
5950 * Indication of whether this is the highest level activity in this task. Can be used to
5951 * determine whether an activity launched by this activity was placed in the same task or
5954 * @return true if this is the topmost, non-finishing activity in its task.
5956 private boolean isTopOfTask() {
5957 if (mToken == null || mWindow == null) {
5961 return ActivityManagerNative.getDefault().isTopOfTask(getActivityToken());
5962 } catch (RemoteException e) {
5968 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
5969 * fullscreen opaque Activity.
5971 * Call this whenever the background of a translucent Activity has changed to become opaque.
5972 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
5974 * This call has no effect on non-translucent activities or on activities with the
5975 * {@link android.R.attr#windowIsFloating} attribute.
5977 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
5979 * @see TranslucentConversionListener
5984 public void convertFromTranslucent() {
5986 mTranslucentCallback = null;
5987 if (ActivityManagerNative.getDefault().convertFromTranslucent(mToken)) {
5988 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
5990 } catch (RemoteException e) {
5996 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
5997 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
5999 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
6000 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
6001 * be called indicating that it is safe to make this activity translucent again. Until
6002 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
6003 * behind the frontmost Activity will be indeterminate.
6005 * This call has no effect on non-translucent activities or on activities with the
6006 * {@link android.R.attr#windowIsFloating} attribute.
6008 * @param callback the method to call when all visible Activities behind this one have been
6009 * drawn and it is safe to make this Activity translucent again.
6010 * @param options activity options delivered to the activity below this one. The options
6011 * are retrieved using {@link #getActivityOptions}.
6012 * @return <code>true</code> if Window was opaque and will become translucent or
6013 * <code>false</code> if window was translucent and no change needed to be made.
6015 * @see #convertFromTranslucent()
6016 * @see TranslucentConversionListener
6021 public boolean convertToTranslucent(TranslucentConversionListener callback,
6022 ActivityOptions options) {
6023 boolean drawComplete;
6025 mTranslucentCallback = callback;
6026 mChangeCanvasToTranslucent =
6027 ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
6028 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6029 drawComplete = true;
6030 } catch (RemoteException e) {
6031 // Make callback return as though it timed out.
6032 mChangeCanvasToTranslucent = false;
6033 drawComplete = false;
6035 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
6036 // Window is already translucent.
6037 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6039 return mChangeCanvasToTranslucent;
6043 void onTranslucentConversionComplete(boolean drawComplete) {
6044 if (mTranslucentCallback != null) {
6045 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6046 mTranslucentCallback = null;
6048 if (mChangeCanvasToTranslucent) {
6049 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6054 public void onNewActivityOptions(ActivityOptions options) {
6055 mActivityTransitionState.setEnterActivityOptions(this, options);
6057 mActivityTransitionState.enterReady(this);
6062 * Retrieve the ActivityOptions passed in from the launching activity or passed back
6063 * from an activity launched by this activity in its call to {@link
6064 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
6066 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
6069 ActivityOptions getActivityOptions() {
6071 return ActivityManagerNative.getDefault().getActivityOptions(mToken);
6072 } catch (RemoteException e) {
6078 * Activities that want to remain visible behind a translucent activity above them must call
6079 * this method anytime between the start of {@link #onResume()} and the return from
6080 * {@link #onPause()}. If this call is successful then the activity will remain visible after
6081 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
6083 * <p>The actions of this call are reset each time that this activity is brought to the
6084 * front. That is, every time {@link #onResume()} is called the activity will be assumed
6085 * to not have requested visible behind. Therefore, if you want this activity to continue to
6086 * be visible in the background you must call this method again.
6088 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
6089 * for dialog and translucent activities.
6091 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
6092 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
6094 * <p>False will be returned any time this method is called between the return of onPause and
6095 * the next call to onResume.
6097 * @param visible true to notify the system that the activity wishes to be visible behind other
6098 * translucent activities, false to indicate otherwise. Resources must be
6099 * released when passing false to this method.
6100 * @return the resulting visibiity state. If true the activity will remain visible beyond
6101 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
6102 * then the activity may not count on being visible behind other translucent activities,
6103 * and must stop any media playback and release resources.
6104 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
6105 * the return value must be checked.
6107 * @see #onVisibleBehindCanceled()
6109 public boolean requestVisibleBehind(boolean visible) {
6111 // Do not permit paused or stopped activities to do this.
6115 mVisibleBehind = ActivityManagerNative.getDefault()
6116 .requestVisibleBehind(mToken, visible) && visible;
6117 } catch (RemoteException e) {
6118 mVisibleBehind = false;
6120 return mVisibleBehind;
6124 * Called when a translucent activity over this activity is becoming opaque or another
6125 * activity is being launched. Activities that override this method must call
6126 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
6128 * <p>When this method is called the activity has 500 msec to release any resources it may be
6129 * using while visible in the background.
6130 * If the activity has not returned from this method in 500 msec the system will destroy
6131 * the activity and kill the process in order to recover the resources for another
6132 * process. Otherwise {@link #onStop()} will be called following return.
6134 * @see #requestVisibleBehind(boolean)
6137 public void onVisibleBehindCanceled() {
6142 * Translucent activities may call this to determine if there is an activity below them that
6143 * is currently set to be visible in the background.
6145 * @return true if an activity below is set to visible according to the most recent call to
6146 * {@link #requestVisibleBehind(boolean)}, false otherwise.
6148 * @see #requestVisibleBehind(boolean)
6149 * @see #onVisibleBehindCanceled()
6150 * @see #onBackgroundVisibleBehindChanged(boolean)
6154 public boolean isBackgroundVisibleBehind() {
6156 return ActivityManagerNative.getDefault().isBackgroundVisibleBehind(mToken);
6157 } catch (RemoteException e) {
6163 * The topmost foreground activity will receive this call when the background visibility state
6164 * of the activity below it changes.
6166 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
6167 * due to a background activity finishing itself.
6169 * @param visible true if a background activity is visible, false otherwise.
6171 * @see #requestVisibleBehind(boolean)
6172 * @see #onVisibleBehindCanceled()
6176 public void onBackgroundVisibleBehindChanged(boolean visible) {
6180 * Activities cannot draw during the period that their windows are animating in. In order
6181 * to know when it is safe to begin drawing they can override this method which will be
6182 * called when the entering animation has completed.
6184 public void onEnterAnimationComplete() {
6190 public void dispatchEnterAnimationComplete() {
6191 onEnterAnimationComplete();
6192 if (getWindow() != null && getWindow().getDecorView() != null) {
6193 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
6198 * Adjust the current immersive mode setting.
6200 * Note that changing this value will have no effect on the activity's
6201 * {@link android.content.pm.ActivityInfo} structure; that is, if
6202 * <code>android:immersive</code> is set to <code>true</code>
6203 * in the application's manifest entry for this activity, the {@link
6204 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
6205 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6206 * FLAG_IMMERSIVE} bit set.
6208 * @see #isImmersive()
6209 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6211 public void setImmersive(boolean i) {
6213 ActivityManagerNative.getDefault().setImmersive(mToken, i);
6214 } catch (RemoteException e) {
6220 * Enable or disable virtual reality (VR) mode for this Activity.
6222 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
6223 * while this Activity has user focus.</p>
6225 * <p>It is recommended that applications additionally declare
6226 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
6227 * transitions when switching between VR activities.</p>
6229 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
6230 * VR mode will not be started. Developers can handle this case as follows:</p>
6233 * String servicePackage = "com.whatever.app";
6234 * String serviceClass = "com.whatever.app.MyVrListenerService";
6236 * // Name of the component of the VrListenerService to start.
6237 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
6240 * setVrModeEnabled(true, myComponentName);
6241 * } catch (PackageManager.NameNotFoundException e) {
6242 * List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
6243 * boolean isInstalled = false;
6244 * for (ApplicationInfo app : installed) {
6245 * if (app.packageName.equals(servicePackage)) {
6246 * isInstalled = true;
6250 * if (isInstalled) {
6251 * // Package is installed, but not enabled in Settings. Let user enable it.
6252 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
6254 * // Package is not installed. Send an intent to download this.
6255 * sentIntentToLaunchAppStore(servicePackage);
6260 * @param enabled {@code true} to enable this mode.
6261 * @param requestedComponent the name of the component to use as a
6262 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
6264 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
6265 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
6266 * not been enabled in user settings.
6268 * @see android.content.pm.PackageManager#FEATURE_VR_MODE
6269 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
6270 * @see android.service.vr.VrListenerService
6271 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
6272 * @see android.R.attr#enableVrMode
6274 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
6275 throws PackageManager.NameNotFoundException {
6277 if (ActivityManagerNative.getDefault().setVrMode(mToken, enabled, requestedComponent)
6279 throw new PackageManager.NameNotFoundException(
6280 requestedComponent.flattenToString());
6282 } catch (RemoteException e) {
6288 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
6290 * @param callback Callback that will manage lifecycle events for this action mode
6291 * @return The ActionMode that was started, or null if it was canceled
6296 public ActionMode startActionMode(ActionMode.Callback callback) {
6297 return mWindow.getDecorView().startActionMode(callback);
6301 * Start an action mode of the given type.
6303 * @param callback Callback that will manage lifecycle events for this action mode
6304 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6305 * @return The ActionMode that was started, or null if it was canceled
6310 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6311 return mWindow.getDecorView().startActionMode(callback, type);
6315 * Give the Activity a chance to control the UI for an action mode requested
6318 * <p>Note: If you are looking for a notification callback that an action mode
6319 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
6321 * @param callback The callback that should control the new action mode
6322 * @return The new action mode, or <code>null</code> if the activity does not want to
6323 * provide special handling for this action mode. (It will be handled by the system.)
6327 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
6328 // Only Primary ActionModes are represented in the ActionBar.
6329 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
6330 initWindowDecorActionBar();
6331 if (mActionBar != null) {
6332 return mActionBar.startActionMode(callback);
6343 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
6345 mActionModeTypeStarting = type;
6346 return onWindowStartingActionMode(callback);
6348 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
6353 * Notifies the Activity that an action mode has been started.
6354 * Activity subclasses overriding this method should call the superclass implementation.
6356 * @param mode The new action mode.
6360 public void onActionModeStarted(ActionMode mode) {
6364 * Notifies the activity that an action mode has finished.
6365 * Activity subclasses overriding this method should call the superclass implementation.
6367 * @param mode The action mode that just finished.
6371 public void onActionModeFinished(ActionMode mode) {
6375 * Returns true if the app should recreate the task when navigating 'up' from this activity
6376 * by using targetIntent.
6378 * <p>If this method returns false the app can trivially call
6379 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
6380 * up navigation. If this method returns false, the app should synthesize a new task stack
6381 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6383 * @param targetIntent An intent representing the target destination for up navigation
6384 * @return true if navigating up should recreate a new task stack, false if the same task
6385 * should be used for the destination
6387 public boolean shouldUpRecreateTask(Intent targetIntent) {
6389 PackageManager pm = getPackageManager();
6390 ComponentName cn = targetIntent.getComponent();
6392 cn = targetIntent.resolveActivity(pm);
6394 ActivityInfo info = pm.getActivityInfo(cn, 0);
6395 if (info.taskAffinity == null) {
6398 return ActivityManagerNative.getDefault()
6399 .shouldUpRecreateTask(mToken, info.taskAffinity);
6400 } catch (RemoteException e) {
6402 } catch (NameNotFoundException e) {
6408 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6409 * in the process. If the activity indicated by upIntent already exists in the task's history,
6410 * this activity and all others before the indicated activity in the history stack will be
6413 * <p>If the indicated activity does not appear in the history stack, this will finish
6414 * each activity in this task until the root activity of the task is reached, resulting in
6415 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6416 * when an activity may be reached by a path not passing through a canonical parent
6419 * <p>This method should be used when performing up navigation from within the same task
6420 * as the destination. If up navigation should cross tasks in some cases, see
6421 * {@link #shouldUpRecreateTask(Intent)}.</p>
6423 * @param upIntent An intent representing the target destination for up navigation
6425 * @return true if up navigation successfully reached the activity indicated by upIntent and
6426 * upIntent was delivered to it. false if an instance of the indicated activity could
6427 * not be found and this activity was simply finished normally.
6429 public boolean navigateUpTo(Intent upIntent) {
6430 if (mParent == null) {
6431 ComponentName destInfo = upIntent.getComponent();
6432 if (destInfo == null) {
6433 destInfo = upIntent.resolveActivity(getPackageManager());
6434 if (destInfo == null) {
6437 upIntent = new Intent(upIntent);
6438 upIntent.setComponent(destInfo);
6442 synchronized (this) {
6443 resultCode = mResultCode;
6444 resultData = mResultData;
6446 if (resultData != null) {
6447 resultData.prepareToLeaveProcess(this);
6450 upIntent.prepareToLeaveProcess(this);
6451 return ActivityManagerNative.getDefault().navigateUpTo(mToken, upIntent,
6452 resultCode, resultData);
6453 } catch (RemoteException e) {
6457 return mParent.navigateUpToFromChild(this, upIntent);
6462 * This is called when a child activity of this one calls its
6463 * {@link #navigateUpTo} method. The default implementation simply calls
6464 * navigateUpTo(upIntent) on this activity (the parent).
6466 * @param child The activity making the call.
6467 * @param upIntent An intent representing the target destination for up navigation
6469 * @return true if up navigation successfully reached the activity indicated by upIntent and
6470 * upIntent was delivered to it. false if an instance of the indicated activity could
6471 * not be found and this activity was simply finished normally.
6473 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6474 return navigateUpTo(upIntent);
6478 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6479 * this activity's logical parent. The logical parent is named in the application's manifest
6480 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6481 * Activity subclasses may override this method to modify the Intent returned by
6482 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6483 * the parent intent entirely.
6485 * @return a new Intent targeting the defined parent of this activity or null if
6486 * there is no valid parent.
6489 public Intent getParentActivityIntent() {
6490 final String parentName = mActivityInfo.parentActivityName;
6491 if (TextUtils.isEmpty(parentName)) {
6495 // If the parent itself has no parent, generate a main activity intent.
6496 final ComponentName target = new ComponentName(this, parentName);
6498 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6499 final String parentActivity = parentInfo.parentActivityName;
6500 final Intent parentIntent = parentActivity == null
6501 ? Intent.makeMainActivity(target)
6502 : new Intent().setComponent(target);
6503 return parentIntent;
6504 } catch (NameNotFoundException e) {
6505 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6512 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6513 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6514 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6515 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6517 * @param callback Used to manipulate shared element transitions on the launched Activity.
6519 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6520 if (callback == null) {
6521 callback = SharedElementCallback.NULL_CALLBACK;
6523 mEnterTransitionListener = callback;
6527 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6528 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6529 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6530 * calls will only come when returning from the started Activity.
6531 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6533 * @param callback Used to manipulate shared element transitions on the launching Activity.
6535 public void setExitSharedElementCallback(SharedElementCallback callback) {
6536 if (callback == null) {
6537 callback = SharedElementCallback.NULL_CALLBACK;
6539 mExitTransitionListener = callback;
6543 * Postpone the entering activity transition when Activity was started with
6544 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6545 * android.util.Pair[])}.
6546 * <p>This method gives the Activity the ability to delay starting the entering and
6547 * shared element transitions until all data is loaded. Until then, the Activity won't
6548 * draw into its window, leaving the window transparent. This may also cause the
6549 * returning animation to be delayed until data is ready. This method should be
6550 * called in {@link #onCreate(android.os.Bundle)} or in
6551 * {@link #onActivityReenter(int, android.content.Intent)}.
6552 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6553 * start the transitions. If the Activity did not use
6554 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6555 * android.util.Pair[])}, then this method does nothing.</p>
6557 public void postponeEnterTransition() {
6558 mActivityTransitionState.postponeEnterTransition();
6562 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6563 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6564 * to have your Activity start drawing.
6566 public void startPostponedEnterTransition() {
6567 mActivityTransitionState.startPostponedEnterTransition();
6571 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
6572 * access permissions for content URIs associated with the {@link DragEvent}.
6573 * @param event Drag event
6574 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
6575 * Null if no content URIs are associated with the event or if permissions could not be granted.
6577 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
6578 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
6579 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
6580 return dragAndDropPermissions;
6585 // ------------------ Internal API ------------------
6587 final void setParent(Activity parent) {
6591 final void attach(Context context, ActivityThread aThread,
6592 Instrumentation instr, IBinder token, int ident,
6593 Application application, Intent intent, ActivityInfo info,
6594 CharSequence title, Activity parent, String id,
6595 NonConfigurationInstances lastNonConfigurationInstances,
6596 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6598 attachBaseContext(context);
6600 mFragments.attachHost(null /*parent*/);
6602 mWindow = new PhoneWindow(this, window);
6603 mWindow.setWindowControllerCallback(this);
6604 mWindow.setCallback(this);
6605 mWindow.setOnWindowDismissedCallback(this);
6606 mWindow.getLayoutInflater().setPrivateFactory(this);
6607 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6608 mWindow.setSoftInputMode(info.softInputMode);
6610 if (info.uiOptions != 0) {
6611 mWindow.setUiOptions(info.uiOptions);
6613 mUiThread = Thread.currentThread();
6615 mMainThread = aThread;
6616 mInstrumentation = instr;
6619 mApplication = application;
6621 mReferrer = referrer;
6622 mComponent = intent.getComponent();
6623 mActivityInfo = info;
6627 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6628 if (voiceInteractor != null) {
6629 if (lastNonConfigurationInstances != null) {
6630 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6632 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6637 mWindow.setWindowManager(
6638 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6639 mToken, mComponent.flattenToString(),
6640 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6641 if (mParent != null) {
6642 mWindow.setContainer(mParent.getWindow());
6644 mWindowManager = mWindow.getWindowManager();
6645 mCurrentConfig = config;
6649 public final IBinder getActivityToken() {
6650 return mParent != null ? mParent.getActivityToken() : mToken;
6653 final void performCreateCommon() {
6654 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6655 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6656 mFragments.dispatchActivityCreated();
6657 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6660 final void performCreate(Bundle icicle) {
6661 restoreHasCurrentPermissionRequest(icicle);
6663 mActivityTransitionState.readState(icicle);
6664 performCreateCommon();
6667 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6668 restoreHasCurrentPermissionRequest(icicle);
6669 onCreate(icicle, persistentState);
6670 mActivityTransitionState.readState(icicle);
6671 performCreateCommon();
6674 final void performStart() {
6675 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6676 mFragments.noteStateNotSaved();
6678 mFragments.execPendingActions();
6679 mInstrumentation.callActivityOnStart(this);
6681 throw new SuperNotCalledException(
6682 "Activity " + mComponent.toShortString() +
6683 " did not call through to super.onStart()");
6685 mFragments.dispatchStart();
6686 mFragments.reportLoaderStart();
6688 // This property is set for all builds except final release
6689 boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
6690 boolean isAppDebuggable =
6691 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
6693 if (isAppDebuggable || isDlwarningEnabled) {
6694 String dlwarning = getDlWarning();
6695 if (dlwarning != null) {
6696 String appName = getApplicationInfo().loadLabel(getPackageManager())
6698 String warning = "Detected problems with app native libraries\n" +
6699 "(please consult log for detail):\n" + dlwarning;
6700 if (isAppDebuggable) {
6701 new AlertDialog.Builder(this).
6703 setMessage(warning).
6704 setPositiveButton(android.R.string.ok, null).
6705 setCancelable(false).
6708 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
6713 mActivityTransitionState.enterReady(this);
6716 final void performRestart() {
6717 mFragments.noteStateNotSaved();
6719 if (mToken != null && mParent == null) {
6720 // No need to check mStopped, the roots will check if they were actually stopped.
6721 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
6727 synchronized (mManagedCursors) {
6728 final int N = mManagedCursors.size();
6729 for (int i=0; i<N; i++) {
6730 ManagedCursor mc = mManagedCursors.get(i);
6731 if (mc.mReleased || mc.mUpdated) {
6732 if (!mc.mCursor.requery()) {
6733 if (getApplicationInfo().targetSdkVersion
6734 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
6735 throw new IllegalStateException(
6736 "trying to requery an already closed cursor "
6740 mc.mReleased = false;
6741 mc.mUpdated = false;
6747 mInstrumentation.callActivityOnRestart(this);
6749 throw new SuperNotCalledException(
6750 "Activity " + mComponent.toShortString() +
6751 " did not call through to super.onRestart()");
6757 final void performResume() {
6760 mFragments.execPendingActions();
6762 mLastNonConfigurationInstances = null;
6765 // mResumed is set by the instrumentation
6766 mInstrumentation.callActivityOnResume(this);
6768 throw new SuperNotCalledException(
6769 "Activity " + mComponent.toShortString() +
6770 " did not call through to super.onResume()");
6773 // invisible activities must be finished before onResume() completes
6774 if (!mVisibleFromClient && !mFinished) {
6775 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
6776 if (getApplicationInfo().targetSdkVersion
6777 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
6778 throw new IllegalStateException(
6779 "Activity " + mComponent.toShortString() +
6780 " did not call finish() prior to onResume() completing");
6784 // Now really resume, and install the current status bar and menu.
6787 mFragments.dispatchResume();
6788 mFragments.execPendingActions();
6792 throw new SuperNotCalledException(
6793 "Activity " + mComponent.toShortString() +
6794 " did not call through to super.onPostResume()");
6798 final void performPause() {
6799 mDoReportFullyDrawn = false;
6800 mFragments.dispatchPause();
6804 if (!mCalled && getApplicationInfo().targetSdkVersion
6805 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
6806 throw new SuperNotCalledException(
6807 "Activity " + mComponent.toShortString() +
6808 " did not call through to super.onPause()");
6813 final void performUserLeaving() {
6814 onUserInteraction();
6818 final void performStop(boolean preserveWindow) {
6819 mDoReportFullyDrawn = false;
6820 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
6823 if (mWindow != null) {
6824 mWindow.closeAllPanels();
6827 // If we're preserving the window, don't setStoppedState to true, since we
6828 // need the window started immediately again. Stopping the window will
6829 // destroys hardware resources and causes flicker.
6830 if (!preserveWindow && mToken != null && mParent == null) {
6831 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
6834 mFragments.dispatchStop();
6837 mInstrumentation.callActivityOnStop(this);
6839 throw new SuperNotCalledException(
6840 "Activity " + mComponent.toShortString() +
6841 " did not call through to super.onStop()");
6844 synchronized (mManagedCursors) {
6845 final int N = mManagedCursors.size();
6846 for (int i=0; i<N; i++) {
6847 ManagedCursor mc = mManagedCursors.get(i);
6848 if (!mc.mReleased) {
6849 mc.mCursor.deactivate();
6850 mc.mReleased = true;
6860 final void performDestroy() {
6863 mFragments.dispatchDestroy();
6865 mFragments.doLoaderDestroy();
6866 if (mVoiceInteractor != null) {
6867 mVoiceInteractor.detachActivity();
6871 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode) {
6872 if (DEBUG_LIFECYCLE) Slog.v(TAG,
6873 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode);
6874 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode);
6875 if (mWindow != null) {
6876 mWindow.onMultiWindowModeChanged();
6878 onMultiWindowModeChanged(isInMultiWindowMode);
6881 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
6882 if (DEBUG_LIFECYCLE) Slog.v(TAG,
6883 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode);
6884 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode);
6885 onPictureInPictureModeChanged(isInPictureInPictureMode);
6891 public final boolean isResumed() {
6895 private void storeHasCurrentPermissionRequest(Bundle bundle) {
6896 if (bundle != null && mHasCurrentPermissionsRequest) {
6897 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
6901 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
6902 if (bundle != null) {
6903 mHasCurrentPermissionsRequest = bundle.getBoolean(
6904 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
6908 void dispatchActivityResult(String who, int requestCode,
6909 int resultCode, Intent data) {
6911 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
6912 + ", resCode=" + resultCode + ", data=" + data);
6913 mFragments.noteStateNotSaved();
6915 onActivityResult(requestCode, resultCode, data);
6916 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
6917 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
6918 if (TextUtils.isEmpty(who)) {
6919 dispatchRequestPermissionsResult(requestCode, data);
6921 Fragment frag = mFragments.findFragmentByWho(who);
6923 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
6926 } else if (who.startsWith("@android:view:")) {
6927 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
6928 getActivityToken());
6929 for (ViewRootImpl viewRoot : views) {
6930 if (viewRoot.getView() != null
6931 && viewRoot.getView().dispatchActivityResult(
6932 who, requestCode, resultCode, data)) {
6937 Fragment frag = mFragments.findFragmentByWho(who);
6939 frag.onActivityResult(requestCode, resultCode, data);
6945 * Request to put this Activity in a mode where the user is locked to the
6948 * This will prevent the user from launching other apps, going to settings, or reaching the
6949 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
6950 * values permit launching while locked.
6952 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
6953 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
6954 * Lock Task mode. The user will not be able to exit this mode until
6955 * {@link Activity#stopLockTask()} is called.
6957 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
6958 * then the system will prompt the user with a dialog requesting permission to enter
6959 * this mode. When entered through this method the user can exit at any time through
6960 * an action described by the request dialog. Calling stopLockTask will also exit the
6963 * @see android.R.attr#lockTaskMode
6965 public void startLockTask() {
6967 ActivityManagerNative.getDefault().startLockTaskMode(mToken);
6968 } catch (RemoteException e) {
6973 * Allow the user to switch away from the current task.
6975 * Called to end the mode started by {@link Activity#startLockTask}. This
6976 * can only be called by activities that have successfully called
6977 * startLockTask previously.
6979 * This will allow the user to exit this app and move onto other activities.
6980 * <p>Note: This method should only be called when the activity is user-facing. That is,
6981 * between onResume() and onPause().
6982 * <p>Note: If there are other tasks below this one that are also locked then calling this
6983 * method will immediately finish this task and resume the previous locked one, remaining in
6986 * @see android.R.attr#lockTaskMode
6987 * @see ActivityManager#getLockTaskModeState()
6989 public void stopLockTask() {
6991 ActivityManagerNative.getDefault().stopLockTaskMode();
6992 } catch (RemoteException e) {
6997 * Shows the user the system defined message for telling the user how to exit
6998 * lock task mode. The task containing this activity must be in lock task mode at the time
6999 * of this call for the message to be displayed.
7001 public void showLockTaskEscapeMessage() {
7003 ActivityManagerNative.getDefault().showLockTaskEscapeMessage(mToken);
7004 } catch (RemoteException e) {
7009 * Check whether the caption on freeform windows is displayed directly on the content.
7011 * @return True if caption is displayed on content, false if it pushes the content down.
7013 * @see {@link #setOverlayWithDecorCaptionEnabled(boolean)}
7017 public boolean isOverlayWithDecorCaptionEnabled() {
7018 return mWindow.isOverlayWithDecorCaptionEnabled();
7022 * Set whether the caption should displayed directly on the content rather than push it down.
7024 * This affects only freeform windows since they display the caption and only the main
7025 * window of the activity. The caption is used to drag the window around and also shows
7026 * maximize and close action buttons.
7030 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
7031 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
7035 * Interface for informing a translucent {@link Activity} once all visible activities below it
7036 * have completed drawing. This is necessary only after an {@link Activity} has been made
7037 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
7038 * translucent again following a call to {@link
7039 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7045 public interface TranslucentConversionListener {
7047 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
7048 * below the top one have been redrawn. Following this callback it is safe to make the top
7049 * Activity translucent because the underlying Activity has been drawn.
7051 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
7052 * occurred waiting for the Activity to complete drawing.
7054 * @see Activity#convertFromTranslucent()
7055 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
7057 public void onTranslucentConversionComplete(boolean drawComplete);
7060 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
7061 mHasCurrentPermissionsRequest = false;
7062 // If the package installer crashed we may have not data - best effort.
7063 String[] permissions = (data != null) ? data.getStringArrayExtra(
7064 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7065 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7066 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7067 onRequestPermissionsResult(requestCode, permissions, grantResults);
7070 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
7071 Fragment fragment) {
7072 // If the package installer crashed we may have not data - best effort.
7073 String[] permissions = (data != null) ? data.getStringArrayExtra(
7074 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7075 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7076 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7077 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
7080 class HostCallbacks extends FragmentHostCallback<Activity> {
7081 public HostCallbacks() {
7082 super(Activity.this /*activity*/);
7086 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
7087 Activity.this.dump(prefix, fd, writer, args);
7091 public boolean onShouldSaveFragmentState(Fragment fragment) {
7092 return !isFinishing();
7096 public LayoutInflater onGetLayoutInflater() {
7097 final LayoutInflater result = Activity.this.getLayoutInflater();
7098 if (onUseFragmentManagerInflaterFactory()) {
7099 return result.cloneInContext(Activity.this);
7105 public boolean onUseFragmentManagerInflaterFactory() {
7106 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
7107 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
7111 public Activity onGetHost() {
7112 return Activity.this;
7116 public void onInvalidateOptionsMenu() {
7117 Activity.this.invalidateOptionsMenu();
7121 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
7123 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
7127 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
7128 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
7129 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
7130 if (mParent == null) {
7131 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
7132 flagsMask, flagsValues, options);
7133 } else if (options != null) {
7134 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode,
7135 fillInIntent, flagsMask, flagsValues, extraFlags, options);
7140 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
7142 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
7143 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
7144 startActivityForResult(who, intent, requestCode, null);
7148 public boolean onHasWindowAnimations() {
7149 return getWindow() != null;
7153 public int onGetWindowAnimations() {
7154 final Window w = getWindow();
7155 return (w == null) ? 0 : w.getAttributes().windowAnimations;
7159 public void onAttachFragment(Fragment fragment) {
7160 Activity.this.onAttachFragment(fragment);
7165 public View onFindViewById(int id) {
7166 return Activity.this.findViewById(id);
7170 public boolean onHasView() {
7171 final Window w = getWindow();
7172 return (w != null && w.peekDecorView() != null);