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 android.graphics.Rect;
20 import android.view.ViewRootImpl.ActivityConfigCallback;
21 import android.view.autofill.AutofillManager;
22 import android.view.autofill.AutofillPopupWindow;
23 import android.view.autofill.IAutofillWindowPresenter;
24 import com.android.internal.annotations.GuardedBy;
25 import com.android.internal.app.IVoiceInteractor;
26 import com.android.internal.app.ToolbarActionBar;
27 import com.android.internal.app.WindowDecorActionBar;
28 import com.android.internal.policy.DecorView;
29 import com.android.internal.policy.PhoneWindow;
31 import android.annotation.CallSuper;
32 import android.annotation.DrawableRes;
33 import android.annotation.IdRes;
34 import android.annotation.IntDef;
35 import android.annotation.LayoutRes;
36 import android.annotation.MainThread;
37 import android.annotation.NonNull;
38 import android.annotation.Nullable;
39 import android.annotation.RequiresPermission;
40 import android.annotation.StyleRes;
41 import android.annotation.SystemApi;
42 import android.app.VoiceInteractor.Request;
43 import android.app.admin.DevicePolicyManager;
44 import android.app.assist.AssistContent;
45 import android.content.ComponentCallbacks2;
46 import android.content.ComponentName;
47 import android.content.ContentResolver;
48 import android.content.Context;
49 import android.content.CursorLoader;
50 import android.content.IIntentSender;
51 import android.content.Intent;
52 import android.content.IntentSender;
53 import android.content.SharedPreferences;
54 import android.content.pm.ActivityInfo;
55 import android.content.pm.ApplicationInfo;
56 import android.content.pm.PackageManager;
57 import android.content.pm.PackageManager.NameNotFoundException;
58 import android.content.res.Configuration;
59 import android.content.res.Resources;
60 import android.content.res.TypedArray;
61 import android.database.Cursor;
62 import android.graphics.Bitmap;
63 import android.graphics.Canvas;
64 import android.graphics.Color;
65 import android.graphics.drawable.Drawable;
66 import android.media.AudioManager;
67 import android.media.session.MediaController;
68 import android.net.Uri;
69 import android.os.BadParcelableException;
70 import android.os.Build;
71 import android.os.Bundle;
72 import android.os.Handler;
73 import android.os.IBinder;
74 import android.os.Looper;
75 import android.os.Parcelable;
76 import android.os.PersistableBundle;
77 import android.os.RemoteException;
78 import android.os.ServiceManager.ServiceNotFoundException;
79 import android.os.StrictMode;
80 import android.os.SystemProperties;
81 import android.os.UserHandle;
82 import android.text.Selection;
83 import android.text.SpannableStringBuilder;
84 import android.text.TextUtils;
85 import android.text.method.TextKeyListener;
86 import android.transition.Scene;
87 import android.transition.TransitionManager;
88 import android.util.ArrayMap;
89 import android.util.AttributeSet;
90 import android.util.EventLog;
91 import android.util.Log;
92 import android.util.PrintWriterPrinter;
93 import android.util.Slog;
94 import android.util.SparseArray;
95 import android.util.SuperNotCalledException;
96 import android.view.ActionMode;
97 import android.view.ContextMenu;
98 import android.view.ContextMenu.ContextMenuInfo;
99 import android.view.ContextThemeWrapper;
100 import android.view.DragAndDropPermissions;
101 import android.view.DragEvent;
102 import android.view.KeyEvent;
103 import android.view.KeyboardShortcutGroup;
104 import android.view.KeyboardShortcutInfo;
105 import android.view.LayoutInflater;
106 import android.view.Menu;
107 import android.view.MenuInflater;
108 import android.view.MenuItem;
109 import android.view.MotionEvent;
110 import android.view.SearchEvent;
111 import android.view.View;
112 import android.view.View.OnCreateContextMenuListener;
113 import android.view.ViewGroup;
114 import android.view.ViewGroup.LayoutParams;
115 import android.view.ViewManager;
116 import android.view.ViewRootImpl;
117 import android.view.Window;
118 import android.view.Window.WindowControllerCallback;
119 import android.view.WindowManager;
120 import android.view.WindowManagerGlobal;
121 import android.view.accessibility.AccessibilityEvent;
122 import android.widget.AdapterView;
123 import android.widget.Toast;
124 import android.widget.Toolbar;
126 import java.io.FileDescriptor;
127 import java.io.PrintWriter;
128 import java.lang.annotation.Retention;
129 import java.lang.annotation.RetentionPolicy;
130 import java.util.ArrayList;
131 import java.util.HashMap;
132 import java.util.List;
134 import static android.os.Build.VERSION_CODES.O;
135 import static java.lang.Character.MIN_VALUE;
138 * An activity is a single, focused thing that the user can do. Almost all
139 * activities interact with the user, so the Activity class takes care of
140 * creating a window for you in which you can place your UI with
141 * {@link #setContentView}. While activities are often presented to the user
142 * as full-screen windows, they can also be used in other ways: as floating
143 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
144 * or embedded inside of another activity (using {@link ActivityGroup}).
146 * There are two methods almost all subclasses of Activity will implement:
149 * <li> {@link #onCreate} is where you initialize your activity. Most
150 * importantly, here you will usually call {@link #setContentView(int)}
151 * with a layout resource defining your UI, and using {@link #findViewById}
152 * to retrieve the widgets in that UI that you need to interact with
155 * <li> {@link #onPause} is where you deal with the user leaving your
156 * activity. Most importantly, any changes made by the user should at this
157 * point be committed (usually to the
158 * {@link android.content.ContentProvider} holding the data).
161 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
162 * activity classes must have a corresponding
163 * {@link android.R.styleable#AndroidManifestActivity <activity>}
164 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
166 * <p>Topics covered here:
168 * <li><a href="#Fragments">Fragments</a>
169 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
170 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
171 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
172 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
173 * <li><a href="#Permissions">Permissions</a>
174 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
177 * <div class="special reference">
178 * <h3>Developer Guides</h3>
179 * <p>The Activity class is an important part of an application's overall lifecycle,
180 * and the way activities are launched and put together is a fundamental
181 * part of the platform's application model. For a detailed perspective on the structure of an
182 * Android application and how activities behave, please read the
183 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
184 * <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
185 * developer guides.</p>
187 * <p>You can also find a detailed discussion about how to create activities in the
188 * <a href="{@docRoot}guide/components/activities.html">Activities</a>
189 * developer guide.</p>
192 * <a name="Fragments"></a>
195 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
196 * implementations can make use of the {@link Fragment} class to better
197 * modularize their code, build more sophisticated user interfaces for larger
198 * screens, and help scale their application between small and large screens.
200 * <a name="ActivityLifecycle"></a>
201 * <h3>Activity Lifecycle</h3>
203 * <p>Activities in the system are managed as an <em>activity stack</em>.
204 * When a new activity is started, it is placed on the top of the stack
205 * and becomes the running activity -- the previous activity always remains
206 * below it in the stack, and will not come to the foreground again until
207 * the new activity exits.</p>
209 * <p>An activity has essentially four states:</p>
211 * <li> If an activity is in the foreground of the screen (at the top of
213 * it is <em>active</em> or <em>running</em>. </li>
214 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
215 * or transparent activity has focus on top of your activity), it
216 * is <em>paused</em>. A paused activity is completely alive (it
217 * maintains all state and member information and remains attached to
218 * the window manager), but can be killed by the system in extreme
219 * low memory situations.
220 * <li>If an activity is completely obscured by another activity,
221 * it is <em>stopped</em>. It still retains all state and member information,
222 * however, it is no longer visible to the user so its window is hidden
223 * and it will often be killed by the system when memory is needed
225 * <li>If an activity is paused or stopped, the system can drop the activity
226 * from memory by either asking it to finish, or simply killing its
227 * process. When it is displayed again to the user, it must be
228 * completely restarted and restored to its previous state.</li>
231 * <p>The following diagram shows the important state paths of an Activity.
232 * The square rectangles represent callback methods you can implement to
233 * perform operations when the Activity moves between states. The colored
234 * ovals are major states the Activity can be in.</p>
236 * <p><img src="../../../images/activity_lifecycle.png"
237 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
239 * <p>There are three key loops you may be interested in monitoring within your
243 * <li>The <b>entire lifetime</b> of an activity happens between the first call
244 * to {@link android.app.Activity#onCreate} through to a single final call
245 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
246 * of "global" state in onCreate(), and release all remaining resources in
247 * onDestroy(). For example, if it has a thread running in the background
248 * to download data from the network, it may create that thread in onCreate()
249 * and then stop the thread in onDestroy().
251 * <li>The <b>visible lifetime</b> of an activity happens between a call to
252 * {@link android.app.Activity#onStart} until a corresponding call to
253 * {@link android.app.Activity#onStop}. During this time the user can see the
254 * activity on-screen, though it may not be in the foreground and interacting
255 * with the user. Between these two methods you can maintain resources that
256 * are needed to show the activity to the user. For example, you can register
257 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
258 * that impact your UI, and unregister it in onStop() when the user no
259 * longer sees what you are displaying. The onStart() and onStop() methods
260 * can be called multiple times, as the activity becomes visible and hidden
263 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
264 * {@link android.app.Activity#onResume} until a corresponding call to
265 * {@link android.app.Activity#onPause}. During this time the activity is
266 * in front of all other activities and interacting with the user. An activity
267 * can frequently go between the resumed and paused states -- for example when
268 * the device goes to sleep, when an activity result is delivered, when a new
269 * intent is delivered -- so the code in these methods should be fairly
273 * <p>The entire lifecycle of an activity is defined by the following
274 * Activity methods. All of these are hooks that you can override
275 * to do appropriate work when the activity changes state. All
276 * activities will implement {@link android.app.Activity#onCreate}
277 * to do their initial setup; many will also implement
278 * {@link android.app.Activity#onPause} to commit changes to data and
279 * otherwise prepare to stop interacting with the user. You should always
280 * call up to your superclass when implementing these methods.</p>
283 * <pre class="prettyprint">
284 * public class Activity extends ApplicationContext {
285 * protected void onCreate(Bundle savedInstanceState);
287 * protected void onStart();
289 * protected void onRestart();
291 * protected void onResume();
293 * protected void onPause();
295 * protected void onStop();
297 * protected void onDestroy();
301 * <p>In general the movement through an activity's lifecycle looks like
304 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
305 * <colgroup align="left" span="3" />
306 * <colgroup align="left" />
307 * <colgroup align="center" />
308 * <colgroup align="center" />
311 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
315 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</td>
316 * <td>Called when the activity is first created.
317 * This is where you should do all of your normal static set up:
318 * create views, bind data to lists, etc. This method also
319 * provides you with a Bundle containing the activity's previously
320 * frozen state, if there was one.
321 * <p>Always followed by <code>onStart()</code>.</td>
322 * <td align="center">No</td>
323 * <td align="center"><code>onStart()</code></td>
326 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
327 * <td colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</td>
328 * <td>Called after your activity has been stopped, prior to it being
330 * <p>Always followed by <code>onStart()</code></td>
331 * <td align="center">No</td>
332 * <td align="center"><code>onStart()</code></td>
335 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</td>
336 * <td>Called when the activity is becoming visible to the user.
337 * <p>Followed by <code>onResume()</code> if the activity comes
338 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
339 * <td align="center">No</td>
340 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
343 * <tr><td rowspan="2" style="border-left: none;"> </td>
344 * <td align="left" border="0">{@link android.app.Activity#onResume onResume()}</td>
345 * <td>Called when the activity will start
346 * interacting with the user. At this point your activity is at
347 * the top of the activity stack, with user input going to it.
348 * <p>Always followed by <code>onPause()</code>.</td>
349 * <td align="center">No</td>
350 * <td align="center"><code>onPause()</code></td>
353 * <tr><td align="left" border="0">{@link android.app.Activity#onPause onPause()}</td>
354 * <td>Called when the system is about to start resuming a previous
355 * activity. This is typically used to commit unsaved changes to
356 * persistent data, stop animations and other things that may be consuming
357 * CPU, etc. Implementations of this method must be very quick because
358 * the next activity will not be resumed until this method returns.
359 * <p>Followed by either <code>onResume()</code> if the activity
360 * returns back to the front, or <code>onStop()</code> if it becomes
361 * invisible to the user.</td>
362 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
363 * <td align="center"><code>onResume()</code> or<br>
364 * <code>onStop()</code></td>
367 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</td>
368 * <td>Called when the activity is no longer visible to the user, because
369 * another activity has been resumed and is covering this one. This
370 * may happen either because a new activity is being started, an existing
371 * one is being brought in front of this one, or this one is being
373 * <p>Followed by either <code>onRestart()</code> if
374 * this activity is coming back to interact with the user, or
375 * <code>onDestroy()</code> if this activity is going away.</td>
376 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
377 * <td align="center"><code>onRestart()</code> or<br>
378 * <code>onDestroy()</code></td>
381 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</td>
382 * <td>The final call you receive before your
383 * activity is destroyed. This can happen either because the
384 * activity is finishing (someone called {@link Activity#finish} on
385 * it, or because the system is temporarily destroying this
386 * instance of the activity to save space. You can distinguish
387 * between these two scenarios with the {@link
388 * Activity#isFinishing} method.</td>
389 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
390 * <td align="center"><em>nothing</em></td>
395 * <p>Note the "Killable" column in the above table -- for those methods that
396 * are marked as being killable, after that method returns the process hosting the
397 * activity may be killed by the system <em>at any time</em> without another line
398 * of its code being executed. Because of this, you should use the
399 * {@link #onPause} method to write any persistent data (such as user edits)
400 * to storage. In addition, the method
401 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
402 * in such a background state, allowing you to save away any dynamic instance
403 * state in your activity into the given Bundle, to be later received in
404 * {@link #onCreate} if the activity needs to be re-created.
405 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
406 * section for more information on how the lifecycle of a process is tied
407 * to the activities it is hosting. Note that it is important to save
408 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
409 * because the latter is not part of the lifecycle callbacks, so will not
410 * be called in every situation as described in its documentation.</p>
412 * <p class="note">Be aware that these semantics will change slightly between
413 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
414 * vs. those targeting prior platforms. Starting with Honeycomb, an application
415 * is not in the killable state until its {@link #onStop} has returned. This
416 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
417 * safely called after {@link #onPause()} and allows and application to safely
418 * wait until {@link #onStop()} to save persistent state.</p>
420 * <p>For those methods that are not marked as being killable, the activity's
421 * process will not be killed by the system starting from the time the method
422 * is called and continuing after it returns. Thus an activity is in the killable
423 * state, for example, between after <code>onPause()</code> to the start of
424 * <code>onResume()</code>.</p>
426 * <a name="ConfigurationChanges"></a>
427 * <h3>Configuration Changes</h3>
429 * <p>If the configuration of the device (as defined by the
430 * {@link Configuration Resources.Configuration} class) changes,
431 * then anything displaying a user interface will need to update to match that
432 * configuration. Because Activity is the primary mechanism for interacting
433 * with the user, it includes special support for handling configuration
436 * <p>Unless you specify otherwise, a configuration change (such as a change
437 * in screen orientation, language, input devices, etc) will cause your
438 * current activity to be <em>destroyed</em>, going through the normal activity
439 * lifecycle process of {@link #onPause},
440 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
441 * had been in the foreground or visible to the user, once {@link #onDestroy} is
442 * called in that instance then a new instance of the activity will be
443 * created, with whatever savedInstanceState the previous instance had generated
444 * from {@link #onSaveInstanceState}.</p>
446 * <p>This is done because any application resource,
447 * including layout files, can change based on any configuration value. Thus
448 * the only safe way to handle a configuration change is to re-retrieve all
449 * resources, including layouts, drawables, and strings. Because activities
450 * must already know how to save their state and re-create themselves from
451 * that state, this is a convenient way to have an activity restart itself
452 * with a new configuration.</p>
454 * <p>In some special cases, you may want to bypass restarting of your
455 * activity based on one or more types of configuration changes. This is
456 * done with the {@link android.R.attr#configChanges android:configChanges}
457 * attribute in its manifest. For any types of configuration changes you say
458 * that you handle there, you will receive a call to your current activity's
459 * {@link #onConfigurationChanged} method instead of being restarted. If
460 * a configuration change involves any that you do not handle, however, the
461 * activity will still be restarted and {@link #onConfigurationChanged}
462 * will not be called.</p>
464 * <a name="StartingActivities"></a>
465 * <h3>Starting Activities and Getting Results</h3>
467 * <p>The {@link android.app.Activity#startActivity}
468 * method is used to start a
469 * new activity, which will be placed at the top of the activity stack. It
470 * takes a single argument, an {@link android.content.Intent Intent},
471 * which describes the activity
472 * to be executed.</p>
474 * <p>Sometimes you want to get a result back from an activity when it
475 * ends. For example, you may start an activity that lets the user pick
476 * a person in a list of contacts; when it ends, it returns the person
477 * that was selected. To do this, you call the
478 * {@link android.app.Activity#startActivityForResult(Intent, int)}
479 * version with a second integer parameter identifying the call. The result
480 * will come back through your {@link android.app.Activity#onActivityResult}
483 * <p>When an activity exits, it can call
484 * {@link android.app.Activity#setResult(int)}
485 * to return data back to its parent. It must always supply a result code,
486 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
487 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
488 * return back an Intent containing any additional data it wants. All of this
489 * information appears back on the
490 * parent's <code>Activity.onActivityResult()</code>, along with the integer
491 * identifier it originally supplied.</p>
493 * <p>If a child activity fails for any reason (such as crashing), the parent
494 * activity will receive a result with the code RESULT_CANCELED.</p>
496 * <pre class="prettyprint">
497 * public class MyActivity extends Activity {
500 * static final int PICK_CONTACT_REQUEST = 0;
502 * public boolean onKeyDown(int keyCode, KeyEvent event) {
503 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
504 * // When the user center presses, let them pick a contact.
505 * startActivityForResult(
506 * new Intent(Intent.ACTION_PICK,
507 * new Uri("content://contacts")),
508 * PICK_CONTACT_REQUEST);
514 * protected void onActivityResult(int requestCode, int resultCode,
516 * if (requestCode == PICK_CONTACT_REQUEST) {
517 * if (resultCode == RESULT_OK) {
518 * // A contact was picked. Here we will just display it
520 * startActivity(new Intent(Intent.ACTION_VIEW, data));
527 * <a name="SavingPersistentState"></a>
528 * <h3>Saving Persistent State</h3>
530 * <p>There are generally two kinds of persistent state than an activity
531 * will deal with: shared document-like data (typically stored in a SQLite
532 * database using a {@linkplain android.content.ContentProvider content provider})
533 * and internal state such as user preferences.</p>
535 * <p>For content provider data, we suggest that activities use a
536 * "edit in place" user model. That is, any edits a user makes are effectively
537 * made immediately without requiring an additional confirmation step.
538 * Supporting this model is generally a simple matter of following two rules:</p>
541 * <li> <p>When creating a new document, the backing database entry or file for
542 * it is created immediately. For example, if the user chooses to write
543 * a new e-mail, a new entry for that e-mail is created as soon as they
544 * start entering data, so that if they go to any other activity after
545 * that point this e-mail will now appear in the list of drafts.</p>
546 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
547 * commit to the backing content provider or file any changes the user
548 * has made. This ensures that those changes will be seen by any other
549 * activity that is about to run. You will probably want to commit
550 * your data even more aggressively at key times during your
551 * activity's lifecycle: for example before starting a new
552 * activity, before finishing your own activity, when the user
553 * switches between input fields, etc.</p>
556 * <p>This model is designed to prevent data loss when a user is navigating
557 * between activities, and allows the system to safely kill an activity (because
558 * system resources are needed somewhere else) at any time after it has been
559 * paused. Note this implies
560 * that the user pressing BACK from your activity does <em>not</em>
561 * mean "cancel" -- it means to leave the activity with its current contents
562 * saved away. Canceling edits in an activity must be provided through
563 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
565 * <p>See the {@linkplain android.content.ContentProvider content package} for
566 * more information about content providers. These are a key aspect of how
567 * different activities invoke and propagate data between themselves.</p>
569 * <p>The Activity class also provides an API for managing internal persistent state
570 * associated with an activity. This can be used, for example, to remember
571 * the user's preferred initial display in a calendar (day view or week view)
572 * or the user's default home page in a web browser.</p>
574 * <p>Activity persistent state is managed
575 * with the method {@link #getPreferences},
576 * allowing you to retrieve and
577 * modify a set of name/value pairs associated with the activity. To use
578 * preferences that are shared across multiple application components
579 * (activities, receivers, services, providers), you can use the underlying
580 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
581 * to retrieve a preferences
582 * object stored under a specific name.
583 * (Note that it is not possible to share settings data across application
584 * packages -- for that you will need a content provider.)</p>
586 * <p>Here is an excerpt from a calendar activity that stores the user's
587 * preferred view mode in its persistent settings:</p>
589 * <pre class="prettyprint">
590 * public class CalendarActivity extends Activity {
593 * static final int DAY_VIEW_MODE = 0;
594 * static final int WEEK_VIEW_MODE = 1;
596 * private SharedPreferences mPrefs;
597 * private int mCurViewMode;
599 * protected void onCreate(Bundle savedInstanceState) {
600 * super.onCreate(savedInstanceState);
602 * SharedPreferences mPrefs = getSharedPreferences();
603 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
606 * protected void onPause() {
609 * SharedPreferences.Editor ed = mPrefs.edit();
610 * ed.putInt("view_mode", mCurViewMode);
616 * <a name="Permissions"></a>
617 * <h3>Permissions</h3>
619 * <p>The ability to start a particular Activity can be enforced when it is
621 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
622 * tag. By doing so, other applications will need to declare a corresponding
623 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
624 * element in their own manifest to be able to start that activity.
626 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
627 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
628 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
629 * Activity access to the specific URIs in the Intent. Access will remain
630 * until the Activity has finished (it will remain across the hosting
631 * process being killed and other temporary destruction). As of
632 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
633 * was already created and a new Intent is being delivered to
634 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
635 * to the existing ones it holds.
637 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
638 * document for more information on permissions and security in general.
640 * <a name="ProcessLifecycle"></a>
641 * <h3>Process Lifecycle</h3>
643 * <p>The Android system attempts to keep application process around for as
644 * long as possible, but eventually will need to remove old processes when
645 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
646 * Lifecycle</a>, the decision about which process to remove is intimately
647 * tied to the state of the user's interaction with it. In general, there
648 * are four states a process can be in based on the activities running in it,
649 * listed here in order of importance. The system will kill less important
650 * processes (the last ones) before it resorts to killing more important
651 * processes (the first ones).
654 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
655 * that the user is currently interacting with) is considered the most important.
656 * Its process will only be killed as a last resort, if it uses more memory
657 * than is available on the device. Generally at this point the device has
658 * reached a memory paging state, so this is required in order to keep the user
659 * interface responsive.
660 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
661 * but not in the foreground, such as one sitting behind a foreground dialog)
662 * is considered extremely important and will not be killed unless that is
663 * required to keep the foreground activity running.
664 * <li> <p>A <b>background activity</b> (an activity that is not visible to
665 * the user and has been paused) is no longer critical, so the system may
666 * safely kill its process to reclaim memory for other foreground or
667 * visible processes. If its process needs to be killed, when the user navigates
668 * back to the activity (making it visible on the screen again), its
669 * {@link #onCreate} method will be called with the savedInstanceState it had previously
670 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
671 * state as the user last left it.
672 * <li> <p>An <b>empty process</b> is one hosting no activities or other
673 * application components (such as {@link Service} or
674 * {@link android.content.BroadcastReceiver} classes). These are killed very
675 * quickly by the system as memory becomes low. For this reason, any
676 * background operation you do outside of an activity must be executed in the
677 * context of an activity BroadcastReceiver or Service to ensure that the system
678 * knows it needs to keep your process around.
681 * <p>Sometimes an Activity may need to do a long-running operation that exists
682 * independently of the activity lifecycle itself. An example may be a camera
683 * application that allows you to upload a picture to a web site. The upload
684 * may take a long time, and the application should allow the user to leave
685 * the application while it is executing. To accomplish this, your Activity
686 * should start a {@link Service} in which the upload takes place. This allows
687 * the system to properly prioritize your process (considering it to be more
688 * important than other non-visible applications) for the duration of the
689 * upload, independent of whether the original activity is paused, stopped,
692 public class Activity extends ContextThemeWrapper
693 implements LayoutInflater.Factory2,
694 Window.Callback, KeyEvent.Callback,
695 OnCreateContextMenuListener, ComponentCallbacks2,
696 Window.OnWindowDismissedCallback, WindowControllerCallback,
697 AutofillManager.AutofillClient {
698 private static final String TAG = "Activity";
699 private static final boolean DEBUG_LIFECYCLE = false;
701 /** Standard activity result: operation canceled. */
702 public static final int RESULT_CANCELED = 0;
703 /** Standard activity result: operation succeeded. */
704 public static final int RESULT_OK = -1;
705 /** Start of user-defined activity results. */
706 public static final int RESULT_FIRST_USER = 1;
708 /** @hide Task isn't finished when activity is finished */
709 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0;
711 * @hide Task is finished if the finishing activity is the root of the task. To preserve the
712 * past behavior the task is also removed from recents.
714 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1;
716 * @hide Task is finished along with the finishing activity, but it is not removed from
719 public static final int FINISH_TASK_WITH_ACTIVITY = 2;
721 static final String FRAGMENTS_TAG = "android:fragments";
722 private static final String LAST_ACCESSIBILITY_ID = "android:lastAccessibilityId";
724 private static final String AUTOFILL_RESET_NEEDED = "@android:autofillResetNeeded";
725 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
726 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
727 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
728 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
729 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
730 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
731 "android:hasCurrentPermissionsRequest";
733 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
734 private static final String AUTO_FILL_AUTH_WHO_PREFIX = "@android:autoFillAuth:";
736 private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
738 private static class ManagedDialog {
742 private SparseArray<ManagedDialog> mManagedDialogs;
744 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
745 private Instrumentation mInstrumentation;
746 private IBinder mToken;
748 /*package*/ String mEmbeddedID;
749 private Application mApplication;
750 /*package*/ Intent mIntent;
751 /*package*/ String mReferrer;
752 private ComponentName mComponent;
753 /*package*/ ActivityInfo mActivityInfo;
754 /*package*/ ActivityThread mMainThread;
757 /*package*/ boolean mResumed;
758 /*package*/ boolean mStopped;
760 boolean mStartedActivity;
761 private boolean mDestroyed;
762 private boolean mDoReportFullyDrawn = true;
763 /** true if the activity is going through a transient pause */
764 /*package*/ boolean mTemporaryPause = false;
765 /** true if the activity is being destroyed in order to recreate it with a new configuration */
766 /*package*/ boolean mChangingConfigurations = false;
767 /*package*/ int mConfigChangeFlags;
768 /*package*/ Configuration mCurrentConfig;
769 private SearchManager mSearchManager;
770 private MenuInflater mMenuInflater;
772 /** The autofill manager. Always access via {@link #getAutofillManager()}. */
773 @Nullable private AutofillManager mAutofillManager;
775 static final class NonConfigurationInstances {
777 HashMap<String, Object> children;
778 FragmentManagerNonConfig fragments;
779 ArrayMap<String, LoaderManager> loaders;
780 VoiceInteractor voiceInteractor;
782 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
784 private Window mWindow;
786 private WindowManager mWindowManager;
787 /*package*/ View mDecor = null;
788 /*package*/ boolean mWindowAdded = false;
789 /*package*/ boolean mVisibleFromServer = false;
790 /*package*/ boolean mVisibleFromClient = true;
791 /*package*/ ActionBar mActionBar = null;
792 private boolean mEnableDefaultActionBarUp;
794 private VoiceInteractor mVoiceInteractor;
796 private CharSequence mTitle;
797 private int mTitleColor = 0;
799 // we must have a handler before the FragmentController is constructed
800 final Handler mHandler = new Handler();
801 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
803 // Most recent call to requestVisibleBehind().
805 boolean mVisibleBehind;
807 private static final class ManagedCursor {
808 ManagedCursor(Cursor cursor) {
814 private final Cursor mCursor;
815 private boolean mReleased;
816 private boolean mUpdated;
819 @GuardedBy("mManagedCursors")
820 private final ArrayList<ManagedCursor> mManagedCursors = new ArrayList<>();
823 int mResultCode = RESULT_CANCELED;
825 Intent mResultData = null;
827 private TranslucentConversionListener mTranslucentCallback;
828 private boolean mChangeCanvasToTranslucent;
830 private SearchEvent mSearchEvent;
832 private boolean mTitleReady = false;
833 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
835 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
836 private SpannableStringBuilder mDefaultKeySsb = null;
838 private ActivityManager.TaskDescription mTaskDescription =
839 new ActivityManager.TaskDescription();
841 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
843 @SuppressWarnings("unused")
844 private final Object mInstanceTracker = StrictMode.trackActivity(this);
846 private Thread mUiThread;
848 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
849 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
850 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
852 private boolean mHasCurrentPermissionsRequest;
854 private boolean mAutoFillResetNeeded;
856 /** The last accessibility id that was returned from {@link #getNextAccessibilityId()} */
857 private int mLastAccessibilityId = View.LAST_APP_ACCESSIBILITY_ID;
859 private AutofillPopupWindow mAutofillPopupWindow;
861 private static native String getDlWarning();
863 /** Return the intent that started this activity. */
864 public Intent getIntent() {
869 * Change the intent returned by {@link #getIntent}. This holds a
870 * reference to the given intent; it does not copy it. Often used in
871 * conjunction with {@link #onNewIntent}.
873 * @param newIntent The new Intent object to return from getIntent
878 public void setIntent(Intent newIntent) {
882 /** Return the application that owns this activity. */
883 public final Application getApplication() {
887 /** Is this activity embedded inside of another activity? */
888 public final boolean isChild() {
889 return mParent != null;
892 /** Return the parent activity if this view is an embedded child. */
893 public final Activity getParent() {
897 /** Retrieve the window manager for showing custom windows. */
898 public WindowManager getWindowManager() {
899 return mWindowManager;
903 * Retrieve the current {@link android.view.Window} for the activity.
904 * This can be used to directly access parts of the Window API that
905 * are not available through Activity/Screen.
907 * @return Window The current window, or null if the activity is not
910 public Window getWindow() {
915 * Return the LoaderManager for this activity, creating it if needed.
917 public LoaderManager getLoaderManager() {
918 return mFragments.getLoaderManager();
922 * Calls {@link android.view.Window#getCurrentFocus} on the
923 * Window of this Activity to return the currently focused view.
925 * @return View The current View with focus or null.
928 * @see android.view.Window#getCurrentFocus
931 public View getCurrentFocus() {
932 return mWindow != null ? mWindow.getCurrentFocus() : null;
936 * (Create and) return the autofill manager
938 * @return The autofill manager
940 @NonNull private AutofillManager getAutofillManager() {
941 if (mAutofillManager == null) {
942 mAutofillManager = getSystemService(AutofillManager.class);
945 return mAutofillManager;
949 * Called when the activity is starting. This is where most initialization
950 * should go: calling {@link #setContentView(int)} to inflate the
951 * activity's UI, using {@link #findViewById} to programmatically interact
952 * with widgets in the UI, calling
953 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
954 * cursors for data being displayed, etc.
956 * <p>You can call {@link #finish} from within this function, in
957 * which case onDestroy() will be immediately called without any of the rest
958 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
959 * {@link #onPause}, etc) executing.
961 * <p><em>Derived classes must call through to the super class's
962 * implementation of this method. If they do not, an exception will be
965 * @param savedInstanceState If the activity is being re-initialized after
966 * previously being shut down then this Bundle contains the data it most
967 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
970 * @see #onSaveInstanceState
971 * @see #onRestoreInstanceState
976 protected void onCreate(@Nullable Bundle savedInstanceState) {
977 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
979 if (getApplicationInfo().targetSdkVersion > O && mActivityInfo.isFixedOrientation()) {
980 final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
981 final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
984 if (isTranslucentOrFloating) {
985 throw new IllegalStateException(
986 "Only fullscreen opaque activities can request orientation");
990 if (mLastNonConfigurationInstances != null) {
991 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
993 if (mActivityInfo.parentActivityName != null) {
994 if (mActionBar == null) {
995 mEnableDefaultActionBarUp = true;
997 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
1000 if (savedInstanceState != null) {
1001 mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
1002 mLastAccessibilityId = savedInstanceState.getInt(LAST_ACCESSIBILITY_ID, View.NO_ID);
1004 if (mAutoFillResetNeeded) {
1005 getAutofillManager().onCreate(savedInstanceState);
1008 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
1009 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
1010 ? mLastNonConfigurationInstances.fragments : null);
1012 mFragments.dispatchCreate();
1013 getApplication().dispatchActivityCreated(this, savedInstanceState);
1014 if (mVoiceInteractor != null) {
1015 mVoiceInteractor.attachActivity(this);
1021 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
1022 * the attribute {@link android.R.attr#persistableMode} set to
1023 * <code>persistAcrossReboots</code>.
1025 * @param savedInstanceState if the activity is being re-initialized after
1026 * previously being shut down then this Bundle contains the data it most
1027 * recently supplied in {@link #onSaveInstanceState}.
1028 * <b><i>Note: Otherwise it is null.</i></b>
1029 * @param persistentState if the activity is being re-initialized after
1030 * previously being shut down or powered off then this Bundle contains the data it most
1031 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
1032 * <b><i>Note: Otherwise it is null.</i></b>
1034 * @see #onCreate(android.os.Bundle)
1036 * @see #onSaveInstanceState
1037 * @see #onRestoreInstanceState
1038 * @see #onPostCreate
1040 public void onCreate(@Nullable Bundle savedInstanceState,
1041 @Nullable PersistableBundle persistentState) {
1042 onCreate(savedInstanceState);
1046 * The hook for {@link ActivityThread} to restore the state of this activity.
1048 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1049 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1051 * @param savedInstanceState contains the saved state
1053 final void performRestoreInstanceState(Bundle savedInstanceState) {
1054 onRestoreInstanceState(savedInstanceState);
1055 restoreManagedDialogs(savedInstanceState);
1059 * The hook for {@link ActivityThread} to restore the state of this activity.
1061 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1062 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1064 * @param savedInstanceState contains the saved state
1065 * @param persistentState contains the persistable saved state
1067 final void performRestoreInstanceState(Bundle savedInstanceState,
1068 PersistableBundle persistentState) {
1069 onRestoreInstanceState(savedInstanceState, persistentState);
1070 if (savedInstanceState != null) {
1071 restoreManagedDialogs(savedInstanceState);
1076 * This method is called after {@link #onStart} when the activity is
1077 * being re-initialized from a previously saved state, given here in
1078 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
1079 * to restore their state, but it is sometimes convenient to do it here
1080 * after all of the initialization has been done or to allow subclasses to
1081 * decide whether to use your default implementation. The default
1082 * implementation of this method performs a restore of any view state that
1083 * had previously been frozen by {@link #onSaveInstanceState}.
1085 * <p>This method is called between {@link #onStart} and
1086 * {@link #onPostCreate}.
1088 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1091 * @see #onPostCreate
1093 * @see #onSaveInstanceState
1095 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1096 if (mWindow != null) {
1097 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1098 if (windowState != null) {
1099 mWindow.restoreHierarchyState(windowState);
1105 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1106 * created with the attribute {@link android.R.attr#persistableMode} set to
1107 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1108 * came from the restored PersistableBundle first
1109 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1111 * <p>This method is called between {@link #onStart} and
1112 * {@link #onPostCreate}.
1114 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1116 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1117 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1119 * @see #onRestoreInstanceState(Bundle)
1121 * @see #onPostCreate
1123 * @see #onSaveInstanceState
1125 public void onRestoreInstanceState(Bundle savedInstanceState,
1126 PersistableBundle persistentState) {
1127 if (savedInstanceState != null) {
1128 onRestoreInstanceState(savedInstanceState);
1133 * Restore the state of any saved managed dialogs.
1135 * @param savedInstanceState The bundle to restore from.
1137 private void restoreManagedDialogs(Bundle savedInstanceState) {
1138 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1143 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1144 final int numDialogs = ids.length;
1145 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1146 for (int i = 0; i < numDialogs; i++) {
1147 final Integer dialogId = ids[i];
1148 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1149 if (dialogState != null) {
1150 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1151 // so tell createDialog() not to do it, otherwise we get an exception
1152 final ManagedDialog md = new ManagedDialog();
1153 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1154 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1155 if (md.mDialog != null) {
1156 mManagedDialogs.put(dialogId, md);
1157 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1158 md.mDialog.onRestoreInstanceState(dialogState);
1164 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1165 final Dialog dialog = onCreateDialog(dialogId, args);
1166 if (dialog == null) {
1169 dialog.dispatchOnCreate(state);
1173 private static String savedDialogKeyFor(int key) {
1174 return SAVED_DIALOG_KEY_PREFIX + key;
1177 private static String savedDialogArgsKeyFor(int key) {
1178 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1182 * Called when activity start-up is complete (after {@link #onStart}
1183 * and {@link #onRestoreInstanceState} have been called). Applications will
1184 * generally not implement this method; it is intended for system
1185 * classes to do final initialization after application code has run.
1187 * <p><em>Derived classes must call through to the super class's
1188 * implementation of this method. If they do not, an exception will be
1191 * @param savedInstanceState If the activity is being re-initialized after
1192 * previously being shut down then this Bundle contains the data it most
1193 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1197 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1200 onTitleChanged(getTitle(), getTitleColor());
1207 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1208 * created with the attribute {@link android.R.attr#persistableMode} set to
1209 * <code>persistAcrossReboots</code>.
1211 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1212 * @param persistentState The data caming from the PersistableBundle first
1213 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1217 public void onPostCreate(@Nullable Bundle savedInstanceState,
1218 @Nullable PersistableBundle persistentState) {
1219 onPostCreate(savedInstanceState);
1223 * Called after {@link #onCreate} — or after {@link #onRestart} when
1224 * the activity had been stopped, but is now again being displayed to the
1225 * user. It will be followed by {@link #onResume}.
1227 * <p><em>Derived classes must call through to the super class's
1228 * implementation of this method. If they do not, an exception will be
1236 protected void onStart() {
1237 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1240 mFragments.doLoaderStart();
1242 getApplication().dispatchActivityStarted(this);
1244 if (mAutoFillResetNeeded) {
1245 AutofillManager afm = getAutofillManager();
1247 afm.onVisibleForAutofill();
1253 * Called after {@link #onStop} when the current activity is being
1254 * re-displayed to the user (the user has navigated back to it). It will
1255 * be followed by {@link #onStart} and then {@link #onResume}.
1257 * <p>For activities that are using raw {@link Cursor} objects (instead of
1258 * creating them through
1259 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1260 * this is usually the place
1261 * where the cursor should be requeried (because you had deactivated it in
1264 * <p><em>Derived classes must call through to the super class's
1265 * implementation of this method. If they do not, an exception will be
1273 protected void onRestart() {
1278 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1279 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1280 * to give the activity a hint that its state is no longer saved -- it will generally
1281 * be called after {@link #onSaveInstanceState} and prior to the activity being
1282 * resumed/started again.
1284 public void onStateNotSaved() {
1288 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1289 * {@link #onPause}, for your activity to start interacting with the user.
1290 * This is a good place to begin animations, open exclusive-access devices
1291 * (such as the camera), etc.
1293 * <p>Keep in mind that onResume is not the best indicator that your activity
1294 * is visible to the user; a system window such as the keyguard may be in
1295 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1296 * activity is visible to the user (for example, to resume a game).
1298 * <p><em>Derived classes must call through to the super class's
1299 * implementation of this method. If they do not, an exception will be
1302 * @see #onRestoreInstanceState
1304 * @see #onPostResume
1308 protected void onResume() {
1309 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1310 getApplication().dispatchActivityResumed(this);
1311 mActivityTransitionState.onResume(this, isTopOfTask());
1316 * Called when activity resume is complete (after {@link #onResume} has
1317 * been called). Applications will generally not implement this method;
1318 * it is intended for system classes to do final setup after application
1319 * resume code has run.
1321 * <p><em>Derived classes must call through to the super class's
1322 * implementation of this method. If they do not, an exception will be
1328 protected void onPostResume() {
1329 final Window win = getWindow();
1330 if (win != null) win.makeActive();
1331 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1335 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
1336 if (mVoiceInteractor != null) {
1337 for (Request activeRequest: mVoiceInteractor.getActiveRequests()) {
1338 activeRequest.cancel();
1339 activeRequest.clear();
1342 if (voiceInteractor == null) {
1343 mVoiceInteractor = null;
1345 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
1351 * Gets the next accessibility ID.
1353 * <p>All IDs will be bigger than {@link View#LAST_APP_ACCESSIBILITY_ID}. All IDs returned
1356 * @return A ID that is unique in the activity
1361 public int getNextAccessibilityId() {
1362 if (mLastAccessibilityId == Integer.MAX_VALUE - 1) {
1363 mLastAccessibilityId = View.LAST_APP_ACCESSIBILITY_ID;
1366 mLastAccessibilityId++;
1368 return mLastAccessibilityId;
1372 * Check whether this activity is running as part of a voice interaction with the user.
1373 * If true, it should perform its interaction with the user through the
1374 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1376 public boolean isVoiceInteraction() {
1377 return mVoiceInteractor != null;
1381 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1382 * of a voice interaction. That is, returns true if this activity was directly
1383 * started by the voice interaction service as the initiation of a voice interaction.
1384 * Otherwise, for example if it was started by another activity while under voice
1385 * interaction, returns false.
1387 public boolean isVoiceInteractionRoot() {
1389 return mVoiceInteractor != null
1390 && ActivityManager.getService().isRootVoiceInteraction(mToken);
1391 } catch (RemoteException e) {
1397 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1398 * interact with this activity.
1400 public VoiceInteractor getVoiceInteractor() {
1401 return mVoiceInteractor;
1405 * Queries whether the currently enabled voice interaction service supports returning
1406 * a voice interactor for use by the activity. This is valid only for the duration of the
1409 * @return whether the current voice interaction service supports local voice interaction
1411 public boolean isLocalVoiceInteractionSupported() {
1413 return ActivityManager.getService().supportsLocalVoiceInteraction();
1414 } catch (RemoteException re) {
1420 * Starts a local voice interaction session. When ready,
1421 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
1422 * to the registered voice interaction service.
1423 * @param privateOptions a Bundle of private arguments to the current voice interaction service
1425 public void startLocalVoiceInteraction(Bundle privateOptions) {
1427 ActivityManager.getService().startLocalVoiceInteraction(mToken, privateOptions);
1428 } catch (RemoteException re) {
1433 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
1434 * voice interaction session being started. You can now retrieve a voice interactor using
1435 * {@link #getVoiceInteractor()}.
1437 public void onLocalVoiceInteractionStarted() {
1441 * Callback to indicate that the local voice interaction has stopped either
1442 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
1443 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
1444 * is no longer valid after this.
1446 public void onLocalVoiceInteractionStopped() {
1450 * Request to terminate the current voice interaction that was previously started
1451 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
1452 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
1454 public void stopLocalVoiceInteraction() {
1456 ActivityManager.getService().stopLocalVoiceInteraction(mToken);
1457 } catch (RemoteException re) {
1462 * This is called for activities that set launchMode to "singleTop" in
1463 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1464 * flag when calling {@link #startActivity}. In either case, when the
1465 * activity is re-launched while at the top of the activity stack instead
1466 * of a new instance of the activity being started, onNewIntent() will be
1467 * called on the existing instance with the Intent that was used to
1470 * <p>An activity will always be paused before receiving a new intent, so
1471 * you can count on {@link #onResume} being called after this method.
1473 * <p>Note that {@link #getIntent} still returns the original Intent. You
1474 * can use {@link #setIntent} to update it to this new Intent.
1476 * @param intent The new intent that was started for the activity.
1482 protected void onNewIntent(Intent intent) {
1486 * The hook for {@link ActivityThread} to save the state of this activity.
1488 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1489 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1491 * @param outState The bundle to save the state to.
1493 final void performSaveInstanceState(Bundle outState) {
1494 onSaveInstanceState(outState);
1495 saveManagedDialogs(outState);
1496 mActivityTransitionState.saveState(outState);
1497 storeHasCurrentPermissionRequest(outState);
1498 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1502 * The hook for {@link ActivityThread} to save the state of this activity.
1504 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1505 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1507 * @param outState The bundle to save the state to.
1508 * @param outPersistentState The bundle to save persistent state to.
1510 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1511 onSaveInstanceState(outState, outPersistentState);
1512 saveManagedDialogs(outState);
1513 storeHasCurrentPermissionRequest(outState);
1514 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1515 ", " + outPersistentState);
1519 * Called to retrieve per-instance state from an activity before being killed
1520 * so that the state can be restored in {@link #onCreate} or
1521 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1522 * will be passed to both).
1524 * <p>This method is called before an activity may be killed so that when it
1525 * comes back some time in the future it can restore its state. For example,
1526 * if activity B is launched in front of activity A, and at some point activity
1527 * A is killed to reclaim resources, activity A will have a chance to save the
1528 * current state of its user interface via this method so that when the user
1529 * returns to activity A, the state of the user interface can be restored
1530 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1532 * <p>Do not confuse this method with activity lifecycle callbacks such as
1533 * {@link #onPause}, which is always called when an activity is being placed
1534 * in the background or on its way to destruction, or {@link #onStop} which
1535 * is called before destruction. One example of when {@link #onPause} and
1536 * {@link #onStop} is called and not this method is when a user navigates back
1537 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1538 * on B because that particular instance will never be restored, so the
1539 * system avoids calling it. An example when {@link #onPause} is called and
1540 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1541 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1542 * killed during the lifetime of B since the state of the user interface of
1543 * A will stay intact.
1545 * <p>The default implementation takes care of most of the UI per-instance
1546 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1547 * view in the hierarchy that has an id, and by saving the id of the currently
1548 * focused view (all of which is restored by the default implementation of
1549 * {@link #onRestoreInstanceState}). If you override this method to save additional
1550 * information not captured by each individual view, you will likely want to
1551 * call through to the default implementation, otherwise be prepared to save
1552 * all of the state of each view yourself.
1554 * <p>If called, this method will occur before {@link #onStop}. There are
1555 * no guarantees about whether it will occur before or after {@link #onPause}.
1557 * @param outState Bundle in which to place your saved state.
1560 * @see #onRestoreInstanceState
1563 protected void onSaveInstanceState(Bundle outState) {
1564 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1566 outState.putInt(LAST_ACCESSIBILITY_ID, mLastAccessibilityId);
1567 Parcelable p = mFragments.saveAllState();
1569 outState.putParcelable(FRAGMENTS_TAG, p);
1571 if (mAutoFillResetNeeded) {
1572 outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
1573 getAutofillManager().onSaveInstanceState(outState);
1575 getApplication().dispatchActivitySaveInstanceState(this, outState);
1579 * This is the same as {@link #onSaveInstanceState} but is called for activities
1580 * created with the attribute {@link android.R.attr#persistableMode} set to
1581 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1582 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1583 * the first time that this activity is restarted following the next device reboot.
1585 * @param outState Bundle in which to place your saved state.
1586 * @param outPersistentState State which will be saved across reboots.
1588 * @see #onSaveInstanceState(Bundle)
1590 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1593 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1594 onSaveInstanceState(outState);
1598 * Save the state of any managed dialogs.
1600 * @param outState place to store the saved state.
1602 private void saveManagedDialogs(Bundle outState) {
1603 if (mManagedDialogs == null) {
1607 final int numDialogs = mManagedDialogs.size();
1608 if (numDialogs == 0) {
1612 Bundle dialogState = new Bundle();
1614 int[] ids = new int[mManagedDialogs.size()];
1616 // save each dialog's bundle, gather the ids
1617 for (int i = 0; i < numDialogs; i++) {
1618 final int key = mManagedDialogs.keyAt(i);
1620 final ManagedDialog md = mManagedDialogs.valueAt(i);
1621 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1622 if (md.mArgs != null) {
1623 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1627 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1628 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1633 * Called as part of the activity lifecycle when an activity is going into
1634 * the background, but has not (yet) been killed. The counterpart to
1635 * {@link #onResume}.
1637 * <p>When activity B is launched in front of activity A, this callback will
1638 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1639 * so be sure to not do anything lengthy here.
1641 * <p>This callback is mostly used for saving any persistent state the
1642 * activity is editing, to present a "edit in place" model to the user and
1643 * making sure nothing is lost if there are not enough resources to start
1644 * the new activity without first killing this one. This is also a good
1645 * place to do things like stop animations and other things that consume a
1646 * noticeable amount of CPU in order to make the switch to the next activity
1647 * as fast as possible, or to close resources that are exclusive access
1648 * such as the camera.
1650 * <p>In situations where the system needs more memory it may kill paused
1651 * processes to reclaim resources. Because of this, you should be sure
1652 * that all of your state is saved by the time you return from
1653 * this function. In general {@link #onSaveInstanceState} is used to save
1654 * per-instance state in the activity and this method is used to store
1655 * global persistent data (in content providers, files, etc.)
1657 * <p>After receiving this call you will usually receive a following call
1658 * to {@link #onStop} (after the next activity has been resumed and
1659 * displayed), however in some cases there will be a direct call back to
1660 * {@link #onResume} without going through the stopped state.
1662 * <p><em>Derived classes must call through to the super class's
1663 * implementation of this method. If they do not, an exception will be
1667 * @see #onSaveInstanceState
1671 protected void onPause() {
1672 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1673 getApplication().dispatchActivityPaused(this);
1678 * Called as part of the activity lifecycle when an activity is about to go
1679 * into the background as the result of user choice. For example, when the
1680 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1681 * when an incoming phone call causes the in-call Activity to be automatically
1682 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1683 * the activity being interrupted. In cases when it is invoked, this method
1684 * is called right before the activity's {@link #onPause} callback.
1686 * <p>This callback and {@link #onUserInteraction} are intended to help
1687 * activities manage status bar notifications intelligently; specifically,
1688 * for helping activities determine the proper time to cancel a notfication.
1690 * @see #onUserInteraction()
1692 protected void onUserLeaveHint() {
1696 * Generate a new thumbnail for this activity. This method is called before
1697 * pausing the activity, and should draw into <var>outBitmap</var> the
1698 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1699 * can use the given <var>canvas</var>, which is configured to draw into the
1700 * bitmap, for rendering if desired.
1702 * <p>The default implementation returns fails and does not draw a thumbnail;
1703 * this will result in the platform creating its own thumbnail if needed.
1705 * @param outBitmap The bitmap to contain the thumbnail.
1706 * @param canvas Can be used to render into the bitmap.
1708 * @return Return true if you have drawn into the bitmap; otherwise after
1709 * you return it will be filled with a default thumbnail.
1711 * @see #onCreateDescription
1712 * @see #onSaveInstanceState
1715 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1720 * Generate a new description for this activity. This method is called
1721 * before pausing the activity and can, if desired, return some textual
1722 * description of its current state to be displayed to the user.
1724 * <p>The default implementation returns null, which will cause you to
1725 * inherit the description from the previous activity. If all activities
1726 * return null, generally the label of the top activity will be used as the
1729 * @return A description of what the user is doing. It should be short and
1730 * sweet (only a few words).
1732 * @see #onCreateThumbnail
1733 * @see #onSaveInstanceState
1737 public CharSequence onCreateDescription() {
1742 * This is called when the user is requesting an assist, to build a full
1743 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1744 * application. You can override this method to place into the bundle anything
1745 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1746 * of the assist Intent.
1748 * <p>This function will be called after any global assist callbacks that had
1749 * been registered with {@link Application#registerOnProvideAssistDataListener
1750 * Application.registerOnProvideAssistDataListener}.
1752 public void onProvideAssistData(Bundle data) {
1756 * This is called when the user is requesting an assist, to provide references
1757 * to content related to the current activity. Before being called, the
1758 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1759 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1760 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1761 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1762 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1764 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1765 * context of the activity, and fill in its ClipData with additional content of
1766 * interest that the user is currently viewing. For example, an image gallery application
1767 * that has launched in to an activity allowing the user to swipe through pictures should
1768 * modify the intent to reference the current image they are looking it; such an
1769 * application when showing a list of pictures should add a ClipData that has
1770 * references to all of the pictures currently visible on screen.</p>
1772 * @param outContent The assist content to return.
1774 public void onProvideAssistContent(AssistContent outContent) {
1778 * Request the Keyboard Shortcuts screen to show up. This will trigger
1779 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
1781 public final void requestShowKeyboardShortcuts() {
1782 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
1783 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1784 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1788 * Dismiss the Keyboard Shortcuts screen.
1790 public final void dismissKeyboardShortcutsHelper() {
1791 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
1792 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1793 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1797 public void onProvideKeyboardShortcuts(
1798 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
1802 KeyboardShortcutGroup group = null;
1803 int menuSize = menu.size();
1804 for (int i = 0; i < menuSize; ++i) {
1805 final MenuItem item = menu.getItem(i);
1806 final CharSequence title = item.getTitle();
1807 final char alphaShortcut = item.getAlphabeticShortcut();
1808 final int alphaModifiers = item.getAlphabeticModifiers();
1809 if (title != null && alphaShortcut != MIN_VALUE) {
1810 if (group == null) {
1811 final int resource = mApplication.getApplicationInfo().labelRes;
1812 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
1814 group.addItem(new KeyboardShortcutInfo(
1815 title, alphaShortcut, alphaModifiers));
1818 if (group != null) {
1824 * Ask to have the current assistant shown to the user. This only works if the calling
1825 * activity is the current foreground activity. It is the same as calling
1826 * {@link android.service.voice.VoiceInteractionService#showSession
1827 * VoiceInteractionService.showSession} and requesting all of the possible context.
1828 * The receiver will always see
1829 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1830 * @return Returns true if the assistant was successfully invoked, else false. For example
1831 * false will be returned if the caller is not the current top activity.
1833 public boolean showAssist(Bundle args) {
1835 return ActivityManager.getService().showAssistFromActivity(mToken, args);
1836 } catch (RemoteException e) {
1842 * Called when you are no longer visible to the user. You will next
1843 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1844 * depending on later user activity.
1846 * <p><em>Derived classes must call through to the super class's
1847 * implementation of this method. If they do not, an exception will be
1852 * @see #onSaveInstanceState
1856 protected void onStop() {
1857 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1858 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1859 mActivityTransitionState.onStop();
1860 getApplication().dispatchActivityStopped(this);
1861 mTranslucentCallback = null;
1863 if (isFinishing() && mAutoFillResetNeeded) {
1864 getAutofillManager().commit();
1869 * Perform any final cleanup before an activity is destroyed. This can
1870 * happen either because the activity is finishing (someone called
1871 * {@link #finish} on it, or because the system is temporarily destroying
1872 * this instance of the activity to save space. You can distinguish
1873 * between these two scenarios with the {@link #isFinishing} method.
1875 * <p><em>Note: do not count on this method being called as a place for
1876 * saving data! For example, if an activity is editing data in a content
1877 * provider, those edits should be committed in either {@link #onPause} or
1878 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1879 * free resources like threads that are associated with an activity, so
1880 * that a destroyed activity does not leave such things around while the
1881 * rest of its application is still running. There are situations where
1882 * the system will simply kill the activity's hosting process without
1883 * calling this method (or any others) in it, so it should not be used to
1884 * do things that are intended to remain around after the process goes
1887 * <p><em>Derived classes must call through to the super class's
1888 * implementation of this method. If they do not, an exception will be
1897 protected void onDestroy() {
1898 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1901 // dismiss any dialogs we are managing.
1902 if (mManagedDialogs != null) {
1903 final int numDialogs = mManagedDialogs.size();
1904 for (int i = 0; i < numDialogs; i++) {
1905 final ManagedDialog md = mManagedDialogs.valueAt(i);
1906 if (md.mDialog.isShowing()) {
1907 md.mDialog.dismiss();
1910 mManagedDialogs = null;
1913 // close any cursors we are managing.
1914 synchronized (mManagedCursors) {
1915 int numCursors = mManagedCursors.size();
1916 for (int i = 0; i < numCursors; i++) {
1917 ManagedCursor c = mManagedCursors.get(i);
1922 mManagedCursors.clear();
1925 // Close any open search dialog
1926 if (mSearchManager != null) {
1927 mSearchManager.stopSearch();
1930 if (mActionBar != null) {
1931 mActionBar.onDestroy();
1934 getApplication().dispatchActivityDestroyed(this);
1938 * Report to the system that your app is now fully drawn, purely for diagnostic
1939 * purposes (calling it does not impact the visible behavior of the activity).
1940 * This is only used to help instrument application launch times, so that the
1941 * app can report when it is fully in a usable state; without this, the only thing
1942 * the system itself can determine is the point at which the activity's window
1943 * is <em>first</em> drawn and displayed. To participate in app launch time
1944 * measurement, you should always call this method after first launch (when
1945 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1946 * entirely drawn your UI and populated with all of the significant data. You
1947 * can safely call this method any time after first launch as well, in which case
1948 * it will simply be ignored.
1950 public void reportFullyDrawn() {
1951 if (mDoReportFullyDrawn) {
1952 mDoReportFullyDrawn = false;
1954 ActivityManager.getService().reportActivityFullyDrawn(mToken);
1955 } catch (RemoteException e) {
1961 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
1962 * visa-versa. This method provides the same configuration that will be sent in the following
1963 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
1965 * @see android.R.attr#resizeableActivity
1967 * @param isInMultiWindowMode True if the activity is in multi-window mode.
1968 * @param newConfig The new configuration of the activity with the state
1969 * {@param isInMultiWindowMode}.
1971 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
1972 // Left deliberately empty. There should be no side effects if a direct
1973 // subclass of Activity does not call super.
1974 onMultiWindowModeChanged(isInMultiWindowMode);
1978 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
1981 * @see android.R.attr#resizeableActivity
1983 * @param isInMultiWindowMode True if the activity is in multi-window mode.
1985 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
1988 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
1989 // Left deliberately empty. There should be no side effects if a direct
1990 // subclass of Activity does not call super.
1994 * Returns true if the activity is currently in multi-window mode.
1995 * @see android.R.attr#resizeableActivity
1997 * @return True if the activity is in multi-window mode.
1999 public boolean isInMultiWindowMode() {
2001 return ActivityManager.getService().isInMultiWindowMode(mToken);
2002 } catch (RemoteException e) {
2008 * Called by the system when the activity changes to and from picture-in-picture mode. This
2009 * method provides the same configuration that will be sent in the following
2010 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2012 * @see android.R.attr#supportsPictureInPicture
2014 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2015 * @param newConfig The new configuration of the activity with the state
2016 * {@param isInPictureInPictureMode}.
2018 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2019 Configuration newConfig) {
2020 // Left deliberately empty. There should be no side effects if a direct
2021 // subclass of Activity does not call super.
2022 onPictureInPictureModeChanged(isInPictureInPictureMode);
2026 * Called by the system when the activity changes to and from picture-in-picture mode.
2028 * @see android.R.attr#supportsPictureInPicture
2030 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2032 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
2035 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2036 // Left deliberately empty. There should be no side effects if a direct
2037 // subclass of Activity does not call super.
2041 * Returns true if the activity is currently in picture-in-picture mode.
2042 * @see android.R.attr#supportsPictureInPicture
2044 * @return True if the activity is in picture-in-picture mode.
2046 public boolean isInPictureInPictureMode() {
2048 return ActivityManager.getService().isInPictureInPictureMode(mToken);
2049 } catch (RemoteException e) {
2055 * Puts the activity in picture-in-picture mode if possible in the current system state. Any
2056 * prior calls to {@link #setPictureInPictureParams(PictureInPictureParams)} will still apply
2057 * when entering picture-in-picture through this call.
2059 * @see #enterPictureInPictureMode(PictureInPictureParams)
2060 * @see android.R.attr#supportsPictureInPicture
2063 public void enterPictureInPictureMode() {
2064 enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
2069 public boolean enterPictureInPictureMode(@NonNull PictureInPictureArgs args) {
2070 return enterPictureInPictureMode(PictureInPictureArgs.convert(args));
2074 * Puts the activity in picture-in-picture mode if possible in the current system state. The
2075 * set parameters in {@param params} will be combined with the parameters from prior calls to
2076 * {@link #setPictureInPictureParams(PictureInPictureParams)}.
2078 * The system may disallow entering picture-in-picture in various cases, including when the
2079 * activity is not visible, if the screen is locked or if the user has an activity pinned.
2081 * @see android.R.attr#supportsPictureInPicture
2082 * @see PictureInPictureParams
2084 * @param params non-null parameters to be combined with previously set parameters when entering
2085 * picture-in-picture.
2087 * @return true if the system puts this activity into picture-in-picture mode or was already
2088 * in picture-in-picture mode (@see {@link #isInPictureInPictureMode())
2090 public boolean enterPictureInPictureMode(@NonNull PictureInPictureParams params) {
2092 if (params == null) {
2093 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2095 return ActivityManagerNative.getDefault().enterPictureInPictureMode(mToken, params);
2096 } catch (RemoteException e) {
2103 public void setPictureInPictureArgs(@NonNull PictureInPictureArgs args) {
2104 setPictureInPictureParams(PictureInPictureArgs.convert(args));
2108 * Updates the properties of the picture-in-picture activity, or sets it to be used later when
2109 * {@link #enterPictureInPictureMode()} is called.
2111 * @param params the new parameters for the picture-in-picture.
2113 public void setPictureInPictureParams(@NonNull PictureInPictureParams params) {
2115 if (params == null) {
2116 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2118 ActivityManagerNative.getDefault().setPictureInPictureParams(mToken, params);
2119 } catch (RemoteException e) {
2124 * Return the number of actions that will be displayed in the picture-in-picture UI when the
2125 * user interacts with the activity currently in picture-in-picture mode. This number may change
2126 * if the global configuration changes (ie. if the device is plugged into an external display),
2127 * but will always be larger than three.
2129 public int getMaxNumPictureInPictureActions() {
2131 return ActivityManagerNative.getDefault().getMaxNumPictureInPictureActions(mToken);
2132 } catch (RemoteException e) {
2137 void dispatchMovedToDisplay(int displayId, Configuration config) {
2138 updateDisplay(displayId);
2139 onMovedToDisplay(displayId, config);
2143 * Called by the system when the activity is moved from one display to another without
2144 * recreation. This means that this activity is declared to handle all changes to configuration
2145 * that happened when it was switched to another display, so it wasn't destroyed and created
2148 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
2149 * applied configuration actually changed. It is up to app developer to choose whether to handle
2150 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
2153 * <p>Use this callback to track changes to the displays if some activity functionality relies
2154 * on an association with some display properties.
2156 * @param displayId The id of the display to which activity was moved.
2157 * @param config Configuration of the activity resources on new display after move.
2159 * @see #onConfigurationChanged(Configuration)
2160 * @see View#onMovedToDisplay(int, Configuration)
2163 public void onMovedToDisplay(int displayId, Configuration config) {
2167 * Called by the system when the device configuration changes while your
2168 * activity is running. Note that this will <em>only</em> be called if
2169 * you have selected configurations you would like to handle with the
2170 * {@link android.R.attr#configChanges} attribute in your manifest. If
2171 * any configuration change occurs that is not selected to be reported
2172 * by that attribute, then instead of reporting it the system will stop
2173 * and restart the activity (to have it launched with the new
2176 * <p>At the time that this function has been called, your Resources
2177 * object will have been updated to return resource values matching the
2178 * new configuration.
2180 * @param newConfig The new device configuration.
2182 public void onConfigurationChanged(Configuration newConfig) {
2183 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
2186 mFragments.dispatchConfigurationChanged(newConfig);
2188 if (mWindow != null) {
2189 // Pass the configuration changed event to the window
2190 mWindow.onConfigurationChanged(newConfig);
2193 if (mActionBar != null) {
2194 // Do this last; the action bar will need to access
2195 // view changes from above.
2196 mActionBar.onConfigurationChanged(newConfig);
2201 * If this activity is being destroyed because it can not handle a
2202 * configuration parameter being changed (and thus its
2203 * {@link #onConfigurationChanged(Configuration)} method is
2204 * <em>not</em> being called), then you can use this method to discover
2205 * the set of changes that have occurred while in the process of being
2206 * destroyed. Note that there is no guarantee that these will be
2207 * accurate (other changes could have happened at any time), so you should
2208 * only use this as an optimization hint.
2210 * @return Returns a bit field of the configuration parameters that are
2211 * changing, as defined by the {@link android.content.res.Configuration}
2214 public int getChangingConfigurations() {
2215 return mConfigChangeFlags;
2219 * Retrieve the non-configuration instance data that was previously
2220 * returned by {@link #onRetainNonConfigurationInstance()}. This will
2221 * be available from the initial {@link #onCreate} and
2222 * {@link #onStart} calls to the new instance, allowing you to extract
2223 * any useful dynamic state from the previous instance.
2225 * <p>Note that the data you retrieve here should <em>only</em> be used
2226 * as an optimization for handling configuration changes. You should always
2227 * be able to handle getting a null pointer back, and an activity must
2228 * still be able to restore itself to its previous state (through the
2229 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2230 * function returns null.
2232 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2233 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2234 * available on older platforms through the Android support libraries.
2236 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
2239 public Object getLastNonConfigurationInstance() {
2240 return mLastNonConfigurationInstances != null
2241 ? mLastNonConfigurationInstances.activity : null;
2245 * Called by the system, as part of destroying an
2246 * activity due to a configuration change, when it is known that a new
2247 * instance will immediately be created for the new configuration. You
2248 * can return any object you like here, including the activity instance
2249 * itself, which can later be retrieved by calling
2250 * {@link #getLastNonConfigurationInstance()} in the new activity
2253 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2254 * or later, consider instead using a {@link Fragment} with
2255 * {@link Fragment#setRetainInstance(boolean)
2256 * Fragment.setRetainInstance(boolean}.</em>
2258 * <p>This function is called purely as an optimization, and you must
2259 * not rely on it being called. When it is called, a number of guarantees
2260 * will be made to help optimize configuration switching:
2262 * <li> The function will be called between {@link #onStop} and
2263 * {@link #onDestroy}.
2264 * <li> A new instance of the activity will <em>always</em> be immediately
2265 * created after this one's {@link #onDestroy()} is called. In particular,
2266 * <em>no</em> messages will be dispatched during this time (when the returned
2267 * object does not have an activity to be associated with).
2268 * <li> The object you return here will <em>always</em> be available from
2269 * the {@link #getLastNonConfigurationInstance()} method of the following
2270 * activity instance as described there.
2273 * <p>These guarantees are designed so that an activity can use this API
2274 * to propagate extensive state from the old to new activity instance, from
2275 * loaded bitmaps, to network connections, to evenly actively running
2276 * threads. Note that you should <em>not</em> propagate any data that
2277 * may change based on the configuration, including any data loaded from
2278 * resources such as strings, layouts, or drawables.
2280 * <p>The guarantee of no message handling during the switch to the next
2281 * activity simplifies use with active objects. For example if your retained
2282 * state is an {@link android.os.AsyncTask} you are guaranteed that its
2283 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
2284 * not be called from the call here until you execute the next instance's
2285 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
2286 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
2287 * running in a separate thread.)
2289 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2290 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2291 * available on older platforms through the Android support libraries.
2293 * @return any Object holding the desired state to propagate to the
2294 * next activity instance
2296 public Object onRetainNonConfigurationInstance() {
2301 * Retrieve the non-configuration instance data that was previously
2302 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
2303 * be available from the initial {@link #onCreate} and
2304 * {@link #onStart} calls to the new instance, allowing you to extract
2305 * any useful dynamic state from the previous instance.
2307 * <p>Note that the data you retrieve here should <em>only</em> be used
2308 * as an optimization for handling configuration changes. You should always
2309 * be able to handle getting a null pointer back, and an activity must
2310 * still be able to restore itself to its previous state (through the
2311 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2312 * function returns null.
2314 * @return Returns the object previously returned by
2315 * {@link #onRetainNonConfigurationChildInstances()}
2318 HashMap<String, Object> getLastNonConfigurationChildInstances() {
2319 return mLastNonConfigurationInstances != null
2320 ? mLastNonConfigurationInstances.children : null;
2324 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
2325 * it should return either a mapping from child activity id strings to arbitrary objects,
2326 * or null. This method is intended to be used by Activity framework subclasses that control a
2327 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
2328 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
2331 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
2335 NonConfigurationInstances retainNonConfigurationInstances() {
2336 Object activity = onRetainNonConfigurationInstance();
2337 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
2338 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
2340 // We're already stopped but we've been asked to retain.
2341 // Our fragments are taken care of but we need to mark the loaders for retention.
2342 // In order to do this correctly we need to restart the loaders first before
2343 // handing them off to the next activity.
2344 mFragments.doLoaderStart();
2345 mFragments.doLoaderStop(true);
2346 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
2348 if (activity == null && children == null && fragments == null && loaders == null
2349 && mVoiceInteractor == null) {
2353 NonConfigurationInstances nci = new NonConfigurationInstances();
2354 nci.activity = activity;
2355 nci.children = children;
2356 nci.fragments = fragments;
2357 nci.loaders = loaders;
2358 if (mVoiceInteractor != null) {
2359 mVoiceInteractor.retainInstance();
2360 nci.voiceInteractor = mVoiceInteractor;
2365 public void onLowMemory() {
2366 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
2368 mFragments.dispatchLowMemory();
2371 public void onTrimMemory(int level) {
2372 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
2374 mFragments.dispatchTrimMemory(level);
2378 * Return the FragmentManager for interacting with fragments associated
2379 * with this activity.
2381 public FragmentManager getFragmentManager() {
2382 return mFragments.getFragmentManager();
2386 * Called when a Fragment is being attached to this activity, immediately
2387 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
2388 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
2390 public void onAttachFragment(Fragment fragment) {
2395 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2396 * that gives the resulting {@link Cursor} to call
2397 * {@link #startManagingCursor} so that the activity will manage its
2398 * lifecycle for you.
2400 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2401 * or later, consider instead using {@link LoaderManager} instead, available
2402 * via {@link #getLoaderManager()}.</em>
2404 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2405 * this method, because the activity will do that for you at the appropriate time. However, if
2406 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2407 * not</em> automatically close the cursor and, in that case, you must call
2408 * {@link Cursor#close()}.</p>
2410 * @param uri The URI of the content provider to query.
2411 * @param projection List of columns to return.
2412 * @param selection SQL WHERE clause.
2413 * @param sortOrder SQL ORDER BY clause.
2415 * @return The Cursor that was returned by query().
2417 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2418 * @see #startManagingCursor
2421 * @deprecated Use {@link CursorLoader} instead.
2424 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2426 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
2428 startManagingCursor(c);
2435 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2436 * that gives the resulting {@link Cursor} to call
2437 * {@link #startManagingCursor} so that the activity will manage its
2438 * lifecycle for you.
2440 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2441 * or later, consider instead using {@link LoaderManager} instead, available
2442 * via {@link #getLoaderManager()}.</em>
2444 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2445 * this method, because the activity will do that for you at the appropriate time. However, if
2446 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2447 * not</em> automatically close the cursor and, in that case, you must call
2448 * {@link Cursor#close()}.</p>
2450 * @param uri The URI of the content provider to query.
2451 * @param projection List of columns to return.
2452 * @param selection SQL WHERE clause.
2453 * @param selectionArgs The arguments to selection, if any ?s are pesent
2454 * @param sortOrder SQL ORDER BY clause.
2456 * @return The Cursor that was returned by query().
2458 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2459 * @see #startManagingCursor
2461 * @deprecated Use {@link CursorLoader} instead.
2464 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2465 String[] selectionArgs, String sortOrder) {
2466 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2468 startManagingCursor(c);
2474 * This method allows the activity to take care of managing the given
2475 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2476 * That is, when the activity is stopped it will automatically call
2477 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2478 * it will call {@link Cursor#requery} for you. When the activity is
2479 * destroyed, all managed Cursors will be closed automatically.
2481 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2482 * or later, consider instead using {@link LoaderManager} instead, available
2483 * via {@link #getLoaderManager()}.</em>
2485 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2486 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2487 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2488 * <em>will not</em> automatically close the cursor and, in that case, you must call
2489 * {@link Cursor#close()}.</p>
2491 * @param c The Cursor to be managed.
2493 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2494 * @see #stopManagingCursor
2496 * @deprecated Use the new {@link android.content.CursorLoader} class with
2497 * {@link LoaderManager} instead; this is also
2498 * available on older platforms through the Android compatibility package.
2501 public void startManagingCursor(Cursor c) {
2502 synchronized (mManagedCursors) {
2503 mManagedCursors.add(new ManagedCursor(c));
2508 * Given a Cursor that was previously given to
2509 * {@link #startManagingCursor}, stop the activity's management of that
2512 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2513 * the system <em>will not</em> automatically close the cursor and you must call
2514 * {@link Cursor#close()}.</p>
2516 * @param c The Cursor that was being managed.
2518 * @see #startManagingCursor
2520 * @deprecated Use the new {@link android.content.CursorLoader} class with
2521 * {@link LoaderManager} instead; this is also
2522 * available on older platforms through the Android compatibility package.
2525 public void stopManagingCursor(Cursor c) {
2526 synchronized (mManagedCursors) {
2527 final int N = mManagedCursors.size();
2528 for (int i=0; i<N; i++) {
2529 ManagedCursor mc = mManagedCursors.get(i);
2530 if (mc.mCursor == c) {
2531 mManagedCursors.remove(i);
2539 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2544 public void setPersistent(boolean isPersistent) {
2548 * Finds a view that was identified by the {@code android:id} XML attribute
2549 * that was processed in {@link #onCreate}.
2551 * <strong>Note:</strong> In most cases -- depending on compiler support --
2552 * the resulting view is automatically cast to the target class type. If
2553 * the target class type is unconstrained, an explicit cast may be
2556 * @param id the ID to search for
2557 * @return a view with given ID if found, or {@code null} otherwise
2558 * @see View#findViewById(int)
2561 public <T extends View> T findViewById(@IdRes int id) {
2562 return getWindow().findViewById(id);
2566 * Retrieve a reference to this activity's ActionBar.
2568 * @return The Activity's ActionBar, or null if it does not have one.
2571 public ActionBar getActionBar() {
2572 initWindowDecorActionBar();
2577 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2580 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2581 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2582 * a traditional window decor action bar. The toolbar's menu will be populated with the
2583 * Activity's options menu and the navigation button will be wired through the standard
2584 * {@link android.R.id#home home} menu select action.</p>
2586 * <p>In order to use a Toolbar within the Activity's window content the application
2587 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2589 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
2591 public void setActionBar(@Nullable Toolbar toolbar) {
2592 final ActionBar ab = getActionBar();
2593 if (ab instanceof WindowDecorActionBar) {
2594 throw new IllegalStateException("This Activity already has an action bar supplied " +
2595 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2596 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2599 // If we reach here then we're setting a new action bar
2600 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
2601 mMenuInflater = null;
2603 // If we have an action bar currently, destroy it
2608 if (toolbar != null) {
2609 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2611 mWindow.setCallback(tbab.getWrappedWindowCallback());
2614 // Re-set the original window callback since we may have already set a Toolbar wrapper
2615 mWindow.setCallback(this);
2618 invalidateOptionsMenu();
2622 * Creates a new ActionBar, locates the inflated ActionBarView,
2623 * initializes the ActionBar with the view, and sets mActionBar.
2625 private void initWindowDecorActionBar() {
2626 Window window = getWindow();
2628 // Initializing the window decor can change window feature flags.
2629 // Make sure that we have the correct set before performing the test below.
2630 window.getDecorView();
2632 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2636 mActionBar = new WindowDecorActionBar(this);
2637 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2639 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2640 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2644 * Set the activity content from a layout resource. The resource will be
2645 * inflated, adding all top-level views to the activity.
2647 * @param layoutResID Resource ID to be inflated.
2649 * @see #setContentView(android.view.View)
2650 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2652 public void setContentView(@LayoutRes int layoutResID) {
2653 getWindow().setContentView(layoutResID);
2654 initWindowDecorActionBar();
2658 * Set the activity content to an explicit view. This view is placed
2659 * directly into the activity's view hierarchy. It can itself be a complex
2660 * view hierarchy. When calling this method, the layout parameters of the
2661 * specified view are ignored. Both the width and the height of the view are
2662 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2663 * your own layout parameters, invoke
2664 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2667 * @param view The desired content to display.
2669 * @see #setContentView(int)
2670 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2672 public void setContentView(View view) {
2673 getWindow().setContentView(view);
2674 initWindowDecorActionBar();
2678 * Set the activity content to an explicit view. This view is placed
2679 * directly into the activity's view hierarchy. It can itself be a complex
2682 * @param view The desired content to display.
2683 * @param params Layout parameters for the view.
2685 * @see #setContentView(android.view.View)
2686 * @see #setContentView(int)
2688 public void setContentView(View view, ViewGroup.LayoutParams params) {
2689 getWindow().setContentView(view, params);
2690 initWindowDecorActionBar();
2694 * Add an additional content view to the activity. Added after any existing
2695 * ones in the activity -- existing views are NOT removed.
2697 * @param view The desired content to display.
2698 * @param params Layout parameters for the view.
2700 public void addContentView(View view, ViewGroup.LayoutParams params) {
2701 getWindow().addContentView(view, params);
2702 initWindowDecorActionBar();
2706 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2707 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2709 * <p>This method will return non-null after content has been initialized (e.g. by using
2710 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2712 * @return This window's content TransitionManager or null if none is set.
2714 public TransitionManager getContentTransitionManager() {
2715 return getWindow().getTransitionManager();
2719 * Set the {@link TransitionManager} to use for default transitions in this window.
2720 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2722 * @param tm The TransitionManager to use for scene changes.
2724 public void setContentTransitionManager(TransitionManager tm) {
2725 getWindow().setTransitionManager(tm);
2729 * Retrieve the {@link Scene} representing this window's current content.
2730 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2732 * <p>This method will return null if the current content is not represented by a Scene.</p>
2734 * @return Current Scene being shown or null
2736 public Scene getContentScene() {
2737 return getWindow().getContentScene();
2741 * Sets whether this activity is finished when touched outside its window's
2744 public void setFinishOnTouchOutside(boolean finish) {
2745 mWindow.setCloseOnTouchOutside(finish);
2749 @IntDef(prefix = { "DEFAULT_KEYS_" }, value = {
2750 DEFAULT_KEYS_DISABLE,
2751 DEFAULT_KEYS_DIALER,
2752 DEFAULT_KEYS_SHORTCUT,
2753 DEFAULT_KEYS_SEARCH_LOCAL,
2754 DEFAULT_KEYS_SEARCH_GLOBAL
2756 @Retention(RetentionPolicy.SOURCE)
2757 @interface DefaultKeyMode {}
2760 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2763 * @see #setDefaultKeyMode
2765 static public final int DEFAULT_KEYS_DISABLE = 0;
2767 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2770 * @see #setDefaultKeyMode
2772 static public final int DEFAULT_KEYS_DIALER = 1;
2774 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2775 * default key handling.
2777 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2779 * @see #setDefaultKeyMode
2781 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2783 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2784 * will start an application-defined search. (If the application or activity does not
2785 * actually define a search, the the keys will be ignored.)
2787 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2789 * @see #setDefaultKeyMode
2791 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2794 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2795 * will start a global search (typically web search, but some platforms may define alternate
2796 * methods for global search)
2798 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2800 * @see #setDefaultKeyMode
2802 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2805 * Select the default key handling for this activity. This controls what
2806 * will happen to key events that are not otherwise handled. The default
2807 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2808 * floor. Other modes allow you to launch the dialer
2809 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2810 * menu without requiring the menu key be held down
2811 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2812 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2814 * <p>Note that the mode selected here does not impact the default
2815 * handling of system keys, such as the "back" and "menu" keys, and your
2816 * activity and its views always get a first chance to receive and handle
2817 * all application keys.
2819 * @param mode The desired default key mode constant.
2823 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2824 mDefaultKeyMode = mode;
2826 // Some modes use a SpannableStringBuilder to track & dispatch input events
2827 // This list must remain in sync with the switch in onKeyDown()
2829 case DEFAULT_KEYS_DISABLE:
2830 case DEFAULT_KEYS_SHORTCUT:
2831 mDefaultKeySsb = null; // not used in these modes
2833 case DEFAULT_KEYS_DIALER:
2834 case DEFAULT_KEYS_SEARCH_LOCAL:
2835 case DEFAULT_KEYS_SEARCH_GLOBAL:
2836 mDefaultKeySsb = new SpannableStringBuilder();
2837 Selection.setSelection(mDefaultKeySsb,0);
2840 throw new IllegalArgumentException();
2845 * Called when a key was pressed down and not handled by any of the views
2846 * inside of the activity. So, for example, key presses while the cursor
2847 * is inside a TextView will not trigger the event (unless it is a navigation
2848 * to another object) because TextView handles its own key presses.
2850 * <p>If the focused view didn't want this event, this method is called.
2852 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2853 * by calling {@link #onBackPressed()}, though the behavior varies based
2854 * on the application compatibility mode: for
2855 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2856 * it will set up the dispatch to call {@link #onKeyUp} where the action
2857 * will be performed; for earlier applications, it will perform the
2858 * action immediately in on-down, as those versions of the platform
2861 * <p>Other additional default key handling may be performed
2862 * if configured with {@link #setDefaultKeyMode}.
2864 * @return Return <code>true</code> to prevent this event from being propagated
2865 * further, or <code>false</code> to indicate that you have not handled
2866 * this event and it should continue to be propagated.
2868 * @see android.view.KeyEvent
2870 public boolean onKeyDown(int keyCode, KeyEvent event) {
2871 if (keyCode == KeyEvent.KEYCODE_BACK) {
2872 if (getApplicationInfo().targetSdkVersion
2873 >= Build.VERSION_CODES.ECLAIR) {
2874 event.startTracking();
2881 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2883 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2884 Window w = getWindow();
2885 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2886 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2887 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2891 } else if (keyCode == KeyEvent.KEYCODE_TAB) {
2892 // Don't consume TAB here since it's used for navigation. Arrow keys
2893 // aren't considered "typing keys" so they already won't get consumed.
2896 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2897 boolean clearSpannable = false;
2899 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2900 clearSpannable = true;
2903 handled = TextKeyListener.getInstance().onKeyDown(
2904 null, mDefaultKeySsb, keyCode, event);
2905 if (handled && mDefaultKeySsb.length() > 0) {
2906 // something useable has been typed - dispatch it now.
2908 final String str = mDefaultKeySsb.toString();
2909 clearSpannable = true;
2911 switch (mDefaultKeyMode) {
2912 case DEFAULT_KEYS_DIALER:
2913 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2914 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2915 startActivity(intent);
2917 case DEFAULT_KEYS_SEARCH_LOCAL:
2918 startSearch(str, false, null, false);
2920 case DEFAULT_KEYS_SEARCH_GLOBAL:
2921 startSearch(str, false, null, true);
2926 if (clearSpannable) {
2927 mDefaultKeySsb.clear();
2928 mDefaultKeySsb.clearSpans();
2929 Selection.setSelection(mDefaultKeySsb,0);
2936 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2937 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2940 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2945 * Called when a key was released and not handled by any of the views
2946 * inside of the activity. So, for example, key presses while the cursor
2947 * is inside a TextView will not trigger the event (unless it is a navigation
2948 * to another object) because TextView handles its own key presses.
2950 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2953 * @return Return <code>true</code> to prevent this event from being propagated
2954 * further, or <code>false</code> to indicate that you have not handled
2955 * this event and it should continue to be propagated.
2959 public boolean onKeyUp(int keyCode, KeyEvent event) {
2960 if (getApplicationInfo().targetSdkVersion
2961 >= Build.VERSION_CODES.ECLAIR) {
2962 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2963 && !event.isCanceled()) {
2972 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2973 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
2976 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2981 * Called when the activity has detected the user's press of the back
2982 * key. The default implementation simply finishes the current activity,
2983 * but you can override this to do whatever you want.
2985 public void onBackPressed() {
2986 if (mActionBar != null && mActionBar.collapseActionView()) {
2990 FragmentManager fragmentManager = mFragments.getFragmentManager();
2992 if (fragmentManager.isStateSaved() || !fragmentManager.popBackStackImmediate()) {
2993 finishAfterTransition();
2998 * Called when a key shortcut event is not handled by any of the views in the Activity.
2999 * Override this method to implement global key shortcuts for the Activity.
3000 * Key shortcuts can also be implemented by setting the
3001 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
3003 * @param keyCode The value in event.getKeyCode().
3004 * @param event Description of the key event.
3005 * @return True if the key shortcut was handled.
3007 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
3008 // Let the Action Bar have a chance at handling the shortcut.
3009 ActionBar actionBar = getActionBar();
3010 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
3014 * Called when a touch screen event was not handled by any of the views
3015 * under it. This is most useful to process touch events that happen
3016 * outside of your window bounds, where there is no view to receive it.
3018 * @param event The touch screen event being processed.
3020 * @return Return true if you have consumed the event, false if you haven't.
3021 * The default implementation always returns false.
3023 public boolean onTouchEvent(MotionEvent event) {
3024 if (mWindow.shouldCloseOnTouch(this, event)) {
3033 * Called when the trackball was moved and not handled by any of the
3034 * views inside of the activity. So, for example, if the trackball moves
3035 * while focus is on a button, you will receive a call here because
3036 * buttons do not normally do anything with trackball events. The call
3037 * here happens <em>before</em> trackball movements are converted to
3038 * DPAD key events, which then get sent back to the view hierarchy, and
3039 * will be processed at the point for things like focus navigation.
3041 * @param event The trackball event being processed.
3043 * @return Return true if you have consumed the event, false if you haven't.
3044 * The default implementation always returns false.
3046 public boolean onTrackballEvent(MotionEvent event) {
3051 * Called when a generic motion event was not handled by any of the
3052 * views inside of the activity.
3054 * Generic motion events describe joystick movements, mouse hovers, track pad
3055 * touches, scroll wheel movements and other input events. The
3056 * {@link MotionEvent#getSource() source} of the motion event specifies
3057 * the class of input that was received. Implementations of this method
3058 * must examine the bits in the source before processing the event.
3059 * The following code example shows how this is done.
3061 * Generic motion events with source class
3062 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
3063 * are delivered to the view under the pointer. All other generic motion events are
3064 * delivered to the focused view.
3066 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
3067 * handle this event.
3070 * @param event The generic motion event being processed.
3072 * @return Return true if you have consumed the event, false if you haven't.
3073 * The default implementation always returns false.
3075 public boolean onGenericMotionEvent(MotionEvent event) {
3080 * Called whenever a key, touch, or trackball event is dispatched to the
3081 * activity. Implement this method if you wish to know that the user has
3082 * interacted with the device in some way while your activity is running.
3083 * This callback and {@link #onUserLeaveHint} are intended to help
3084 * activities manage status bar notifications intelligently; specifically,
3085 * for helping activities determine the proper time to cancel a notfication.
3087 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
3088 * be accompanied by calls to {@link #onUserInteraction}. This
3089 * ensures that your activity will be told of relevant user activity such
3090 * as pulling down the notification pane and touching an item there.
3092 * <p>Note that this callback will be invoked for the touch down action
3093 * that begins a touch gesture, but may not be invoked for the touch-moved
3094 * and touch-up actions that follow.
3096 * @see #onUserLeaveHint()
3098 public void onUserInteraction() {
3101 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
3102 // Update window manager if: we have a view, that view is
3103 // attached to its parent (which will be a RootView), and
3104 // this activity is not embedded.
3105 if (mParent == null) {
3106 View decor = mDecor;
3107 if (decor != null && decor.getParent() != null) {
3108 getWindowManager().updateViewLayout(decor, params);
3113 public void onContentChanged() {
3117 * Called when the current {@link Window} of the activity gains or loses
3118 * focus. This is the best indicator of whether this activity is visible
3119 * to the user. The default implementation clears the key tracking
3120 * state, so should always be called.
3122 * <p>Note that this provides information about global focus state, which
3123 * is managed independently of activity lifecycles. As such, while focus
3124 * changes will generally have some relation to lifecycle changes (an
3125 * activity that is stopped will not generally get window focus), you
3126 * should not rely on any particular order between the callbacks here and
3127 * those in the other lifecycle methods such as {@link #onResume}.
3129 * <p>As a general rule, however, a resumed activity will have window
3130 * focus... unless it has displayed other dialogs or popups that take
3131 * input focus, in which case the activity itself will not have focus
3132 * when the other windows have it. Likewise, the system may display
3133 * system-level windows (such as the status bar notification panel or
3134 * a system alert) which will temporarily take window input focus without
3135 * pausing the foreground activity.
3137 * @param hasFocus Whether the window of this activity has focus.
3139 * @see #hasWindowFocus()
3141 * @see View#onWindowFocusChanged(boolean)
3143 public void onWindowFocusChanged(boolean hasFocus) {
3147 * Called when the main window associated with the activity has been
3148 * attached to the window manager.
3149 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
3150 * for more information.
3151 * @see View#onAttachedToWindow
3153 public void onAttachedToWindow() {
3157 * Called when the main window associated with the activity has been
3158 * detached from the window manager.
3159 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
3160 * for more information.
3161 * @see View#onDetachedFromWindow
3163 public void onDetachedFromWindow() {
3167 * Returns true if this activity's <em>main</em> window currently has window focus.
3168 * Note that this is not the same as the view itself having focus.
3170 * @return True if this activity's main window currently has window focus.
3172 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
3174 public boolean hasWindowFocus() {
3175 Window w = getWindow();
3177 View d = w.getDecorView();
3179 return d.hasWindowFocus();
3186 * Called when the main window associated with the activity has been dismissed.
3190 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
3191 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
3192 if (suppressWindowTransition) {
3193 overridePendingTransition(0, 0);
3199 * Moves the activity from
3200 * {@link android.app.ActivityManager.StackId#FREEFORM_WORKSPACE_STACK_ID} to
3201 * {@link android.app.ActivityManager.StackId#FULLSCREEN_WORKSPACE_STACK_ID} stack.
3206 public void exitFreeformMode() throws RemoteException {
3207 ActivityManager.getService().exitFreeformMode(mToken);
3210 /** Returns the current stack Id for the window.
3214 public int getWindowStackId() throws RemoteException {
3215 return ActivityManager.getService().getActivityStackId(mToken);
3219 * Puts the activity in picture-in-picture mode if the activity supports.
3220 * @see android.R.attr#supportsPictureInPicture
3224 public void enterPictureInPictureModeIfPossible() {
3225 if (mActivityInfo.supportsPictureInPicture()) {
3226 enterPictureInPictureMode();
3231 * Called to process key events. You can override this to intercept all
3232 * key events before they are dispatched to the window. Be sure to call
3233 * this implementation for key events that should be handled normally.
3235 * @param event The key event.
3237 * @return boolean Return true if this event was consumed.
3239 public boolean dispatchKeyEvent(KeyEvent event) {
3240 onUserInteraction();
3242 // Let action bars open menus in response to the menu key prioritized over
3243 // the window handling it
3244 final int keyCode = event.getKeyCode();
3245 if (keyCode == KeyEvent.KEYCODE_MENU &&
3246 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
3250 Window win = getWindow();
3251 if (win.superDispatchKeyEvent(event)) {
3254 View decor = mDecor;
3255 if (decor == null) decor = win.getDecorView();
3256 return event.dispatch(this, decor != null
3257 ? decor.getKeyDispatcherState() : null, this);
3261 * Called to process a key shortcut event.
3262 * You can override this to intercept all key shortcut events before they are
3263 * dispatched to the window. Be sure to call this implementation for key shortcut
3264 * events that should be handled normally.
3266 * @param event The key shortcut event.
3267 * @return True if this event was consumed.
3269 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3270 onUserInteraction();
3271 if (getWindow().superDispatchKeyShortcutEvent(event)) {
3274 return onKeyShortcut(event.getKeyCode(), event);
3278 * Called to process touch screen events. You can override this to
3279 * intercept all touch screen events before they are dispatched to the
3280 * window. Be sure to call this implementation for touch screen events
3281 * that should be handled normally.
3283 * @param ev The touch screen event.
3285 * @return boolean Return true if this event was consumed.
3287 public boolean dispatchTouchEvent(MotionEvent ev) {
3288 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
3289 onUserInteraction();
3291 if (getWindow().superDispatchTouchEvent(ev)) {
3294 return onTouchEvent(ev);
3298 * Called to process trackball events. You can override this to
3299 * intercept all trackball events before they are dispatched to the
3300 * window. Be sure to call this implementation for trackball events
3301 * that should be handled normally.
3303 * @param ev The trackball event.
3305 * @return boolean Return true if this event was consumed.
3307 public boolean dispatchTrackballEvent(MotionEvent ev) {
3308 onUserInteraction();
3309 if (getWindow().superDispatchTrackballEvent(ev)) {
3312 return onTrackballEvent(ev);
3316 * Called to process generic motion events. You can override this to
3317 * intercept all generic motion events before they are dispatched to the
3318 * window. Be sure to call this implementation for generic motion events
3319 * that should be handled normally.
3321 * @param ev The generic motion event.
3323 * @return boolean Return true if this event was consumed.
3325 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3326 onUserInteraction();
3327 if (getWindow().superDispatchGenericMotionEvent(ev)) {
3330 return onGenericMotionEvent(ev);
3333 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3334 event.setClassName(getClass().getName());
3335 event.setPackageName(getPackageName());
3337 LayoutParams params = getWindow().getAttributes();
3338 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
3339 (params.height == LayoutParams.MATCH_PARENT);
3340 event.setFullScreen(isFullScreen);
3342 CharSequence title = getTitle();
3343 if (!TextUtils.isEmpty(title)) {
3344 event.getText().add(title);
3351 * Default implementation of
3352 * {@link android.view.Window.Callback#onCreatePanelView}
3353 * for activities. This
3354 * simply returns null so that all panel sub-windows will have the default
3358 public View onCreatePanelView(int featureId) {
3363 * Default implementation of
3364 * {@link android.view.Window.Callback#onCreatePanelMenu}
3365 * for activities. This calls through to the new
3366 * {@link #onCreateOptionsMenu} method for the
3367 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3368 * so that subclasses of Activity don't need to deal with feature codes.
3370 public boolean onCreatePanelMenu(int featureId, Menu menu) {
3371 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
3372 boolean show = onCreateOptionsMenu(menu);
3373 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
3380 * Default implementation of
3381 * {@link android.view.Window.Callback#onPreparePanel}
3382 * for activities. This
3383 * calls through to the new {@link #onPrepareOptionsMenu} method for the
3384 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3385 * panel, so that subclasses of
3386 * Activity don't need to deal with feature codes.
3388 public boolean onPreparePanel(int featureId, View view, Menu menu) {
3389 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
3390 boolean goforit = onPrepareOptionsMenu(menu);
3391 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
3400 * @return The default implementation returns true.
3402 public boolean onMenuOpened(int featureId, Menu menu) {
3403 if (featureId == Window.FEATURE_ACTION_BAR) {
3404 initWindowDecorActionBar();
3405 if (mActionBar != null) {
3406 mActionBar.dispatchMenuVisibilityChanged(true);
3408 Log.e(TAG, "Tried to open action bar menu with no action bar");
3415 * Default implementation of
3416 * {@link android.view.Window.Callback#onMenuItemSelected}
3417 * for activities. This calls through to the new
3418 * {@link #onOptionsItemSelected} method for the
3419 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3420 * panel, so that subclasses of
3421 * Activity don't need to deal with feature codes.
3423 public boolean onMenuItemSelected(int featureId, MenuItem item) {
3424 CharSequence titleCondensed = item.getTitleCondensed();
3426 switch (featureId) {
3427 case Window.FEATURE_OPTIONS_PANEL:
3428 // Put event logging here so it gets called even if subclass
3429 // doesn't call through to superclass's implmeentation of each
3430 // of these methods below
3431 if(titleCondensed != null) {
3432 EventLog.writeEvent(50000, 0, titleCondensed.toString());
3434 if (onOptionsItemSelected(item)) {
3437 if (mFragments.dispatchOptionsItemSelected(item)) {
3440 if (item.getItemId() == android.R.id.home && mActionBar != null &&
3441 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
3442 if (mParent == null) {
3443 return onNavigateUp();
3445 return mParent.onNavigateUpFromChild(this);
3450 case Window.FEATURE_CONTEXT_MENU:
3451 if(titleCondensed != null) {
3452 EventLog.writeEvent(50000, 1, titleCondensed.toString());
3454 if (onContextItemSelected(item)) {
3457 return mFragments.dispatchContextItemSelected(item);
3465 * Default implementation of
3466 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
3467 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
3468 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3469 * so that subclasses of Activity don't need to deal with feature codes.
3470 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
3471 * {@link #onContextMenuClosed(Menu)} will be called.
3473 public void onPanelClosed(int featureId, Menu menu) {
3474 switch (featureId) {
3475 case Window.FEATURE_OPTIONS_PANEL:
3476 mFragments.dispatchOptionsMenuClosed(menu);
3477 onOptionsMenuClosed(menu);
3480 case Window.FEATURE_CONTEXT_MENU:
3481 onContextMenuClosed(menu);
3484 case Window.FEATURE_ACTION_BAR:
3485 initWindowDecorActionBar();
3486 mActionBar.dispatchMenuVisibilityChanged(false);
3492 * Declare that the options menu has changed, so should be recreated.
3493 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
3494 * time it needs to be displayed.
3496 public void invalidateOptionsMenu() {
3497 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3498 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
3499 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
3504 * Initialize the contents of the Activity's standard options menu. You
3505 * should place your menu items in to <var>menu</var>.
3507 * <p>This is only called once, the first time the options menu is
3508 * displayed. To update the menu every time it is displayed, see
3509 * {@link #onPrepareOptionsMenu}.
3511 * <p>The default implementation populates the menu with standard system
3512 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
3513 * they will be correctly ordered with application-defined menu items.
3514 * Deriving classes should always call through to the base implementation.
3516 * <p>You can safely hold on to <var>menu</var> (and any items created
3517 * from it), making modifications to it as desired, until the next
3518 * time onCreateOptionsMenu() is called.
3520 * <p>When you add items to the menu, you can implement the Activity's
3521 * {@link #onOptionsItemSelected} method to handle them there.
3523 * @param menu The options menu in which you place your items.
3525 * @return You must return true for the menu to be displayed;
3526 * if you return false it will not be shown.
3528 * @see #onPrepareOptionsMenu
3529 * @see #onOptionsItemSelected
3531 public boolean onCreateOptionsMenu(Menu menu) {
3532 if (mParent != null) {
3533 return mParent.onCreateOptionsMenu(menu);
3539 * Prepare the Screen's standard options menu to be displayed. This is
3540 * called right before the menu is shown, every time it is shown. You can
3541 * use this method to efficiently enable/disable items or otherwise
3542 * dynamically modify the contents.
3544 * <p>The default implementation updates the system menu items based on the
3545 * activity's state. Deriving classes should always call through to the
3546 * base class implementation.
3548 * @param menu The options menu as last shown or first initialized by
3549 * onCreateOptionsMenu().
3551 * @return You must return true for the menu to be displayed;
3552 * if you return false it will not be shown.
3554 * @see #onCreateOptionsMenu
3556 public boolean onPrepareOptionsMenu(Menu menu) {
3557 if (mParent != null) {
3558 return mParent.onPrepareOptionsMenu(menu);
3564 * This hook is called whenever an item in your options menu is selected.
3565 * The default implementation simply returns false to have the normal
3566 * processing happen (calling the item's Runnable or sending a message to
3567 * its Handler as appropriate). You can use this method for any items
3568 * for which you would like to do processing without those other
3571 * <p>Derived classes should call through to the base class for it to
3572 * perform the default menu handling.</p>
3574 * @param item The menu item that was selected.
3576 * @return boolean Return false to allow normal menu processing to
3577 * proceed, true to consume it here.
3579 * @see #onCreateOptionsMenu
3581 public boolean onOptionsItemSelected(MenuItem item) {
3582 if (mParent != null) {
3583 return mParent.onOptionsItemSelected(item);
3589 * This method is called whenever the user chooses to navigate Up within your application's
3590 * activity hierarchy from the action bar.
3592 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3593 * was specified in the manifest for this activity or an activity-alias to it,
3594 * default Up navigation will be handled automatically. If any activity
3595 * along the parent chain requires extra Intent arguments, the Activity subclass
3596 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3597 * to supply those arguments.</p>
3599 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
3600 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3601 * from the design guide for more information about navigating within your app.</p>
3603 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3604 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3605 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3606 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3608 * @return true if Up navigation completed successfully and this Activity was finished,
3611 public boolean onNavigateUp() {
3612 // Automatically handle hierarchical Up navigation if the proper
3613 // metadata is available.
3614 Intent upIntent = getParentActivityIntent();
3615 if (upIntent != null) {
3616 if (mActivityInfo.taskAffinity == null) {
3617 // Activities with a null affinity are special; they really shouldn't
3618 // specify a parent activity intent in the first place. Just finish
3619 // the current activity and call it a day.
3621 } else if (shouldUpRecreateTask(upIntent)) {
3622 TaskStackBuilder b = TaskStackBuilder.create(this);
3623 onCreateNavigateUpTaskStack(b);
3624 onPrepareNavigateUpTaskStack(b);
3625 b.startActivities();
3627 // We can't finishAffinity if we have a result.
3628 // Fall back and simply finish the current activity instead.
3629 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3630 // Tell the developer what's going on to avoid hair-pulling.
3631 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3637 navigateUpTo(upIntent);
3645 * This is called when a child activity of this one attempts to navigate up.
3646 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3648 * @param child The activity making the call.
3650 public boolean onNavigateUpFromChild(Activity child) {
3651 return onNavigateUp();
3655 * Define the synthetic task stack that will be generated during Up navigation from
3658 * <p>The default implementation of this method adds the parent chain of this activity
3659 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3660 * may choose to override this method to construct the desired task stack in a different
3663 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3664 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3665 * returned by {@link #getParentActivityIntent()}.</p>
3667 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3668 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3670 * @param builder An empty TaskStackBuilder - the application should add intents representing
3671 * the desired task stack
3673 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3674 builder.addParentStack(this);
3678 * Prepare the synthetic task stack that will be generated during Up navigation
3679 * from a different task.
3681 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3682 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3683 * If any extra data should be added to these intents before launching the new task,
3684 * the application should override this method and add that data here.</p>
3686 * @param builder A TaskStackBuilder that has been populated with Intents by
3687 * onCreateNavigateUpTaskStack.
3689 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3693 * This hook is called whenever the options menu is being closed (either by the user canceling
3694 * the menu with the back/menu button, or when an item is selected).
3696 * @param menu The options menu as last shown or first initialized by
3697 * onCreateOptionsMenu().
3699 public void onOptionsMenuClosed(Menu menu) {
3700 if (mParent != null) {
3701 mParent.onOptionsMenuClosed(menu);
3706 * Programmatically opens the options menu. If the options menu is already
3707 * open, this method does nothing.
3709 public void openOptionsMenu() {
3710 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3711 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3712 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3717 * Progammatically closes the options menu. If the options menu is already
3718 * closed, this method does nothing.
3720 public void closeOptionsMenu() {
3721 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3722 (mActionBar == null || !mActionBar.closeOptionsMenu())) {
3723 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3728 * Called when a context menu for the {@code view} is about to be shown.
3729 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3730 * time the context menu is about to be shown and should be populated for
3731 * the view (or item inside the view for {@link AdapterView} subclasses,
3732 * this can be found in the {@code menuInfo})).
3734 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3735 * item has been selected.
3737 * It is not safe to hold onto the context menu after this method returns.
3740 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3744 * Registers a context menu to be shown for the given view (multiple views
3745 * can show the context menu). This method will set the
3746 * {@link OnCreateContextMenuListener} on the view to this activity, so
3747 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3748 * called when it is time to show the context menu.
3750 * @see #unregisterForContextMenu(View)
3751 * @param view The view that should show a context menu.
3753 public void registerForContextMenu(View view) {
3754 view.setOnCreateContextMenuListener(this);
3758 * Prevents a context menu to be shown for the given view. This method will remove the
3759 * {@link OnCreateContextMenuListener} on the view.
3761 * @see #registerForContextMenu(View)
3762 * @param view The view that should stop showing a context menu.
3764 public void unregisterForContextMenu(View view) {
3765 view.setOnCreateContextMenuListener(null);
3769 * Programmatically opens the context menu for a particular {@code view}.
3770 * The {@code view} should have been added via
3771 * {@link #registerForContextMenu(View)}.
3773 * @param view The view to show the context menu for.
3775 public void openContextMenu(View view) {
3776 view.showContextMenu();
3780 * Programmatically closes the most recently opened context menu, if showing.
3782 public void closeContextMenu() {
3783 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3784 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3789 * This hook is called whenever an item in a context menu is selected. The
3790 * default implementation simply returns false to have the normal processing
3791 * happen (calling the item's Runnable or sending a message to its Handler
3792 * as appropriate). You can use this method for any items for which you
3793 * would like to do processing without those other facilities.
3795 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3796 * View that added this menu item.
3798 * Derived classes should call through to the base class for it to perform
3799 * the default menu handling.
3801 * @param item The context menu item that was selected.
3802 * @return boolean Return false to allow normal context menu processing to
3803 * proceed, true to consume it here.
3805 public boolean onContextItemSelected(MenuItem item) {
3806 if (mParent != null) {
3807 return mParent.onContextItemSelected(item);
3813 * This hook is called whenever the context menu is being closed (either by
3814 * the user canceling the menu with the back/menu button, or when an item is
3817 * @param menu The context menu that is being closed.
3819 public void onContextMenuClosed(Menu menu) {
3820 if (mParent != null) {
3821 mParent.onContextMenuClosed(menu);
3826 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3829 protected Dialog onCreateDialog(int id) {
3834 * Callback for creating dialogs that are managed (saved and restored) for you
3835 * by the activity. The default implementation calls through to
3836 * {@link #onCreateDialog(int)} for compatibility.
3838 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3839 * or later, consider instead using a {@link DialogFragment} instead.</em>
3841 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3842 * this method the first time, and hang onto it thereafter. Any dialog
3843 * that is created by this method will automatically be saved and restored
3844 * for you, including whether it is showing.
3846 * <p>If you would like the activity to manage saving and restoring dialogs
3847 * for you, you should override this method and handle any ids that are
3848 * passed to {@link #showDialog}.
3850 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3851 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3853 * @param id The id of the dialog.
3854 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3855 * @return The dialog. If you return null, the dialog will not be created.
3857 * @see #onPrepareDialog(int, Dialog, Bundle)
3858 * @see #showDialog(int, Bundle)
3859 * @see #dismissDialog(int)
3860 * @see #removeDialog(int)
3862 * @deprecated Use the new {@link DialogFragment} class with
3863 * {@link FragmentManager} instead; this is also
3864 * available on older platforms through the Android compatibility package.
3868 protected Dialog onCreateDialog(int id, Bundle args) {
3869 return onCreateDialog(id);
3873 * @deprecated Old no-arguments version of
3874 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3877 protected void onPrepareDialog(int id, Dialog dialog) {
3878 dialog.setOwnerActivity(this);
3882 * Provides an opportunity to prepare a managed dialog before it is being
3883 * shown. The default implementation calls through to
3884 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3887 * Override this if you need to update a managed dialog based on the state
3888 * of the application each time it is shown. For example, a time picker
3889 * dialog might want to be updated with the current time. You should call
3890 * through to the superclass's implementation. The default implementation
3891 * will set this Activity as the owner activity on the Dialog.
3893 * @param id The id of the managed dialog.
3894 * @param dialog The dialog.
3895 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3896 * @see #onCreateDialog(int, Bundle)
3897 * @see #showDialog(int)
3898 * @see #dismissDialog(int)
3899 * @see #removeDialog(int)
3901 * @deprecated Use the new {@link DialogFragment} class with
3902 * {@link FragmentManager} instead; this is also
3903 * available on older platforms through the Android compatibility package.
3906 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3907 onPrepareDialog(id, dialog);
3911 * Simple version of {@link #showDialog(int, Bundle)} that does not
3912 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3913 * with null arguments.
3915 * @deprecated Use the new {@link DialogFragment} class with
3916 * {@link FragmentManager} instead; this is also
3917 * available on older platforms through the Android compatibility package.
3920 public final void showDialog(int id) {
3921 showDialog(id, null);
3925 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3926 * will be made with the same id the first time this is called for a given
3927 * id. From thereafter, the dialog will be automatically saved and restored.
3929 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3930 * or later, consider instead using a {@link DialogFragment} instead.</em>
3932 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3933 * be made to provide an opportunity to do any timely preparation.
3935 * @param id The id of the managed dialog.
3936 * @param args Arguments to pass through to the dialog. These will be saved
3937 * and restored for you. Note that if the dialog is already created,
3938 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3939 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3940 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3941 * @return Returns true if the Dialog was created; false is returned if
3942 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3945 * @see #onCreateDialog(int, Bundle)
3946 * @see #onPrepareDialog(int, Dialog, Bundle)
3947 * @see #dismissDialog(int)
3948 * @see #removeDialog(int)
3950 * @deprecated Use the new {@link DialogFragment} class with
3951 * {@link FragmentManager} instead; this is also
3952 * available on older platforms through the Android compatibility package.
3955 public final boolean showDialog(int id, Bundle args) {
3956 if (mManagedDialogs == null) {
3957 mManagedDialogs = new SparseArray<ManagedDialog>();
3959 ManagedDialog md = mManagedDialogs.get(id);
3961 md = new ManagedDialog();
3962 md.mDialog = createDialog(id, null, args);
3963 if (md.mDialog == null) {
3966 mManagedDialogs.put(id, md);
3970 onPrepareDialog(id, md.mDialog, args);
3976 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
3978 * @param id The id of the managed dialog.
3980 * @throws IllegalArgumentException if the id was not previously shown via
3981 * {@link #showDialog(int)}.
3983 * @see #onCreateDialog(int, Bundle)
3984 * @see #onPrepareDialog(int, Dialog, Bundle)
3985 * @see #showDialog(int)
3986 * @see #removeDialog(int)
3988 * @deprecated Use the new {@link DialogFragment} class with
3989 * {@link FragmentManager} instead; this is also
3990 * available on older platforms through the Android compatibility package.
3993 public final void dismissDialog(int id) {
3994 if (mManagedDialogs == null) {
3995 throw missingDialog(id);
3998 final ManagedDialog md = mManagedDialogs.get(id);
4000 throw missingDialog(id);
4002 md.mDialog.dismiss();
4006 * Creates an exception to throw if a user passed in a dialog id that is
4009 private IllegalArgumentException missingDialog(int id) {
4010 return new IllegalArgumentException("no dialog with id " + id + " was ever "
4011 + "shown via Activity#showDialog");
4015 * Removes any internal references to a dialog managed by this Activity.
4016 * If the dialog is showing, it will dismiss it as part of the clean up.
4018 * <p>This can be useful if you know that you will never show a dialog again and
4019 * want to avoid the overhead of saving and restoring it in the future.
4021 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
4022 * will not throw an exception if you try to remove an ID that does not
4023 * currently have an associated dialog.</p>
4025 * @param id The id of the managed dialog.
4027 * @see #onCreateDialog(int, Bundle)
4028 * @see #onPrepareDialog(int, Dialog, Bundle)
4029 * @see #showDialog(int)
4030 * @see #dismissDialog(int)
4032 * @deprecated Use the new {@link DialogFragment} class with
4033 * {@link FragmentManager} instead; this is also
4034 * available on older platforms through the Android compatibility package.
4037 public final void removeDialog(int id) {
4038 if (mManagedDialogs != null) {
4039 final ManagedDialog md = mManagedDialogs.get(id);
4041 md.mDialog.dismiss();
4042 mManagedDialogs.remove(id);
4048 * This hook is called when the user signals the desire to start a search.
4050 * <p>You can use this function as a simple way to launch the search UI, in response to a
4051 * menu item, search button, or other widgets within your activity. Unless overidden,
4052 * calling this function is the same as calling
4053 * {@link #startSearch startSearch(null, false, null, false)}, which launches
4054 * search for the current activity as specified in its manifest, see {@link SearchManager}.
4056 * <p>You can override this function to force global search, e.g. in response to a dedicated
4057 * search key, or to block search entirely (by simply returning false).
4059 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
4060 * implementation changes to simply return false and you must supply your own custom
4061 * implementation if you want to support search.</p>
4063 * @param searchEvent The {@link SearchEvent} that signaled this search.
4064 * @return Returns {@code true} if search launched, and {@code false} if the activity does
4065 * not respond to search. The default implementation always returns {@code true}, except
4066 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
4068 * @see android.app.SearchManager
4070 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
4071 mSearchEvent = searchEvent;
4072 boolean result = onSearchRequested();
4073 mSearchEvent = null;
4078 * @see #onSearchRequested(SearchEvent)
4080 public boolean onSearchRequested() {
4081 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
4082 != Configuration.UI_MODE_TYPE_TELEVISION) {
4083 startSearch(null, false, null, false);
4091 * During the onSearchRequested() callbacks, this function will return the
4092 * {@link SearchEvent} that triggered the callback, if it exists.
4094 * @return SearchEvent The SearchEvent that triggered the {@link
4095 * #onSearchRequested} callback.
4097 public final SearchEvent getSearchEvent() {
4098 return mSearchEvent;
4102 * This hook is called to launch the search UI.
4104 * <p>It is typically called from onSearchRequested(), either directly from
4105 * Activity.onSearchRequested() or from an overridden version in any given
4106 * Activity. If your goal is simply to activate search, it is preferred to call
4107 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
4108 * is to inject specific data such as context data, it is preferred to <i>override</i>
4109 * onSearchRequested(), so that any callers to it will benefit from the override.
4111 * @param initialQuery Any non-null non-empty string will be inserted as
4112 * pre-entered text in the search query box.
4113 * @param selectInitialQuery If true, the initial query will be preselected, which means that
4114 * any further typing will replace it. This is useful for cases where an entire pre-formed
4115 * query is being inserted. If false, the selection point will be placed at the end of the
4116 * inserted query. This is useful when the inserted query is text that the user entered,
4117 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
4118 * if initialQuery is a non-empty string.</i>
4119 * @param appSearchData An application can insert application-specific
4120 * context here, in order to improve quality or specificity of its own
4121 * searches. This data will be returned with SEARCH intent(s). Null if
4122 * no extra data is required.
4123 * @param globalSearch If false, this will only launch the search that has been specifically
4124 * defined by the application (which is usually defined as a local search). If no default
4125 * search is defined in the current application or activity, global search will be launched.
4126 * If true, this will always launch a platform-global (e.g. web-based) search instead.
4128 * @see android.app.SearchManager
4129 * @see #onSearchRequested
4131 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
4132 @Nullable Bundle appSearchData, boolean globalSearch) {
4133 ensureSearchManager();
4134 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
4135 appSearchData, globalSearch);
4139 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
4140 * the search dialog. Made available for testing purposes.
4142 * @param query The query to trigger. If empty, the request will be ignored.
4143 * @param appSearchData An application can insert application-specific
4144 * context here, in order to improve quality or specificity of its own
4145 * searches. This data will be returned with SEARCH intent(s). Null if
4146 * no extra data is required.
4148 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
4149 ensureSearchManager();
4150 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
4154 * Request that key events come to this activity. Use this if your
4155 * activity has no views with focus, but the activity still wants
4156 * a chance to process key events.
4158 * @see android.view.Window#takeKeyEvents
4160 public void takeKeyEvents(boolean get) {
4161 getWindow().takeKeyEvents(get);
4165 * Enable extended window features. This is a convenience for calling
4166 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
4168 * @param featureId The desired feature as defined in
4169 * {@link android.view.Window}.
4170 * @return Returns true if the requested feature is supported and now
4173 * @see android.view.Window#requestFeature
4175 public final boolean requestWindowFeature(int featureId) {
4176 return getWindow().requestFeature(featureId);
4180 * Convenience for calling
4181 * {@link android.view.Window#setFeatureDrawableResource}.
4183 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
4184 getWindow().setFeatureDrawableResource(featureId, resId);
4188 * Convenience for calling
4189 * {@link android.view.Window#setFeatureDrawableUri}.
4191 public final void setFeatureDrawableUri(int featureId, Uri uri) {
4192 getWindow().setFeatureDrawableUri(featureId, uri);
4196 * Convenience for calling
4197 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
4199 public final void setFeatureDrawable(int featureId, Drawable drawable) {
4200 getWindow().setFeatureDrawable(featureId, drawable);
4204 * Convenience for calling
4205 * {@link android.view.Window#setFeatureDrawableAlpha}.
4207 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
4208 getWindow().setFeatureDrawableAlpha(featureId, alpha);
4212 * Convenience for calling
4213 * {@link android.view.Window#getLayoutInflater}.
4216 public LayoutInflater getLayoutInflater() {
4217 return getWindow().getLayoutInflater();
4221 * Returns a {@link MenuInflater} with this context.
4224 public MenuInflater getMenuInflater() {
4225 // Make sure that action views can get an appropriate theme.
4226 if (mMenuInflater == null) {
4227 initWindowDecorActionBar();
4228 if (mActionBar != null) {
4229 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
4231 mMenuInflater = new MenuInflater(this);
4234 return mMenuInflater;
4238 public void setTheme(int resid) {
4239 super.setTheme(resid);
4240 mWindow.setTheme(resid);
4244 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
4246 if (mParent == null) {
4247 super.onApplyThemeResource(theme, resid, first);
4250 theme.setTo(mParent.getTheme());
4251 } catch (Exception e) {
4254 theme.applyStyle(resid, false);
4257 // Get the primary color and update the TaskDescription for this activity
4258 TypedArray a = theme.obtainStyledAttributes(
4259 com.android.internal.R.styleable.ActivityTaskDescription);
4260 if (mTaskDescription.getPrimaryColor() == 0) {
4261 int colorPrimary = a.getColor(
4262 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
4263 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
4264 mTaskDescription.setPrimaryColor(colorPrimary);
4268 int colorBackground = a.getColor(
4269 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
4270 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
4271 mTaskDescription.setBackgroundColor(colorBackground);
4274 final int statusBarColor = a.getColor(
4275 com.android.internal.R.styleable.ActivityTaskDescription_statusBarColor, 0);
4276 if (statusBarColor != 0) {
4277 mTaskDescription.setStatusBarColor(statusBarColor);
4280 final int navigationBarColor = a.getColor(
4281 com.android.internal.R.styleable.ActivityTaskDescription_navigationBarColor, 0);
4282 if (navigationBarColor != 0) {
4283 mTaskDescription.setNavigationBarColor(navigationBarColor);
4287 setTaskDescription(mTaskDescription);
4291 * Requests permissions to be granted to this application. These permissions
4292 * must be requested in your manifest, they should not be granted to your app,
4293 * and they should have protection level {@link android.content.pm.PermissionInfo
4294 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
4295 * the platform or a third-party app.
4297 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
4298 * are granted at install time if requested in the manifest. Signature permissions
4299 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
4300 * install time if requested in the manifest and the signature of your app matches
4301 * the signature of the app declaring the permissions.
4304 * If your app does not have the requested permissions the user will be presented
4305 * with UI for accepting them. After the user has accepted or rejected the
4306 * requested permissions you will receive a callback on {@link
4307 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
4308 * permissions were granted or not.
4311 * Note that requesting a permission does not guarantee it will be granted and
4312 * your app should be able to run without having this permission.
4315 * This method may start an activity allowing the user to choose which permissions
4316 * to grant and which to reject. Hence, you should be prepared that your activity
4317 * may be paused and resumed. Further, granting some permissions may require
4318 * a restart of you application. In such a case, the system will recreate the
4319 * activity stack before delivering the result to {@link
4320 * #onRequestPermissionsResult(int, String[], int[])}.
4323 * When checking whether you have a permission you should use {@link
4324 * #checkSelfPermission(String)}.
4327 * Calling this API for permissions already granted to your app would show UI
4328 * to the user to decide whether the app can still hold these permissions. This
4329 * can be useful if the way your app uses data guarded by the permissions
4330 * changes significantly.
4333 * You cannot request a permission if your activity sets {@link
4334 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
4335 * <code>true</code> because in this case the activity would not receive
4336 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
4339 * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html">
4340 * RuntimePermissions</a> sample app demonstrates how to use this method to
4341 * request permissions at run time.
4344 * @param permissions The requested permissions. Must me non-null and not empty.
4345 * @param requestCode Application specific request code to match with a result
4346 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
4349 * @throws IllegalArgumentException if requestCode is negative.
4351 * @see #onRequestPermissionsResult(int, String[], int[])
4352 * @see #checkSelfPermission(String)
4353 * @see #shouldShowRequestPermissionRationale(String)
4355 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
4356 if (requestCode < 0) {
4357 throw new IllegalArgumentException("requestCode should be >= 0");
4359 if (mHasCurrentPermissionsRequest) {
4360 Log.w(TAG, "Can reqeust only one set of permissions at a time");
4361 // Dispatch the callback with empty arrays which means a cancellation.
4362 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
4365 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
4366 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
4367 mHasCurrentPermissionsRequest = true;
4371 * Callback for the result from requesting permissions. This method
4372 * is invoked for every call on {@link #requestPermissions(String[], int)}.
4374 * <strong>Note:</strong> It is possible that the permissions request interaction
4375 * with the user is interrupted. In this case you will receive empty permissions
4376 * and results arrays which should be treated as a cancellation.
4379 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
4380 * @param permissions The requested permissions. Never null.
4381 * @param grantResults The grant results for the corresponding permissions
4382 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
4383 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
4385 * @see #requestPermissions(String[], int)
4387 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
4388 @NonNull int[] grantResults) {
4389 /* callback - no nothing */
4393 * Gets whether you should show UI with rationale for requesting a permission.
4394 * You should do this only if you do not have the permission and the context in
4395 * which the permission is requested does not clearly communicate to the user
4396 * what would be the benefit from granting this permission.
4398 * For example, if you write a camera app, requesting the camera permission
4399 * would be expected by the user and no rationale for why it is requested is
4400 * needed. If however, the app needs location for tagging photos then a non-tech
4401 * savvy user may wonder how location is related to taking photos. In this case
4402 * you may choose to show UI with rationale of requesting this permission.
4405 * @param permission A permission your app wants to request.
4406 * @return Whether you can show permission rationale UI.
4408 * @see #checkSelfPermission(String)
4409 * @see #requestPermissions(String[], int)
4410 * @see #onRequestPermissionsResult(int, String[], int[])
4412 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
4413 return getPackageManager().shouldShowRequestPermissionRationale(permission);
4417 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
4420 * @param intent The intent to start.
4421 * @param requestCode If >= 0, this code will be returned in
4422 * onActivityResult() when the activity exits.
4424 * @throws android.content.ActivityNotFoundException
4426 * @see #startActivity
4428 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
4429 startActivityForResult(intent, requestCode, null);
4433 * Launch an activity for which you would like a result when it finished.
4434 * When this activity exits, your
4435 * onActivityResult() method will be called with the given requestCode.
4436 * Using a negative requestCode is the same as calling
4437 * {@link #startActivity} (the activity is not launched as a sub-activity).
4439 * <p>Note that this method should only be used with Intent protocols
4440 * that are defined to return a result. In other protocols (such as
4441 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
4442 * not get the result when you expect. For example, if the activity you
4443 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
4444 * run in your task and thus you will immediately receive a cancel result.
4446 * <p>As a special case, if you call startActivityForResult() with a requestCode
4447 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
4448 * activity, then your window will not be displayed until a result is
4449 * returned back from the started activity. This is to avoid visible
4450 * flickering when redirecting to another activity.
4452 * <p>This method throws {@link android.content.ActivityNotFoundException}
4453 * if there was no Activity found to run the given Intent.
4455 * @param intent The intent to start.
4456 * @param requestCode If >= 0, this code will be returned in
4457 * onActivityResult() when the activity exits.
4458 * @param options Additional options for how the Activity should be started.
4459 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4460 * Context.startActivity(Intent, Bundle)} for more details.
4462 * @throws android.content.ActivityNotFoundException
4464 * @see #startActivity
4466 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
4467 @Nullable Bundle options) {
4468 if (mParent == null) {
4469 options = transferSpringboardActivityOptions(options);
4470 Instrumentation.ActivityResult ar =
4471 mInstrumentation.execStartActivity(
4472 this, mMainThread.getApplicationThread(), mToken, this,
4473 intent, requestCode, options);
4475 mMainThread.sendActivityResult(
4476 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4477 ar.getResultData());
4479 if (requestCode >= 0) {
4480 // If this start is requesting a result, we can avoid making
4481 // the activity visible until the result is received. Setting
4482 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4483 // activity hidden during this time, to avoid flickering.
4484 // This can only be done when a result is requested because
4485 // that guarantees we will get information back when the
4486 // activity is finished, no matter what happens to it.
4487 mStartedActivity = true;
4490 cancelInputsAndStartExitTransition(options);
4491 // TODO Consider clearing/flushing other event sources and events for child windows.
4493 if (options != null) {
4494 mParent.startActivityFromChild(this, intent, requestCode, options);
4496 // Note we want to go through this method for compatibility with
4497 // existing applications that may have overridden it.
4498 mParent.startActivityFromChild(this, intent, requestCode);
4504 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
4506 * @param options The ActivityOptions bundle used to start an Activity.
4508 private void cancelInputsAndStartExitTransition(Bundle options) {
4509 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
4510 if (decor != null) {
4511 decor.cancelPendingInputEvents();
4513 if (options != null && !isTopOfTask()) {
4514 mActivityTransitionState.startExitOutTransition(this, options);
4519 * Returns whether there are any activity transitions currently running on this
4520 * activity. A return value of {@code true} can mean that either an enter or
4521 * exit transition is running, including whether the background of the activity
4522 * is animating as a part of that transition.
4524 * @return true if a transition is currently running on this activity, false otherwise.
4526 public boolean isActivityTransitionRunning() {
4527 return mActivityTransitionState.isTransitionRunning();
4530 private Bundle transferSpringboardActivityOptions(Bundle options) {
4531 if (options == null && (mWindow != null && !mWindow.isActive())) {
4532 final ActivityOptions activityOptions = getActivityOptions();
4533 if (activityOptions != null &&
4534 activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
4535 return activityOptions.toBundle();
4542 * @hide Implement to provide correct calling token.
4544 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
4545 startActivityForResultAsUser(intent, requestCode, null, user);
4549 * @hide Implement to provide correct calling token.
4551 public void startActivityForResultAsUser(Intent intent, int requestCode,
4552 @Nullable Bundle options, UserHandle user) {
4553 startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
4557 * @hide Implement to provide correct calling token.
4559 public void startActivityForResultAsUser(Intent intent, String resultWho, int requestCode,
4560 @Nullable Bundle options, UserHandle user) {
4561 if (mParent != null) {
4562 throw new RuntimeException("Can't be called from a child");
4564 options = transferSpringboardActivityOptions(options);
4565 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4566 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
4569 mMainThread.sendActivityResult(
4570 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4572 if (requestCode >= 0) {
4573 // If this start is requesting a result, we can avoid making
4574 // the activity visible until the result is received. Setting
4575 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4576 // activity hidden during this time, to avoid flickering.
4577 // This can only be done when a result is requested because
4578 // that guarantees we will get information back when the
4579 // activity is finished, no matter what happens to it.
4580 mStartedActivity = true;
4583 cancelInputsAndStartExitTransition(options);
4587 * @hide Implement to provide correct calling token.
4589 public void startActivityAsUser(Intent intent, UserHandle user) {
4590 startActivityAsUser(intent, null, user);
4594 * @hide Implement to provide correct calling token.
4596 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4597 if (mParent != null) {
4598 throw new RuntimeException("Can't be called from a child");
4600 options = transferSpringboardActivityOptions(options);
4601 Instrumentation.ActivityResult ar =
4602 mInstrumentation.execStartActivity(
4603 this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
4604 intent, -1, options, user);
4606 mMainThread.sendActivityResult(
4607 mToken, mEmbeddedID, -1, ar.getResultCode(),
4608 ar.getResultData());
4610 cancelInputsAndStartExitTransition(options);
4614 * Start a new activity as if it was started by the activity that started our
4615 * current activity. This is for the resolver and chooser activities, which operate
4616 * as intermediaries that dispatch their intent to the target the user selects -- to
4617 * do this, they must perform all security checks including permission grants as if
4618 * their launch had come from the original activity.
4619 * @param intent The Intent to start.
4620 * @param options ActivityOptions or null.
4621 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4622 * caller it is doing the start is, is actually allowed to start the target activity.
4623 * If you set this to true, you must set an explicit component in the Intent and do any
4624 * appropriate security checks yourself.
4625 * @param userId The user the new activity should run as.
4628 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4629 boolean ignoreTargetSecurity, int userId) {
4630 if (mParent != null) {
4631 throw new RuntimeException("Can't be called from a child");
4633 options = transferSpringboardActivityOptions(options);
4634 Instrumentation.ActivityResult ar =
4635 mInstrumentation.execStartActivityAsCaller(
4636 this, mMainThread.getApplicationThread(), mToken, this,
4637 intent, -1, options, ignoreTargetSecurity, userId);
4639 mMainThread.sendActivityResult(
4640 mToken, mEmbeddedID, -1, ar.getResultCode(),
4641 ar.getResultData());
4643 cancelInputsAndStartExitTransition(options);
4647 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4648 * Intent, int, int, int, Bundle)} with no options.
4650 * @param intent The IntentSender to launch.
4651 * @param requestCode If >= 0, this code will be returned in
4652 * onActivityResult() when the activity exits.
4653 * @param fillInIntent If non-null, this will be provided as the
4654 * intent parameter to {@link IntentSender#sendIntent}.
4655 * @param flagsMask Intent flags in the original IntentSender that you
4656 * would like to change.
4657 * @param flagsValues Desired values for any bits set in
4658 * <var>flagsMask</var>
4659 * @param extraFlags Always set to 0.
4661 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4662 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4663 throws IntentSender.SendIntentException {
4664 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4665 flagsValues, extraFlags, null);
4669 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4670 * to use a IntentSender to describe the activity to be started. If
4671 * the IntentSender is for an activity, that activity will be started
4672 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4673 * here; otherwise, its associated action will be executed (such as
4674 * sending a broadcast) as if you had called
4675 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4677 * @param intent The IntentSender to launch.
4678 * @param requestCode If >= 0, this code will be returned in
4679 * onActivityResult() when the activity exits.
4680 * @param fillInIntent If non-null, this will be provided as the
4681 * intent parameter to {@link IntentSender#sendIntent}.
4682 * @param flagsMask Intent flags in the original IntentSender that you
4683 * would like to change.
4684 * @param flagsValues Desired values for any bits set in
4685 * <var>flagsMask</var>
4686 * @param extraFlags Always set to 0.
4687 * @param options Additional options for how the Activity should be started.
4688 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4689 * Context.startActivity(Intent, Bundle)} for more details. If options
4690 * have also been supplied by the IntentSender, options given here will
4691 * override any that conflict with those given by the IntentSender.
4693 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4694 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4695 Bundle options) throws IntentSender.SendIntentException {
4696 if (mParent == null) {
4697 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
4698 flagsMask, flagsValues, options);
4699 } else if (options != null) {
4700 mParent.startIntentSenderFromChild(this, intent, requestCode,
4701 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4703 // Note we want to go through this call for compatibility with
4704 // existing applications that may have overridden the method.
4705 mParent.startIntentSenderFromChild(this, intent, requestCode,
4706 fillInIntent, flagsMask, flagsValues, extraFlags);
4710 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
4711 Intent fillInIntent, int flagsMask, int flagsValues,
4713 throws IntentSender.SendIntentException {
4715 String resolvedType = null;
4716 if (fillInIntent != null) {
4717 fillInIntent.migrateExtraStreamToClipData();
4718 fillInIntent.prepareToLeaveProcess(this);
4719 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4721 int result = ActivityManager.getService()
4722 .startActivityIntentSender(mMainThread.getApplicationThread(),
4723 intent != null ? intent.getTarget() : null,
4724 intent != null ? intent.getWhitelistToken() : null,
4725 fillInIntent, resolvedType, mToken, who,
4726 requestCode, flagsMask, flagsValues, options);
4727 if (result == ActivityManager.START_CANCELED) {
4728 throw new IntentSender.SendIntentException();
4730 Instrumentation.checkStartActivityResult(result, null);
4731 } catch (RemoteException e) {
4733 if (requestCode >= 0) {
4734 // If this start is requesting a result, we can avoid making
4735 // the activity visible until the result is received. Setting
4736 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4737 // activity hidden during this time, to avoid flickering.
4738 // This can only be done when a result is requested because
4739 // that guarantees we will get information back when the
4740 // activity is finished, no matter what happens to it.
4741 mStartedActivity = true;
4746 * Same as {@link #startActivity(Intent, Bundle)} with no options
4749 * @param intent The intent to start.
4751 * @throws android.content.ActivityNotFoundException
4753 * @see #startActivity(Intent, Bundle)
4754 * @see #startActivityForResult
4757 public void startActivity(Intent intent) {
4758 this.startActivity(intent, null);
4762 * Launch a new activity. You will not receive any information about when
4763 * the activity exits. This implementation overrides the base version,
4764 * providing information about
4765 * the activity performing the launch. Because of this additional
4766 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4767 * required; if not specified, the new activity will be added to the
4768 * task of the caller.
4770 * <p>This method throws {@link android.content.ActivityNotFoundException}
4771 * if there was no Activity found to run the given Intent.
4773 * @param intent The intent to start.
4774 * @param options Additional options for how the Activity should be started.
4775 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4776 * Context.startActivity(Intent, Bundle)} for more details.
4778 * @throws android.content.ActivityNotFoundException
4780 * @see #startActivity(Intent)
4781 * @see #startActivityForResult
4784 public void startActivity(Intent intent, @Nullable Bundle options) {
4785 if (options != null) {
4786 startActivityForResult(intent, -1, options);
4788 // Note we want to go through this call for compatibility with
4789 // applications that may have overridden the method.
4790 startActivityForResult(intent, -1);
4795 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4798 * @param intents The intents to start.
4800 * @throws android.content.ActivityNotFoundException
4802 * @see #startActivities(Intent[], Bundle)
4803 * @see #startActivityForResult
4806 public void startActivities(Intent[] intents) {
4807 startActivities(intents, null);
4811 * Launch a new activity. You will not receive any information about when
4812 * the activity exits. This implementation overrides the base version,
4813 * providing information about
4814 * the activity performing the launch. Because of this additional
4815 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4816 * required; if not specified, the new activity will be added to the
4817 * task of the caller.
4819 * <p>This method throws {@link android.content.ActivityNotFoundException}
4820 * if there was no Activity found to run the given Intent.
4822 * @param intents The intents to start.
4823 * @param options Additional options for how the Activity should be started.
4824 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4825 * Context.startActivity(Intent, Bundle)} for more details.
4827 * @throws android.content.ActivityNotFoundException
4829 * @see #startActivities(Intent[])
4830 * @see #startActivityForResult
4833 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4834 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4835 mToken, this, intents, options);
4839 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4842 * @param intent The IntentSender to launch.
4843 * @param fillInIntent If non-null, this will be provided as the
4844 * intent parameter to {@link IntentSender#sendIntent}.
4845 * @param flagsMask Intent flags in the original IntentSender that you
4846 * would like to change.
4847 * @param flagsValues Desired values for any bits set in
4848 * <var>flagsMask</var>
4849 * @param extraFlags Always set to 0.
4851 public void startIntentSender(IntentSender intent,
4852 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4853 throws IntentSender.SendIntentException {
4854 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4859 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4861 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4862 * for more information.
4864 * @param intent The IntentSender to launch.
4865 * @param fillInIntent If non-null, this will be provided as the
4866 * intent parameter to {@link IntentSender#sendIntent}.
4867 * @param flagsMask Intent flags in the original IntentSender that you
4868 * would like to change.
4869 * @param flagsValues Desired values for any bits set in
4870 * <var>flagsMask</var>
4871 * @param extraFlags Always set to 0.
4872 * @param options Additional options for how the Activity should be started.
4873 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4874 * Context.startActivity(Intent, Bundle)} for more details. If options
4875 * have also been supplied by the IntentSender, options given here will
4876 * override any that conflict with those given by the IntentSender.
4878 public void startIntentSender(IntentSender intent,
4879 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4880 Bundle options) throws IntentSender.SendIntentException {
4881 if (options != null) {
4882 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4883 flagsValues, extraFlags, options);
4885 // Note we want to go through this call for compatibility with
4886 // applications that may have overridden the method.
4887 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4888 flagsValues, extraFlags);
4893 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4896 * @param intent The intent to start.
4897 * @param requestCode If >= 0, this code will be returned in
4898 * onActivityResult() when the activity exits, as described in
4899 * {@link #startActivityForResult}.
4901 * @return If a new activity was launched then true is returned; otherwise
4902 * false is returned and you must handle the Intent yourself.
4904 * @see #startActivity
4905 * @see #startActivityForResult
4907 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4909 return startActivityIfNeeded(intent, requestCode, null);
4913 * A special variation to launch an activity only if a new activity
4914 * instance is needed to handle the given Intent. In other words, this is
4915 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4916 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4917 * singleTask or singleTop
4918 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4920 * that handles <var>intent</var> is the same as your currently running
4921 * activity, then a new instance is not needed. In this case, instead of
4922 * the normal behavior of calling {@link #onNewIntent} this function will
4923 * return and you can handle the Intent yourself.
4925 * <p>This function can only be called from a top-level activity; if it is
4926 * called from a child activity, a runtime exception will be thrown.
4928 * @param intent The intent to start.
4929 * @param requestCode If >= 0, this code will be returned in
4930 * onActivityResult() when the activity exits, as described in
4931 * {@link #startActivityForResult}.
4932 * @param options Additional options for how the Activity should be started.
4933 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4934 * Context.startActivity(Intent, Bundle)} for more details.
4936 * @return If a new activity was launched then true is returned; otherwise
4937 * false is returned and you must handle the Intent yourself.
4939 * @see #startActivity
4940 * @see #startActivityForResult
4942 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4943 int requestCode, @Nullable Bundle options) {
4944 if (mParent == null) {
4945 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4947 Uri referrer = onProvideReferrer();
4948 if (referrer != null) {
4949 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4951 intent.migrateExtraStreamToClipData();
4952 intent.prepareToLeaveProcess(this);
4953 result = ActivityManager.getService()
4954 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4955 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4956 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4958 } catch (RemoteException e) {
4962 Instrumentation.checkStartActivityResult(result, intent);
4964 if (requestCode >= 0) {
4965 // If this start is requesting a result, we can avoid making
4966 // the activity visible until the result is received. Setting
4967 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4968 // activity hidden during this time, to avoid flickering.
4969 // This can only be done when a result is requested because
4970 // that guarantees we will get information back when the
4971 // activity is finished, no matter what happens to it.
4972 mStartedActivity = true;
4974 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
4977 throw new UnsupportedOperationException(
4978 "startActivityIfNeeded can only be called from a top-level activity");
4982 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
4985 * @param intent The intent to dispatch to the next activity. For
4986 * correct behavior, this must be the same as the Intent that started
4987 * your own activity; the only changes you can make are to the extras
4990 * @return Returns a boolean indicating whether there was another Activity
4991 * to start: true if there was a next activity to start, false if there
4992 * wasn't. In general, if true is returned you will then want to call
4993 * finish() on yourself.
4995 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
4996 return startNextMatchingActivity(intent, null);
5000 * Special version of starting an activity, for use when you are replacing
5001 * other activity components. You can use this to hand the Intent off
5002 * to the next Activity that can handle it. You typically call this in
5003 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
5005 * @param intent The intent to dispatch to the next activity. For
5006 * correct behavior, this must be the same as the Intent that started
5007 * your own activity; the only changes you can make are to the extras
5009 * @param options Additional options for how the Activity should be started.
5010 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5011 * Context.startActivity(Intent, Bundle)} for more details.
5013 * @return Returns a boolean indicating whether there was another Activity
5014 * to start: true if there was a next activity to start, false if there
5015 * wasn't. In general, if true is returned you will then want to call
5016 * finish() on yourself.
5018 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
5019 @Nullable Bundle options) {
5020 if (mParent == null) {
5022 intent.migrateExtraStreamToClipData();
5023 intent.prepareToLeaveProcess(this);
5024 return ActivityManager.getService()
5025 .startNextMatchingActivity(mToken, intent, options);
5026 } catch (RemoteException e) {
5032 throw new UnsupportedOperationException(
5033 "startNextMatchingActivity can only be called from a top-level activity");
5037 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
5040 * @param child The activity making the call.
5041 * @param intent The intent to start.
5042 * @param requestCode Reply request code. < 0 if reply is not requested.
5044 * @throws android.content.ActivityNotFoundException
5046 * @see #startActivity
5047 * @see #startActivityForResult
5049 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5051 startActivityFromChild(child, intent, requestCode, null);
5055 * This is called when a child activity of this one calls its
5056 * {@link #startActivity} or {@link #startActivityForResult} method.
5058 * <p>This method throws {@link android.content.ActivityNotFoundException}
5059 * if there was no Activity found to run the given Intent.
5061 * @param child The activity making the call.
5062 * @param intent The intent to start.
5063 * @param requestCode Reply request code. < 0 if reply is not requested.
5064 * @param options Additional options for how the Activity should be started.
5065 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5066 * Context.startActivity(Intent, Bundle)} for more details.
5068 * @throws android.content.ActivityNotFoundException
5070 * @see #startActivity
5071 * @see #startActivityForResult
5073 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5074 int requestCode, @Nullable Bundle options) {
5075 options = transferSpringboardActivityOptions(options);
5076 Instrumentation.ActivityResult ar =
5077 mInstrumentation.execStartActivity(
5078 this, mMainThread.getApplicationThread(), mToken, child,
5079 intent, requestCode, options);
5081 mMainThread.sendActivityResult(
5082 mToken, child.mEmbeddedID, requestCode,
5083 ar.getResultCode(), ar.getResultData());
5085 cancelInputsAndStartExitTransition(options);
5089 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
5092 * @param fragment The fragment making the call.
5093 * @param intent The intent to start.
5094 * @param requestCode Reply request code. < 0 if reply is not requested.
5096 * @throws android.content.ActivityNotFoundException
5098 * @see Fragment#startActivity
5099 * @see Fragment#startActivityForResult
5101 public void startActivityFromFragment(@NonNull Fragment fragment,
5102 @RequiresPermission Intent intent, int requestCode) {
5103 startActivityFromFragment(fragment, intent, requestCode, null);
5107 * This is called when a Fragment in this activity calls its
5108 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
5111 * <p>This method throws {@link android.content.ActivityNotFoundException}
5112 * if there was no Activity found to run the given Intent.
5114 * @param fragment The fragment making the call.
5115 * @param intent The intent to start.
5116 * @param requestCode Reply request code. < 0 if reply is not requested.
5117 * @param options Additional options for how the Activity should be started.
5118 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5119 * Context.startActivity(Intent, Bundle)} for more details.
5121 * @throws android.content.ActivityNotFoundException
5123 * @see Fragment#startActivity
5124 * @see Fragment#startActivityForResult
5126 public void startActivityFromFragment(@NonNull Fragment fragment,
5127 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
5128 startActivityForResult(fragment.mWho, intent, requestCode, options);
5134 public void startActivityAsUserFromFragment(@NonNull Fragment fragment,
5135 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
5137 startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
5144 public void startActivityForResult(
5145 String who, Intent intent, int requestCode, @Nullable Bundle options) {
5146 Uri referrer = onProvideReferrer();
5147 if (referrer != null) {
5148 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5150 options = transferSpringboardActivityOptions(options);
5151 Instrumentation.ActivityResult ar =
5152 mInstrumentation.execStartActivity(
5153 this, mMainThread.getApplicationThread(), mToken, who,
5154 intent, requestCode, options);
5156 mMainThread.sendActivityResult(
5157 mToken, who, requestCode,
5158 ar.getResultCode(), ar.getResultData());
5160 cancelInputsAndStartExitTransition(options);
5167 public boolean canStartActivityForResult() {
5172 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
5173 * int, Intent, int, int, int, Bundle)} with no options.
5175 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5176 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5178 throws IntentSender.SendIntentException {
5179 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
5180 flagsMask, flagsValues, extraFlags, null);
5184 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
5185 * taking a IntentSender; see
5186 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5187 * for more information.
5189 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5190 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5191 int extraFlags, @Nullable Bundle options)
5192 throws IntentSender.SendIntentException {
5193 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
5194 flagsMask, flagsValues, options);
5198 * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see
5199 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5200 * for more information.
5204 public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent,
5205 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5206 int extraFlags, @Nullable Bundle options)
5207 throws IntentSender.SendIntentException {
5208 startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent,
5209 flagsMask, flagsValues, options);
5213 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
5214 * or {@link #finish} to specify an explicit transition animation to
5217 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
5218 * to using this with starting activities is to supply the desired animation
5219 * information through a {@link ActivityOptions} bundle to
5220 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
5221 * you to specify a custom animation even when starting an activity from
5222 * outside the context of the current top activity.
5224 * @param enterAnim A resource ID of the animation resource to use for
5225 * the incoming activity. Use 0 for no animation.
5226 * @param exitAnim A resource ID of the animation resource to use for
5227 * the outgoing activity. Use 0 for no animation.
5229 public void overridePendingTransition(int enterAnim, int exitAnim) {
5231 ActivityManager.getService().overridePendingTransition(
5232 mToken, getPackageName(), enterAnim, exitAnim);
5233 } catch (RemoteException e) {
5238 * Call this to set the result that your activity will return to its
5241 * @param resultCode The result code to propagate back to the originating
5242 * activity, often RESULT_CANCELED or RESULT_OK
5244 * @see #RESULT_CANCELED
5246 * @see #RESULT_FIRST_USER
5247 * @see #setResult(int, Intent)
5249 public final void setResult(int resultCode) {
5250 synchronized (this) {
5251 mResultCode = resultCode;
5257 * Call this to set the result that your activity will return to its
5260 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
5261 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
5262 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
5263 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
5264 * Activity receiving the result access to the specific URIs in the Intent.
5265 * Access will remain until the Activity has finished (it will remain across the hosting
5266 * process being killed and other temporary destruction) and will be added
5267 * to any existing set of URI permissions it already holds.
5269 * @param resultCode The result code to propagate back to the originating
5270 * activity, often RESULT_CANCELED or RESULT_OK
5271 * @param data The data to propagate back to the originating activity.
5273 * @see #RESULT_CANCELED
5275 * @see #RESULT_FIRST_USER
5276 * @see #setResult(int)
5278 public final void setResult(int resultCode, Intent data) {
5279 synchronized (this) {
5280 mResultCode = resultCode;
5286 * Return information about who launched this activity. If the launching Intent
5287 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
5288 * that will be returned as-is; otherwise, if known, an
5289 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
5290 * package name that started the Intent will be returned. This may return null if no
5291 * referrer can be identified -- it is neither explicitly specified, nor is it known which
5292 * application package was involved.
5294 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
5295 * return the referrer that submitted that new intent to the activity. Otherwise, it
5296 * always returns the referrer of the original Intent.</p>
5298 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
5299 * referrer information, applications can spoof it.</p>
5302 public Uri getReferrer() {
5303 Intent intent = getIntent();
5305 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
5306 if (referrer != null) {
5309 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
5310 if (referrerName != null) {
5311 return Uri.parse(referrerName);
5313 } catch (BadParcelableException e) {
5314 Log.w(TAG, "Cannot read referrer from intent;"
5315 + " intent extras contain unknown custom Parcelable objects");
5317 if (mReferrer != null) {
5318 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
5324 * Override to generate the desired referrer for the content currently being shown
5325 * by the app. The default implementation returns null, meaning the referrer will simply
5326 * be the android-app: of the package name of this activity. Return a non-null Uri to
5327 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
5329 public Uri onProvideReferrer() {
5334 * Return the name of the package that invoked this activity. This is who
5335 * the data in {@link #setResult setResult()} will be sent to. You can
5336 * use this information to validate that the recipient is allowed to
5339 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5340 * did not use the {@link #startActivityForResult}
5341 * form that includes a request code), then the calling package will be
5344 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
5345 * the result from this method was unstable. If the process hosting the calling
5346 * package was no longer running, it would return null instead of the proper package
5347 * name. You can use {@link #getCallingActivity()} and retrieve the package name
5348 * from that instead.</p>
5350 * @return The package of the activity that will receive your
5351 * reply, or null if none.
5354 public String getCallingPackage() {
5356 return ActivityManager.getService().getCallingPackage(mToken);
5357 } catch (RemoteException e) {
5363 * Return the name of the activity that invoked this activity. This is
5364 * who the data in {@link #setResult setResult()} will be sent to. You
5365 * can use this information to validate that the recipient is allowed to
5368 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5369 * did not use the {@link #startActivityForResult}
5370 * form that includes a request code), then the calling package will be
5373 * @return The ComponentName of the activity that will receive your
5374 * reply, or null if none.
5377 public ComponentName getCallingActivity() {
5379 return ActivityManager.getService().getCallingActivity(mToken);
5380 } catch (RemoteException e) {
5386 * Control whether this activity's main window is visible. This is intended
5387 * only for the special case of an activity that is not going to show a
5388 * UI itself, but can't just finish prior to onResume() because it needs
5389 * to wait for a service binding or such. Setting this to false allows
5390 * you to prevent your UI from being shown during that time.
5392 * <p>The default value for this is taken from the
5393 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
5395 public void setVisible(boolean visible) {
5396 if (mVisibleFromClient != visible) {
5397 mVisibleFromClient = visible;
5398 if (mVisibleFromServer) {
5399 if (visible) makeVisible();
5400 else mDecor.setVisibility(View.INVISIBLE);
5405 void makeVisible() {
5406 if (!mWindowAdded) {
5407 ViewManager wm = getWindowManager();
5408 wm.addView(mDecor, getWindow().getAttributes());
5409 mWindowAdded = true;
5411 mDecor.setVisibility(View.VISIBLE);
5415 * Check to see whether this activity is in the process of finishing,
5416 * either because you called {@link #finish} on it or someone else
5417 * has requested that it finished. This is often used in
5418 * {@link #onPause} to determine whether the activity is simply pausing or
5419 * completely finishing.
5421 * @return If the activity is finishing, returns true; else returns false.
5425 public boolean isFinishing() {
5430 * Returns true if the final {@link #onDestroy()} call has been made
5431 * on the Activity, so this instance is now dead.
5433 public boolean isDestroyed() {
5438 * Check to see whether this activity is in the process of being destroyed in order to be
5439 * recreated with a new configuration. This is often used in
5440 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
5441 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
5443 * @return If the activity is being torn down in order to be recreated with a new configuration,
5444 * returns true; else returns false.
5446 public boolean isChangingConfigurations() {
5447 return mChangingConfigurations;
5451 * Cause this Activity to be recreated with a new instance. This results
5452 * in essentially the same flow as when the Activity is created due to
5453 * a configuration change -- the current instance will go through its
5454 * lifecycle to {@link #onDestroy} and a new instance then created after it.
5456 public void recreate() {
5457 if (mParent != null) {
5458 throw new IllegalStateException("Can only be called on top-level activity");
5460 if (Looper.myLooper() != mMainThread.getLooper()) {
5461 throw new IllegalStateException("Must be called from main thread");
5464 ActivityManager.getService().requestActivityRelaunch(mToken);
5465 } catch (RemoteException e) {
5470 * Finishes the current activity and specifies whether to remove the task associated with this
5473 private void finish(int finishTask) {
5474 if (mParent == null) {
5477 synchronized (this) {
5478 resultCode = mResultCode;
5479 resultData = mResultData;
5481 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
5483 if (resultData != null) {
5484 resultData.prepareToLeaveProcess(this);
5486 if (ActivityManager.getService()
5487 .finishActivity(mToken, resultCode, resultData, finishTask)) {
5490 } catch (RemoteException e) {
5494 mParent.finishFromChild(this);
5499 * Call this when your activity is done and should be closed. The
5500 * ActivityResult is propagated back to whoever launched you via
5501 * onActivityResult().
5503 public void finish() {
5504 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
5508 * Finish this activity as well as all activities immediately below it
5509 * in the current task that have the same affinity. This is typically
5510 * used when an application can be launched on to another task (such as
5511 * from an ACTION_VIEW of a content type it understands) and the user
5512 * has used the up navigation to switch out of the current task and in
5513 * to its own task. In this case, if the user has navigated down into
5514 * any other activities of the second application, all of those should
5515 * be removed from the original task as part of the task switch.
5517 * <p>Note that this finish does <em>not</em> allow you to deliver results
5518 * to the previous activity, and an exception will be thrown if you are trying
5521 public void finishAffinity() {
5522 if (mParent != null) {
5523 throw new IllegalStateException("Can not be called from an embedded activity");
5525 if (mResultCode != RESULT_CANCELED || mResultData != null) {
5526 throw new IllegalStateException("Can not be called to deliver a result");
5529 if (ActivityManager.getService().finishActivityAffinity(mToken)) {
5532 } catch (RemoteException e) {
5538 * This is called when a child activity of this one calls its
5539 * {@link #finish} method. The default implementation simply calls
5540 * finish() on this activity (the parent), finishing the entire group.
5542 * @param child The activity making the call.
5546 public void finishFromChild(Activity child) {
5551 * Reverses the Activity Scene entry Transition and triggers the calling Activity
5552 * to reverse its exit Transition. When the exit Transition completes,
5553 * {@link #finish()} is called. If no entry Transition was used, finish() is called
5554 * immediately and the Activity exit Transition is run.
5555 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
5557 public void finishAfterTransition() {
5558 if (!mActivityTransitionState.startExitBackTransition(this)) {
5564 * Force finish another activity that you had previously started with
5565 * {@link #startActivityForResult}.
5567 * @param requestCode The request code of the activity that you had
5568 * given to startActivityForResult(). If there are multiple
5569 * activities started with this request code, they
5570 * will all be finished.
5572 public void finishActivity(int requestCode) {
5573 if (mParent == null) {
5575 ActivityManager.getService()
5576 .finishSubActivity(mToken, mEmbeddedID, requestCode);
5577 } catch (RemoteException e) {
5581 mParent.finishActivityFromChild(this, requestCode);
5586 * This is called when a child activity of this one calls its
5589 * @param child The activity making the call.
5590 * @param requestCode Request code that had been used to start the
5593 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
5595 ActivityManager.getService()
5596 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
5597 } catch (RemoteException e) {
5603 * Call this when your activity is done and should be closed and the task should be completely
5604 * removed as a part of finishing the root activity of the task.
5606 public void finishAndRemoveTask() {
5607 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
5611 * Ask that the local app instance of this activity be released to free up its memory.
5612 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5613 * a new instance of the activity will later be re-created if needed due to the user
5614 * navigating back to it.
5616 * @return Returns true if the activity was in a state that it has started the process
5617 * of destroying its current instance; returns false if for any reason this could not
5618 * be done: it is currently visible to the user, it is already being destroyed, it is
5619 * being finished, it hasn't yet saved its state, etc.
5621 public boolean releaseInstance() {
5623 return ActivityManager.getService().releaseActivityInstance(mToken);
5624 } catch (RemoteException e) {
5631 * Called when an activity you launched exits, giving you the requestCode
5632 * you started it with, the resultCode it returned, and any additional
5633 * data from it. The <var>resultCode</var> will be
5634 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5635 * didn't return any result, or crashed during its operation.
5637 * <p>You will receive this call immediately before onResume() when your
5638 * activity is re-starting.
5640 * <p>This method is never invoked if your activity sets
5641 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5642 * <code>true</code>.
5644 * @param requestCode The integer request code originally supplied to
5645 * startActivityForResult(), allowing you to identify who this
5647 * @param resultCode The integer result code returned by the child activity
5648 * through its setResult().
5649 * @param data An Intent, which can return result data to the caller
5650 * (various data can be attached to Intent "extras").
5652 * @see #startActivityForResult
5653 * @see #createPendingResult
5654 * @see #setResult(int)
5656 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5660 * Called when an activity you launched with an activity transition exposes this
5661 * Activity through a returning activity transition, giving you the resultCode
5662 * and any additional data from it. This method will only be called if the activity
5663 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5664 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5666 * <p>The purpose of this function is to let the called Activity send a hint about
5667 * its state so that this underlying Activity can prepare to be exposed. A call to
5668 * this method does not guarantee that the called Activity has or will be exiting soon.
5669 * It only indicates that it will expose this Activity's Window and it has
5670 * some data to pass to prepare it.</p>
5672 * @param resultCode The integer result code returned by the child activity
5673 * through its setResult().
5674 * @param data An Intent, which can return result data to the caller
5675 * (various data can be attached to Intent "extras").
5677 public void onActivityReenter(int resultCode, Intent data) {
5681 * Create a new PendingIntent object which you can hand to others
5682 * for them to use to send result data back to your
5683 * {@link #onActivityResult} callback. The created object will be either
5684 * one-shot (becoming invalid after a result is sent back) or multiple
5685 * (allowing any number of results to be sent through it).
5687 * @param requestCode Private request code for the sender that will be
5688 * associated with the result data when it is returned. The sender can not
5689 * modify this value, allowing you to identify incoming results.
5690 * @param data Default data to supply in the result, which may be modified
5692 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5693 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5694 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5695 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5696 * or any of the flags as supported by
5697 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5698 * of the intent that can be supplied when the actual send happens.
5700 * @return Returns an existing or new PendingIntent matching the given
5701 * parameters. May return null only if
5702 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5705 * @see PendingIntent
5707 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5708 @PendingIntent.Flags int flags) {
5709 String packageName = getPackageName();
5711 data.prepareToLeaveProcess(this);
5712 IIntentSender target =
5713 ActivityManager.getService().getIntentSender(
5714 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5715 mParent == null ? mToken : mParent.mToken,
5716 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5717 UserHandle.myUserId());
5718 return target != null ? new PendingIntent(target) : null;
5719 } catch (RemoteException e) {
5726 * Change the desired orientation of this activity. If the activity
5727 * is currently in the foreground or otherwise impacting the screen
5728 * orientation, the screen will immediately be changed (possibly causing
5729 * the activity to be restarted). Otherwise, this will be used the next
5730 * time the activity is visible.
5732 * @param requestedOrientation An orientation constant as used in
5733 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5735 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5736 if (mParent == null) {
5738 ActivityManager.getService().setRequestedOrientation(
5739 mToken, requestedOrientation);
5740 } catch (RemoteException e) {
5744 mParent.setRequestedOrientation(requestedOrientation);
5749 * Return the current requested orientation of the activity. This will
5750 * either be the orientation requested in its component's manifest, or
5751 * the last requested orientation given to
5752 * {@link #setRequestedOrientation(int)}.
5754 * @return Returns an orientation constant as used in
5755 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5757 @ActivityInfo.ScreenOrientation
5758 public int getRequestedOrientation() {
5759 if (mParent == null) {
5761 return ActivityManager.getService()
5762 .getRequestedOrientation(mToken);
5763 } catch (RemoteException e) {
5767 return mParent.getRequestedOrientation();
5769 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5773 * Return the identifier of the task this activity is in. This identifier
5774 * will remain the same for the lifetime of the activity.
5776 * @return Task identifier, an opaque integer.
5778 public int getTaskId() {
5780 return ActivityManager.getService()
5781 .getTaskForActivity(mToken, false);
5782 } catch (RemoteException e) {
5788 * Return whether this activity is the root of a task. The root is the
5789 * first activity in a task.
5791 * @return True if this is the root activity, else false.
5794 public boolean isTaskRoot() {
5796 return ActivityManager.getService().getTaskForActivity(mToken, true) >= 0;
5797 } catch (RemoteException e) {
5803 * Move the task containing this activity to the back of the activity
5804 * stack. The activity's order within the task is unchanged.
5806 * @param nonRoot If false then this only works if the activity is the root
5807 * of a task; if true it will work for any activity in
5810 * @return If the task was moved (or it was already at the
5811 * back) true is returned, else false.
5813 public boolean moveTaskToBack(boolean nonRoot) {
5815 return ActivityManager.getService().moveActivityTaskToBack(
5817 } catch (RemoteException e) {
5824 * Returns class name for this activity with the package prefix removed.
5825 * This is the default name used to read and write settings.
5827 * @return The local class name.
5830 public String getLocalClassName() {
5831 final String pkg = getPackageName();
5832 final String cls = mComponent.getClassName();
5833 int packageLen = pkg.length();
5834 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5835 || cls.charAt(packageLen) != '.') {
5838 return cls.substring(packageLen+1);
5842 * Returns complete component name of this activity.
5844 * @return Returns the complete component name for this activity
5846 public ComponentName getComponentName()
5852 * Retrieve a {@link SharedPreferences} object for accessing preferences
5853 * that are private to this activity. This simply calls the underlying
5854 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5855 * class name as the preferences name.
5857 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5860 * @return Returns the single SharedPreferences instance that can be used
5861 * to retrieve and modify the preference values.
5863 public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
5864 return getSharedPreferences(getLocalClassName(), mode);
5867 private void ensureSearchManager() {
5868 if (mSearchManager != null) {
5873 mSearchManager = new SearchManager(this, null);
5874 } catch (ServiceNotFoundException e) {
5875 throw new IllegalStateException(e);
5880 public Object getSystemService(@ServiceName @NonNull String name) {
5881 if (getBaseContext() == null) {
5882 throw new IllegalStateException(
5883 "System services not available to Activities before onCreate()");
5886 if (WINDOW_SERVICE.equals(name)) {
5887 return mWindowManager;
5888 } else if (SEARCH_SERVICE.equals(name)) {
5889 ensureSearchManager();
5890 return mSearchManager;
5892 return super.getSystemService(name);
5896 * Change the title associated with this activity. If this is a
5897 * top-level activity, the title for its window will change. If it
5898 * is an embedded activity, the parent can do whatever it wants
5901 public void setTitle(CharSequence title) {
5903 onTitleChanged(title, mTitleColor);
5905 if (mParent != null) {
5906 mParent.onChildTitleChanged(this, title);
5911 * Change the title associated with this activity. If this is a
5912 * top-level activity, the title for its window will change. If it
5913 * is an embedded activity, the parent can do whatever it wants
5916 public void setTitle(int titleId) {
5917 setTitle(getText(titleId));
5921 * Change the color of the title associated with this activity.
5923 * This method is deprecated starting in API Level 11 and replaced by action
5924 * bar styles. For information on styling the Action Bar, read the <a
5925 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5928 * @deprecated Use action bar styles instead.
5931 public void setTitleColor(int textColor) {
5932 mTitleColor = textColor;
5933 onTitleChanged(mTitle, textColor);
5936 public final CharSequence getTitle() {
5940 public final int getTitleColor() {
5944 protected void onTitleChanged(CharSequence title, int color) {
5946 final Window win = getWindow();
5948 win.setTitle(title);
5950 win.setTitleColor(color);
5953 if (mActionBar != null) {
5954 mActionBar.setWindowTitle(title);
5959 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
5963 * Sets information describing the task with this activity for presentation inside the Recents
5964 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
5965 * are traversed in order from the topmost activity to the bottommost. The traversal continues
5966 * for each property until a suitable value is found. For each task the taskDescription will be
5967 * returned in {@link android.app.ActivityManager.TaskDescription}.
5969 * @see ActivityManager#getRecentTasks
5970 * @see android.app.ActivityManager.TaskDescription
5972 * @param taskDescription The TaskDescription properties that describe the task with this activity
5974 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
5975 if (mTaskDescription != taskDescription) {
5976 mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
5977 // Scale the icon down to something reasonable if it is provided
5978 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
5979 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
5980 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
5982 mTaskDescription.setIcon(icon);
5986 ActivityManager.getService().setTaskDescription(mToken, mTaskDescription);
5987 } catch (RemoteException e) {
5992 * Sets the visibility of the progress bar in the title.
5994 * In order for the progress bar to be shown, the feature must be requested
5995 * via {@link #requestWindowFeature(int)}.
5997 * @param visible Whether to show the progress bars in the title.
5998 * @deprecated No longer supported starting in API 21.
6001 public final void setProgressBarVisibility(boolean visible) {
6002 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
6003 Window.PROGRESS_VISIBILITY_OFF);
6007 * Sets the visibility of the indeterminate progress bar in the title.
6009 * In order for the progress bar to be shown, the feature must be requested
6010 * via {@link #requestWindowFeature(int)}.
6012 * @param visible Whether to show the progress bars in the title.
6013 * @deprecated No longer supported starting in API 21.
6016 public final void setProgressBarIndeterminateVisibility(boolean visible) {
6017 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
6018 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
6022 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
6023 * is always indeterminate).
6025 * In order for the progress bar to be shown, the feature must be requested
6026 * via {@link #requestWindowFeature(int)}.
6028 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
6029 * @deprecated No longer supported starting in API 21.
6032 public final void setProgressBarIndeterminate(boolean indeterminate) {
6033 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6034 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
6035 : Window.PROGRESS_INDETERMINATE_OFF);
6039 * Sets the progress for the progress bars in the title.
6041 * In order for the progress bar to be shown, the feature must be requested
6042 * via {@link #requestWindowFeature(int)}.
6044 * @param progress The progress for the progress bar. Valid ranges are from
6045 * 0 to 10000 (both inclusive). If 10000 is given, the progress
6046 * bar will be completely filled and will fade out.
6047 * @deprecated No longer supported starting in API 21.
6050 public final void setProgress(int progress) {
6051 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
6055 * Sets the secondary progress for the progress bar in the title. This
6056 * progress is drawn between the primary progress (set via
6057 * {@link #setProgress(int)} and the background. It can be ideal for media
6058 * scenarios such as showing the buffering progress while the default
6059 * progress shows the play progress.
6061 * In order for the progress bar to be shown, the feature must be requested
6062 * via {@link #requestWindowFeature(int)}.
6064 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
6065 * 0 to 10000 (both inclusive).
6066 * @deprecated No longer supported starting in API 21.
6069 public final void setSecondaryProgress(int secondaryProgress) {
6070 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6071 secondaryProgress + Window.PROGRESS_SECONDARY_START);
6075 * Suggests an audio stream whose volume should be changed by the hardware
6078 * The suggested audio stream will be tied to the window of this Activity.
6079 * Volume requests which are received while the Activity is in the
6080 * foreground will affect this stream.
6082 * It is not guaranteed that the hardware volume controls will always change
6083 * this stream's volume (for example, if a call is in progress, its stream's
6084 * volume may be changed instead). To reset back to the default, use
6085 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
6087 * @param streamType The type of the audio stream whose volume should be
6088 * changed by the hardware volume controls.
6090 public final void setVolumeControlStream(int streamType) {
6091 getWindow().setVolumeControlStream(streamType);
6095 * Gets the suggested audio stream whose volume should be changed by the
6096 * hardware volume controls.
6098 * @return The suggested audio stream type whose volume should be changed by
6099 * the hardware volume controls.
6100 * @see #setVolumeControlStream(int)
6102 public final int getVolumeControlStream() {
6103 return getWindow().getVolumeControlStream();
6107 * Sets a {@link MediaController} to send media keys and volume changes to.
6109 * The controller will be tied to the window of this Activity. Media key and
6110 * volume events which are received while the Activity is in the foreground
6111 * will be forwarded to the controller and used to invoke transport controls
6112 * or adjust the volume. This may be used instead of or in addition to
6113 * {@link #setVolumeControlStream} to affect a specific session instead of a
6116 * It is not guaranteed that the hardware volume controls will always change
6117 * this session's volume (for example, if a call is in progress, its
6118 * stream's volume may be changed instead). To reset back to the default use
6119 * null as the controller.
6121 * @param controller The controller for the session which should receive
6122 * media keys and volume changes.
6124 public final void setMediaController(MediaController controller) {
6125 getWindow().setMediaController(controller);
6129 * Gets the controller which should be receiving media key and volume events
6130 * while this activity is in the foreground.
6132 * @return The controller which should receive events.
6133 * @see #setMediaController(android.media.session.MediaController)
6135 public final MediaController getMediaController() {
6136 return getWindow().getMediaController();
6140 * Runs the specified action on the UI thread. If the current thread is the UI
6141 * thread, then the action is executed immediately. If the current thread is
6142 * not the UI thread, the action is posted to the event queue of the UI thread.
6144 * @param action the action to run on the UI thread
6147 public final void runOnUiThread(Runnable action) {
6148 if (Thread.currentThread() != mUiThread) {
6149 mHandler.post(action);
6156 * Standard implementation of
6157 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
6158 * inflating with the LayoutInflater returned by {@link #getSystemService}.
6159 * This implementation does nothing and is for
6160 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
6161 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
6163 * @see android.view.LayoutInflater#createView
6164 * @see android.view.Window#getLayoutInflater
6167 public View onCreateView(String name, Context context, AttributeSet attrs) {
6172 * Standard implementation of
6173 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
6174 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
6175 * This implementation handles <fragment> tags to embed fragments inside
6178 * @see android.view.LayoutInflater#createView
6179 * @see android.view.Window#getLayoutInflater
6181 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
6182 if (!"fragment".equals(name)) {
6183 return onCreateView(name, context, attrs);
6186 return mFragments.onCreateView(parent, name, context, attrs);
6190 * Print the Activity's state into the given stream. This gets invoked if
6191 * you run "adb shell dumpsys activity <activity_component_name>".
6193 * @param prefix Desired prefix to prepend at each line of output.
6194 * @param fd The raw file descriptor that the dump is being sent to.
6195 * @param writer The PrintWriter to which you should dump your state. This will be
6196 * closed for you after you return.
6197 * @param args additional arguments to the dump request.
6199 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6200 dumpInner(prefix, fd, writer, args);
6203 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6204 writer.print(prefix); writer.print("Local Activity ");
6205 writer.print(Integer.toHexString(System.identityHashCode(this)));
6206 writer.println(" State:");
6207 String innerPrefix = prefix + " ";
6208 writer.print(innerPrefix); writer.print("mResumed=");
6209 writer.print(mResumed); writer.print(" mStopped=");
6210 writer.print(mStopped); writer.print(" mFinished=");
6211 writer.println(mFinished);
6212 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
6213 writer.println(mChangingConfigurations);
6214 writer.print(innerPrefix); writer.print("mCurrentConfig=");
6215 writer.println(mCurrentConfig);
6217 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
6218 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
6219 if (mVoiceInteractor != null) {
6220 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
6223 if (getWindow() != null &&
6224 getWindow().peekDecorView() != null &&
6225 getWindow().peekDecorView().getViewRootImpl() != null) {
6226 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
6229 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
6233 * Bit indicating that this activity is "immersive" and should not be
6234 * interrupted by notifications if possible.
6236 * This value is initially set by the manifest property
6237 * <code>android:immersive</code> but may be changed at runtime by
6238 * {@link #setImmersive}.
6240 * @see #setImmersive(boolean)
6241 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6243 public boolean isImmersive() {
6245 return ActivityManager.getService().isImmersive(mToken);
6246 } catch (RemoteException e) {
6252 * Indication of whether this is the highest level activity in this task. Can be used to
6253 * determine whether an activity launched by this activity was placed in the same task or
6256 * @return true if this is the topmost, non-finishing activity in its task.
6258 private boolean isTopOfTask() {
6259 if (mToken == null || mWindow == null) {
6263 return ActivityManager.getService().isTopOfTask(getActivityToken());
6264 } catch (RemoteException e) {
6270 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
6271 * fullscreen opaque Activity.
6273 * Call this whenever the background of a translucent Activity has changed to become opaque.
6274 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
6276 * This call has no effect on non-translucent activities or on activities with the
6277 * {@link android.R.attr#windowIsFloating} attribute.
6279 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6281 * @see TranslucentConversionListener
6286 public void convertFromTranslucent() {
6288 mTranslucentCallback = null;
6289 if (ActivityManager.getService().convertFromTranslucent(mToken)) {
6290 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
6292 } catch (RemoteException e) {
6298 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
6299 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
6301 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
6302 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
6303 * be called indicating that it is safe to make this activity translucent again. Until
6304 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
6305 * behind the frontmost Activity will be indeterminate.
6307 * This call has no effect on non-translucent activities or on activities with the
6308 * {@link android.R.attr#windowIsFloating} attribute.
6310 * @param callback the method to call when all visible Activities behind this one have been
6311 * drawn and it is safe to make this Activity translucent again.
6312 * @param options activity options delivered to the activity below this one. The options
6313 * are retrieved using {@link #getActivityOptions}.
6314 * @return <code>true</code> if Window was opaque and will become translucent or
6315 * <code>false</code> if window was translucent and no change needed to be made.
6317 * @see #convertFromTranslucent()
6318 * @see TranslucentConversionListener
6323 public boolean convertToTranslucent(TranslucentConversionListener callback,
6324 ActivityOptions options) {
6325 boolean drawComplete;
6327 mTranslucentCallback = callback;
6328 mChangeCanvasToTranslucent = ActivityManager.getService().convertToTranslucent(
6329 mToken, options == null ? null : options.toBundle());
6330 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6331 drawComplete = true;
6332 } catch (RemoteException e) {
6333 // Make callback return as though it timed out.
6334 mChangeCanvasToTranslucent = false;
6335 drawComplete = false;
6337 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
6338 // Window is already translucent.
6339 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6341 return mChangeCanvasToTranslucent;
6345 void onTranslucentConversionComplete(boolean drawComplete) {
6346 if (mTranslucentCallback != null) {
6347 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6348 mTranslucentCallback = null;
6350 if (mChangeCanvasToTranslucent) {
6351 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6356 public void onNewActivityOptions(ActivityOptions options) {
6357 mActivityTransitionState.setEnterActivityOptions(this, options);
6359 mActivityTransitionState.enterReady(this);
6364 * Retrieve the ActivityOptions passed in from the launching activity or passed back
6365 * from an activity launched by this activity in its call to {@link
6366 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
6368 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
6371 ActivityOptions getActivityOptions() {
6373 return ActivityOptions.fromBundle(
6374 ActivityManager.getService().getActivityOptions(mToken));
6375 } catch (RemoteException e) {
6381 * Activities that want to remain visible behind a translucent activity above them must call
6382 * this method anytime between the start of {@link #onResume()} and the return from
6383 * {@link #onPause()}. If this call is successful then the activity will remain visible after
6384 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
6386 * <p>The actions of this call are reset each time that this activity is brought to the
6387 * front. That is, every time {@link #onResume()} is called the activity will be assumed
6388 * to not have requested visible behind. Therefore, if you want this activity to continue to
6389 * be visible in the background you must call this method again.
6391 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
6392 * for dialog and translucent activities.
6394 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
6395 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
6397 * <p>False will be returned any time this method is called between the return of onPause and
6398 * the next call to onResume.
6400 * @deprecated This method's functionality is no longer supported as of
6401 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6403 * @param visible true to notify the system that the activity wishes to be visible behind other
6404 * translucent activities, false to indicate otherwise. Resources must be
6405 * released when passing false to this method.
6407 * @return the resulting visibiity state. If true the activity will remain visible beyond
6408 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
6409 * then the activity may not count on being visible behind other translucent activities,
6410 * and must stop any media playback and release resources.
6411 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
6412 * the return value must be checked.
6414 * @see #onVisibleBehindCanceled()
6417 public boolean requestVisibleBehind(boolean visible) {
6419 // Do not permit paused or stopped activities to do this.
6423 mVisibleBehind = ActivityManager.getService()
6424 .requestVisibleBehind(mToken, visible) && visible;
6425 } catch (RemoteException e) {
6426 mVisibleBehind = false;
6428 return mVisibleBehind;
6432 * Called when a translucent activity over this activity is becoming opaque or another
6433 * activity is being launched. Activities that override this method must call
6434 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
6436 * <p>When this method is called the activity has 500 msec to release any resources it may be
6437 * using while visible in the background.
6438 * If the activity has not returned from this method in 500 msec the system will destroy
6439 * the activity and kill the process in order to recover the resources for another
6440 * process. Otherwise {@link #onStop()} will be called following return.
6442 * @see #requestVisibleBehind(boolean)
6444 * @deprecated This method's functionality is no longer supported as of
6445 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6449 public void onVisibleBehindCanceled() {
6454 * Translucent activities may call this to determine if there is an activity below them that
6455 * is currently set to be visible in the background.
6457 * @deprecated This method's functionality is no longer supported as of
6458 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6460 * @return true if an activity below is set to visible according to the most recent call to
6461 * {@link #requestVisibleBehind(boolean)}, false otherwise.
6463 * @see #requestVisibleBehind(boolean)
6464 * @see #onVisibleBehindCanceled()
6465 * @see #onBackgroundVisibleBehindChanged(boolean)
6470 public boolean isBackgroundVisibleBehind() {
6472 return ActivityManager.getService().isBackgroundVisibleBehind(mToken);
6473 } catch (RemoteException e) {
6479 * The topmost foreground activity will receive this call when the background visibility state
6480 * of the activity below it changes.
6482 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
6483 * due to a background activity finishing itself.
6485 * @deprecated This method's functionality is no longer supported as of
6486 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6488 * @param visible true if a background activity is visible, false otherwise.
6490 * @see #requestVisibleBehind(boolean)
6491 * @see #onVisibleBehindCanceled()
6496 public void onBackgroundVisibleBehindChanged(boolean visible) {
6500 * Activities cannot draw during the period that their windows are animating in. In order
6501 * to know when it is safe to begin drawing they can override this method which will be
6502 * called when the entering animation has completed.
6504 public void onEnterAnimationComplete() {
6510 public void dispatchEnterAnimationComplete() {
6511 onEnterAnimationComplete();
6512 if (getWindow() != null && getWindow().getDecorView() != null) {
6513 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
6518 * Adjust the current immersive mode setting.
6520 * Note that changing this value will have no effect on the activity's
6521 * {@link android.content.pm.ActivityInfo} structure; that is, if
6522 * <code>android:immersive</code> is set to <code>true</code>
6523 * in the application's manifest entry for this activity, the {@link
6524 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
6525 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6526 * FLAG_IMMERSIVE} bit set.
6528 * @see #isImmersive()
6529 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6531 public void setImmersive(boolean i) {
6533 ActivityManager.getService().setImmersive(mToken, i);
6534 } catch (RemoteException e) {
6540 * Enable or disable virtual reality (VR) mode for this Activity.
6542 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
6543 * while this Activity has user focus.</p>
6545 * <p>It is recommended that applications additionally declare
6546 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
6547 * transitions when switching between VR activities.</p>
6549 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
6550 * VR mode will not be started. Developers can handle this case as follows:</p>
6553 * String servicePackage = "com.whatever.app";
6554 * String serviceClass = "com.whatever.app.MyVrListenerService";
6556 * // Name of the component of the VrListenerService to start.
6557 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
6560 * setVrModeEnabled(true, myComponentName);
6561 * } catch (PackageManager.NameNotFoundException e) {
6562 * List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
6563 * boolean isInstalled = false;
6564 * for (ApplicationInfo app : installed) {
6565 * if (app.packageName.equals(servicePackage)) {
6566 * isInstalled = true;
6570 * if (isInstalled) {
6571 * // Package is installed, but not enabled in Settings. Let user enable it.
6572 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
6574 * // Package is not installed. Send an intent to download this.
6575 * sentIntentToLaunchAppStore(servicePackage);
6580 * @param enabled {@code true} to enable this mode.
6581 * @param requestedComponent the name of the component to use as a
6582 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
6584 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
6585 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
6586 * not been enabled in user settings.
6588 * @see android.content.pm.PackageManager#FEATURE_VR_MODE
6589 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
6590 * @see android.service.vr.VrListenerService
6591 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
6592 * @see android.R.attr#enableVrMode
6594 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
6595 throws PackageManager.NameNotFoundException {
6597 if (ActivityManager.getService().setVrMode(mToken, enabled, requestedComponent)
6599 throw new PackageManager.NameNotFoundException(
6600 requestedComponent.flattenToString());
6602 } catch (RemoteException e) {
6608 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
6610 * @param callback Callback that will manage lifecycle events for this action mode
6611 * @return The ActionMode that was started, or null if it was canceled
6616 public ActionMode startActionMode(ActionMode.Callback callback) {
6617 return mWindow.getDecorView().startActionMode(callback);
6621 * Start an action mode of the given type.
6623 * @param callback Callback that will manage lifecycle events for this action mode
6624 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6625 * @return The ActionMode that was started, or null if it was canceled
6630 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6631 return mWindow.getDecorView().startActionMode(callback, type);
6635 * Give the Activity a chance to control the UI for an action mode requested
6638 * <p>Note: If you are looking for a notification callback that an action mode
6639 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
6641 * @param callback The callback that should control the new action mode
6642 * @return The new action mode, or <code>null</code> if the activity does not want to
6643 * provide special handling for this action mode. (It will be handled by the system.)
6647 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
6648 // Only Primary ActionModes are represented in the ActionBar.
6649 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
6650 initWindowDecorActionBar();
6651 if (mActionBar != null) {
6652 return mActionBar.startActionMode(callback);
6663 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
6665 mActionModeTypeStarting = type;
6666 return onWindowStartingActionMode(callback);
6668 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
6673 * Notifies the Activity that an action mode has been started.
6674 * Activity subclasses overriding this method should call the superclass implementation.
6676 * @param mode The new action mode.
6680 public void onActionModeStarted(ActionMode mode) {
6684 * Notifies the activity that an action mode has finished.
6685 * Activity subclasses overriding this method should call the superclass implementation.
6687 * @param mode The action mode that just finished.
6691 public void onActionModeFinished(ActionMode mode) {
6695 * Returns true if the app should recreate the task when navigating 'up' from this activity
6696 * by using targetIntent.
6698 * <p>If this method returns false the app can trivially call
6699 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
6700 * up navigation. If this method returns false, the app should synthesize a new task stack
6701 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6703 * @param targetIntent An intent representing the target destination for up navigation
6704 * @return true if navigating up should recreate a new task stack, false if the same task
6705 * should be used for the destination
6707 public boolean shouldUpRecreateTask(Intent targetIntent) {
6709 PackageManager pm = getPackageManager();
6710 ComponentName cn = targetIntent.getComponent();
6712 cn = targetIntent.resolveActivity(pm);
6714 ActivityInfo info = pm.getActivityInfo(cn, 0);
6715 if (info.taskAffinity == null) {
6718 return ActivityManager.getService()
6719 .shouldUpRecreateTask(mToken, info.taskAffinity);
6720 } catch (RemoteException e) {
6722 } catch (NameNotFoundException e) {
6728 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6729 * in the process. If the activity indicated by upIntent already exists in the task's history,
6730 * this activity and all others before the indicated activity in the history stack will be
6733 * <p>If the indicated activity does not appear in the history stack, this will finish
6734 * each activity in this task until the root activity of the task is reached, resulting in
6735 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6736 * when an activity may be reached by a path not passing through a canonical parent
6739 * <p>This method should be used when performing up navigation from within the same task
6740 * as the destination. If up navigation should cross tasks in some cases, see
6741 * {@link #shouldUpRecreateTask(Intent)}.</p>
6743 * @param upIntent An intent representing the target destination for up navigation
6745 * @return true if up navigation successfully reached the activity indicated by upIntent and
6746 * upIntent was delivered to it. false if an instance of the indicated activity could
6747 * not be found and this activity was simply finished normally.
6749 public boolean navigateUpTo(Intent upIntent) {
6750 if (mParent == null) {
6751 ComponentName destInfo = upIntent.getComponent();
6752 if (destInfo == null) {
6753 destInfo = upIntent.resolveActivity(getPackageManager());
6754 if (destInfo == null) {
6757 upIntent = new Intent(upIntent);
6758 upIntent.setComponent(destInfo);
6762 synchronized (this) {
6763 resultCode = mResultCode;
6764 resultData = mResultData;
6766 if (resultData != null) {
6767 resultData.prepareToLeaveProcess(this);
6770 upIntent.prepareToLeaveProcess(this);
6771 return ActivityManager.getService().navigateUpTo(mToken, upIntent,
6772 resultCode, resultData);
6773 } catch (RemoteException e) {
6777 return mParent.navigateUpToFromChild(this, upIntent);
6782 * This is called when a child activity of this one calls its
6783 * {@link #navigateUpTo} method. The default implementation simply calls
6784 * navigateUpTo(upIntent) on this activity (the parent).
6786 * @param child The activity making the call.
6787 * @param upIntent An intent representing the target destination for up navigation
6789 * @return true if up navigation successfully reached the activity indicated by upIntent and
6790 * upIntent was delivered to it. false if an instance of the indicated activity could
6791 * not be found and this activity was simply finished normally.
6793 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6794 return navigateUpTo(upIntent);
6798 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6799 * this activity's logical parent. The logical parent is named in the application's manifest
6800 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6801 * Activity subclasses may override this method to modify the Intent returned by
6802 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6803 * the parent intent entirely.
6805 * @return a new Intent targeting the defined parent of this activity or null if
6806 * there is no valid parent.
6809 public Intent getParentActivityIntent() {
6810 final String parentName = mActivityInfo.parentActivityName;
6811 if (TextUtils.isEmpty(parentName)) {
6815 // If the parent itself has no parent, generate a main activity intent.
6816 final ComponentName target = new ComponentName(this, parentName);
6818 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6819 final String parentActivity = parentInfo.parentActivityName;
6820 final Intent parentIntent = parentActivity == null
6821 ? Intent.makeMainActivity(target)
6822 : new Intent().setComponent(target);
6823 return parentIntent;
6824 } catch (NameNotFoundException e) {
6825 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6832 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6833 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6834 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6835 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6837 * @param callback Used to manipulate shared element transitions on the launched Activity.
6839 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6840 if (callback == null) {
6841 callback = SharedElementCallback.NULL_CALLBACK;
6843 mEnterTransitionListener = callback;
6847 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6848 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6849 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6850 * calls will only come when returning from the started Activity.
6851 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6853 * @param callback Used to manipulate shared element transitions on the launching Activity.
6855 public void setExitSharedElementCallback(SharedElementCallback callback) {
6856 if (callback == null) {
6857 callback = SharedElementCallback.NULL_CALLBACK;
6859 mExitTransitionListener = callback;
6863 * Postpone the entering activity transition when Activity was started with
6864 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6865 * android.util.Pair[])}.
6866 * <p>This method gives the Activity the ability to delay starting the entering and
6867 * shared element transitions until all data is loaded. Until then, the Activity won't
6868 * draw into its window, leaving the window transparent. This may also cause the
6869 * returning animation to be delayed until data is ready. This method should be
6870 * called in {@link #onCreate(android.os.Bundle)} or in
6871 * {@link #onActivityReenter(int, android.content.Intent)}.
6872 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6873 * start the transitions. If the Activity did not use
6874 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6875 * android.util.Pair[])}, then this method does nothing.</p>
6877 public void postponeEnterTransition() {
6878 mActivityTransitionState.postponeEnterTransition();
6882 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6883 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6884 * to have your Activity start drawing.
6886 public void startPostponedEnterTransition() {
6887 mActivityTransitionState.startPostponedEnterTransition();
6891 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
6892 * access permissions for content URIs associated with the {@link DragEvent}.
6893 * @param event Drag event
6894 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
6895 * Null if no content URIs are associated with the event or if permissions could not be granted.
6897 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
6898 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
6899 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
6900 return dragAndDropPermissions;
6905 // ------------------ Internal API ------------------
6907 final void setParent(Activity parent) {
6911 final void attach(Context context, ActivityThread aThread,
6912 Instrumentation instr, IBinder token, int ident,
6913 Application application, Intent intent, ActivityInfo info,
6914 CharSequence title, Activity parent, String id,
6915 NonConfigurationInstances lastNonConfigurationInstances,
6916 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6917 Window window, ActivityConfigCallback activityConfigCallback) {
6918 attachBaseContext(context);
6920 mFragments.attachHost(null /*parent*/);
6922 mWindow = new PhoneWindow(this, window, activityConfigCallback);
6923 mWindow.setWindowControllerCallback(this);
6924 mWindow.setCallback(this);
6925 mWindow.setOnWindowDismissedCallback(this);
6926 mWindow.getLayoutInflater().setPrivateFactory(this);
6927 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6928 mWindow.setSoftInputMode(info.softInputMode);
6930 if (info.uiOptions != 0) {
6931 mWindow.setUiOptions(info.uiOptions);
6933 mUiThread = Thread.currentThread();
6935 mMainThread = aThread;
6936 mInstrumentation = instr;
6939 mApplication = application;
6941 mReferrer = referrer;
6942 mComponent = intent.getComponent();
6943 mActivityInfo = info;
6947 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6948 if (voiceInteractor != null) {
6949 if (lastNonConfigurationInstances != null) {
6950 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6952 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6957 mWindow.setWindowManager(
6958 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6959 mToken, mComponent.flattenToString(),
6960 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6961 if (mParent != null) {
6962 mWindow.setContainer(mParent.getWindow());
6964 mWindowManager = mWindow.getWindowManager();
6965 mCurrentConfig = config;
6967 mWindow.setColorMode(info.colorMode);
6971 public final IBinder getActivityToken() {
6972 return mParent != null ? mParent.getActivityToken() : mToken;
6975 final void performCreateCommon() {
6976 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
6977 com.android.internal.R.styleable.Window_windowNoDisplay, false);
6978 mFragments.dispatchActivityCreated();
6979 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6982 final void performCreate(Bundle icicle) {
6983 restoreHasCurrentPermissionRequest(icicle);
6985 mActivityTransitionState.readState(icicle);
6986 performCreateCommon();
6989 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
6990 restoreHasCurrentPermissionRequest(icicle);
6991 onCreate(icicle, persistentState);
6992 mActivityTransitionState.readState(icicle);
6993 performCreateCommon();
6996 final void performStart() {
6997 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
6998 mFragments.noteStateNotSaved();
7000 mFragments.execPendingActions();
7001 mInstrumentation.callActivityOnStart(this);
7003 throw new SuperNotCalledException(
7004 "Activity " + mComponent.toShortString() +
7005 " did not call through to super.onStart()");
7007 mFragments.dispatchStart();
7008 mFragments.reportLoaderStart();
7010 // This property is set for all builds except final release
7011 boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
7012 boolean isAppDebuggable =
7013 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7015 if (isAppDebuggable || isDlwarningEnabled) {
7016 String dlwarning = getDlWarning();
7017 if (dlwarning != null) {
7018 String appName = getApplicationInfo().loadLabel(getPackageManager())
7020 String warning = "Detected problems with app native libraries\n" +
7021 "(please consult log for detail):\n" + dlwarning;
7022 if (isAppDebuggable) {
7023 new AlertDialog.Builder(this).
7025 setMessage(warning).
7026 setPositiveButton(android.R.string.ok, null).
7027 setCancelable(false).
7030 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
7035 mActivityTransitionState.enterReady(this);
7038 final void performRestart() {
7039 mFragments.noteStateNotSaved();
7041 if (mToken != null && mParent == null) {
7042 // No need to check mStopped, the roots will check if they were actually stopped.
7043 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
7049 synchronized (mManagedCursors) {
7050 final int N = mManagedCursors.size();
7051 for (int i=0; i<N; i++) {
7052 ManagedCursor mc = mManagedCursors.get(i);
7053 if (mc.mReleased || mc.mUpdated) {
7054 if (!mc.mCursor.requery()) {
7055 if (getApplicationInfo().targetSdkVersion
7056 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
7057 throw new IllegalStateException(
7058 "trying to requery an already closed cursor "
7062 mc.mReleased = false;
7063 mc.mUpdated = false;
7069 mInstrumentation.callActivityOnRestart(this);
7071 throw new SuperNotCalledException(
7072 "Activity " + mComponent.toShortString() +
7073 " did not call through to super.onRestart()");
7079 final void performResume() {
7082 mFragments.execPendingActions();
7084 mLastNonConfigurationInstances = null;
7087 // mResumed is set by the instrumentation
7088 mInstrumentation.callActivityOnResume(this);
7090 throw new SuperNotCalledException(
7091 "Activity " + mComponent.toShortString() +
7092 " did not call through to super.onResume()");
7095 // invisible activities must be finished before onResume() completes
7096 if (!mVisibleFromClient && !mFinished) {
7097 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
7098 if (getApplicationInfo().targetSdkVersion
7099 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
7100 throw new IllegalStateException(
7101 "Activity " + mComponent.toShortString() +
7102 " did not call finish() prior to onResume() completing");
7106 // Now really resume, and install the current status bar and menu.
7109 mFragments.dispatchResume();
7110 mFragments.execPendingActions();
7114 throw new SuperNotCalledException(
7115 "Activity " + mComponent.toShortString() +
7116 " did not call through to super.onPostResume()");
7120 final void performPause() {
7121 mDoReportFullyDrawn = false;
7122 mFragments.dispatchPause();
7126 if (!mCalled && getApplicationInfo().targetSdkVersion
7127 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
7128 throw new SuperNotCalledException(
7129 "Activity " + mComponent.toShortString() +
7130 " did not call through to super.onPause()");
7135 final void performUserLeaving() {
7136 onUserInteraction();
7140 final void performStop(boolean preserveWindow) {
7141 mDoReportFullyDrawn = false;
7142 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
7145 if (mWindow != null) {
7146 mWindow.closeAllPanels();
7149 // If we're preserving the window, don't setStoppedState to true, since we
7150 // need the window started immediately again. Stopping the window will
7151 // destroys hardware resources and causes flicker.
7152 if (!preserveWindow && mToken != null && mParent == null) {
7153 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
7156 mFragments.dispatchStop();
7159 mInstrumentation.callActivityOnStop(this);
7161 throw new SuperNotCalledException(
7162 "Activity " + mComponent.toShortString() +
7163 " did not call through to super.onStop()");
7166 synchronized (mManagedCursors) {
7167 final int N = mManagedCursors.size();
7168 for (int i=0; i<N; i++) {
7169 ManagedCursor mc = mManagedCursors.get(i);
7170 if (!mc.mReleased) {
7171 mc.mCursor.deactivate();
7172 mc.mReleased = true;
7182 final void performDestroy() {
7185 mFragments.dispatchDestroy();
7187 mFragments.doLoaderDestroy();
7188 if (mVoiceInteractor != null) {
7189 mVoiceInteractor.detachActivity();
7193 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
7194 Configuration newConfig) {
7195 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7196 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
7198 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7199 if (mWindow != null) {
7200 mWindow.onMultiWindowModeChanged();
7202 onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7205 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
7206 Configuration newConfig) {
7207 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7208 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
7210 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7211 if (mWindow != null) {
7212 mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
7214 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7220 public final boolean isResumed() {
7224 private void storeHasCurrentPermissionRequest(Bundle bundle) {
7225 if (bundle != null && mHasCurrentPermissionsRequest) {
7226 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
7230 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
7231 if (bundle != null) {
7232 mHasCurrentPermissionsRequest = bundle.getBoolean(
7233 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
7237 void dispatchActivityResult(String who, int requestCode,
7238 int resultCode, Intent data) {
7240 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
7241 + ", resCode=" + resultCode + ", data=" + data);
7242 mFragments.noteStateNotSaved();
7244 onActivityResult(requestCode, resultCode, data);
7245 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
7246 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
7247 if (TextUtils.isEmpty(who)) {
7248 dispatchRequestPermissionsResult(requestCode, data);
7250 Fragment frag = mFragments.findFragmentByWho(who);
7252 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
7255 } else if (who.startsWith("@android:view:")) {
7256 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
7257 getActivityToken());
7258 for (ViewRootImpl viewRoot : views) {
7259 if (viewRoot.getView() != null
7260 && viewRoot.getView().dispatchActivityResult(
7261 who, requestCode, resultCode, data)) {
7265 } else if (who.startsWith(AUTO_FILL_AUTH_WHO_PREFIX)) {
7266 Intent resultData = (resultCode == Activity.RESULT_OK) ? data : null;
7267 getAutofillManager().onAuthenticationResult(requestCode, resultData);
7269 Fragment frag = mFragments.findFragmentByWho(who);
7271 frag.onActivityResult(requestCode, resultCode, data);
7277 * Request to put this Activity in a mode where the user is locked to the
7280 * This will prevent the user from launching other apps, going to settings, or reaching the
7281 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
7282 * values permit launching while locked.
7284 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
7285 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
7286 * Lock Task mode. The user will not be able to exit this mode until
7287 * {@link Activity#stopLockTask()} is called.
7289 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
7290 * then the system will prompt the user with a dialog requesting permission to enter
7291 * this mode. When entered through this method the user can exit at any time through
7292 * an action described by the request dialog. Calling stopLockTask will also exit the
7295 * @see android.R.attr#lockTaskMode
7297 public void startLockTask() {
7299 ActivityManager.getService().startLockTaskModeByToken(mToken);
7300 } catch (RemoteException e) {
7305 * Allow the user to switch away from the current task.
7307 * Called to end the mode started by {@link Activity#startLockTask}. This
7308 * can only be called by activities that have successfully called
7309 * startLockTask previously.
7311 * This will allow the user to exit this app and move onto other activities.
7312 * <p>Note: This method should only be called when the activity is user-facing. That is,
7313 * between onResume() and onPause().
7314 * <p>Note: If there are other tasks below this one that are also locked then calling this
7315 * method will immediately finish this task and resume the previous locked one, remaining in
7318 * @see android.R.attr#lockTaskMode
7319 * @see ActivityManager#getLockTaskModeState()
7321 public void stopLockTask() {
7323 ActivityManager.getService().stopLockTaskMode();
7324 } catch (RemoteException e) {
7329 * Shows the user the system defined message for telling the user how to exit
7330 * lock task mode. The task containing this activity must be in lock task mode at the time
7331 * of this call for the message to be displayed.
7333 public void showLockTaskEscapeMessage() {
7335 ActivityManager.getService().showLockTaskEscapeMessage(mToken);
7336 } catch (RemoteException e) {
7341 * Check whether the caption on freeform windows is displayed directly on the content.
7343 * @return True if caption is displayed on content, false if it pushes the content down.
7345 * @see #setOverlayWithDecorCaptionEnabled(boolean)
7348 public boolean isOverlayWithDecorCaptionEnabled() {
7349 return mWindow.isOverlayWithDecorCaptionEnabled();
7353 * Set whether the caption should displayed directly on the content rather than push it down.
7355 * This affects only freeform windows since they display the caption and only the main
7356 * window of the activity. The caption is used to drag the window around and also shows
7357 * maximize and close action buttons.
7360 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
7361 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
7365 * Interface for informing a translucent {@link Activity} once all visible activities below it
7366 * have completed drawing. This is necessary only after an {@link Activity} has been made
7367 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
7368 * translucent again following a call to {@link
7369 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7375 public interface TranslucentConversionListener {
7377 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
7378 * below the top one have been redrawn. Following this callback it is safe to make the top
7379 * Activity translucent because the underlying Activity has been drawn.
7381 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
7382 * occurred waiting for the Activity to complete drawing.
7384 * @see Activity#convertFromTranslucent()
7385 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
7387 public void onTranslucentConversionComplete(boolean drawComplete);
7390 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
7391 mHasCurrentPermissionsRequest = false;
7392 // If the package installer crashed we may have not data - best effort.
7393 String[] permissions = (data != null) ? data.getStringArrayExtra(
7394 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7395 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7396 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7397 onRequestPermissionsResult(requestCode, permissions, grantResults);
7400 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
7401 Fragment fragment) {
7402 // If the package installer crashed we may have not data - best effort.
7403 String[] permissions = (data != null) ? data.getStringArrayExtra(
7404 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7405 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7406 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7407 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
7412 final public void autofillCallbackAuthenticate(int authenticationId, IntentSender intent,
7413 Intent fillInIntent) {
7415 startIntentSenderForResultInner(intent, AUTO_FILL_AUTH_WHO_PREFIX,
7416 authenticationId, fillInIntent, 0, 0, null);
7417 } catch (IntentSender.SendIntentException e) {
7418 Log.e(TAG, "authenticate() failed for intent:" + intent, e);
7424 final public void autofillCallbackResetableStateAvailable() {
7425 mAutoFillResetNeeded = true;
7430 final public boolean autofillCallbackRequestShowFillUi(@NonNull View anchor, int width,
7431 int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter) {
7432 final boolean wasShowing;
7434 if (mAutofillPopupWindow == null) {
7436 mAutofillPopupWindow = new AutofillPopupWindow(presenter);
7438 wasShowing = mAutofillPopupWindow.isShowing();
7440 mAutofillPopupWindow.update(anchor, 0, 0, width, height, anchorBounds);
7442 return !wasShowing && mAutofillPopupWindow.isShowing();
7447 final public boolean autofillCallbackRequestHideFillUi() {
7448 if (mAutofillPopupWindow == null) {
7451 mAutofillPopupWindow.dismiss();
7452 mAutofillPopupWindow = null;
7458 @NonNull public View[] findViewsByAccessibilityIdTraversal(@NonNull int[] viewIds) {
7459 final View[] views = new View[viewIds.length];
7460 final ArrayList<ViewRootImpl> roots =
7461 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7463 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7464 final View rootView = roots.get(rootNum).getView();
7466 if (rootView != null) {
7467 for (int viewNum = 0; viewNum < viewIds.length; viewNum++) {
7468 if (views[viewNum] == null) {
7469 views[viewNum] = rootView.findViewByAccessibilityIdTraversal(
7481 @Nullable public View findViewByAccessibilityIdTraversal(int viewId) {
7482 final ArrayList<ViewRootImpl> roots =
7483 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7484 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7485 final View rootView = roots.get(rootNum).getView();
7487 if (rootView != null) {
7488 final View view = rootView.findViewByAccessibilityIdTraversal(viewId);
7500 @NonNull public boolean[] getViewVisibility(@NonNull int[] viewIds) {
7501 final boolean[] isVisible = new boolean[viewIds.length];
7502 final View views[] = findViewsByAccessibilityIdTraversal(viewIds);
7504 for (int i = 0; i < viewIds.length; i++) {
7505 View view = views[i];
7507 isVisible[i] = false;
7511 isVisible[i] = true;
7513 // Check if the view is visible by checking all parents
7515 if (view instanceof DecorView && view.getViewRootImpl() == view.getParent()) {
7519 if (view.getVisibility() != View.VISIBLE) {
7520 isVisible[i] = false;
7524 if (view.getParent() instanceof View) {
7525 view = (View) view.getParent();
7537 public boolean isVisibleForAutofill() {
7542 * If set to true, this indicates to the system that it should never take a
7543 * screenshot of the activity to be used as a representation while it is not in a started state.
7545 * Note that the system may use the window background of the theme instead to represent
7546 * the window when it is not running.
7548 * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
7549 * this only affects the behavior when the activity's screenshot would be used as a
7550 * representation when the activity is not in a started state, i.e. in Overview. The system may
7551 * still take screenshots of the activity in other contexts; for example, when the user takes a
7552 * screenshot of the entire screen, or when the active
7553 * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
7554 * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
7556 * @param disable {@code true} to disable preview screenshots; {@code false} otherwise.
7560 public void setDisablePreviewScreenshots(boolean disable) {
7562 ActivityManager.getService().setDisablePreviewScreenshots(mToken, disable);
7563 } catch (RemoteException e) {
7564 Log.e(TAG, "Failed to call setDisablePreviewScreenshots", e);
7568 class HostCallbacks extends FragmentHostCallback<Activity> {
7569 public HostCallbacks() {
7570 super(Activity.this /*activity*/);
7574 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
7575 Activity.this.dump(prefix, fd, writer, args);
7579 public boolean onShouldSaveFragmentState(Fragment fragment) {
7580 return !isFinishing();
7584 public LayoutInflater onGetLayoutInflater() {
7585 final LayoutInflater result = Activity.this.getLayoutInflater();
7586 if (onUseFragmentManagerInflaterFactory()) {
7587 return result.cloneInContext(Activity.this);
7593 public boolean onUseFragmentManagerInflaterFactory() {
7594 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
7595 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
7599 public Activity onGetHost() {
7600 return Activity.this;
7604 public void onInvalidateOptionsMenu() {
7605 Activity.this.invalidateOptionsMenu();
7609 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
7611 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
7615 public void onStartActivityAsUserFromFragment(
7616 Fragment fragment, Intent intent, int requestCode, Bundle options,
7618 Activity.this.startActivityAsUserFromFragment(
7619 fragment, intent, requestCode, options, user);
7623 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
7624 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
7625 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
7626 if (mParent == null) {
7627 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
7628 flagsMask, flagsValues, options);
7629 } else if (options != null) {
7630 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode,
7631 fillInIntent, flagsMask, flagsValues, extraFlags, options);
7636 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
7638 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
7639 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
7640 startActivityForResult(who, intent, requestCode, null);
7644 public boolean onHasWindowAnimations() {
7645 return getWindow() != null;
7649 public int onGetWindowAnimations() {
7650 final Window w = getWindow();
7651 return (w == null) ? 0 : w.getAttributes().windowAnimations;
7655 public void onAttachFragment(Fragment fragment) {
7656 Activity.this.onAttachFragment(fragment);
7661 public <T extends View> T onFindViewById(int id) {
7662 return Activity.this.findViewById(id);
7666 public boolean onHasView() {
7667 final Window w = getWindow();
7668 return (w != null && w.peekDecorView() != null);