2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 import static java.lang.Character.MIN_VALUE;
21 import android.annotation.CallSuper;
22 import android.annotation.DrawableRes;
23 import android.annotation.IdRes;
24 import android.annotation.IntDef;
25 import android.annotation.LayoutRes;
26 import android.annotation.MainThread;
27 import android.annotation.NonNull;
28 import android.annotation.Nullable;
29 import android.annotation.RequiresPermission;
30 import android.annotation.StyleRes;
31 import android.annotation.SystemApi;
32 import android.app.VoiceInteractor.Request;
33 import android.app.admin.DevicePolicyManager;
34 import android.app.assist.AssistContent;
35 import android.content.ComponentCallbacks2;
36 import android.content.ComponentName;
37 import android.content.ContentResolver;
38 import android.content.Context;
39 import android.content.CursorLoader;
40 import android.content.IIntentSender;
41 import android.content.Intent;
42 import android.content.IntentSender;
43 import android.content.SharedPreferences;
44 import android.content.pm.ActivityInfo;
45 import android.content.pm.ApplicationInfo;
46 import android.content.pm.PackageManager;
47 import android.content.pm.PackageManager.NameNotFoundException;
48 import android.content.res.Configuration;
49 import android.content.res.Resources;
50 import android.content.res.TypedArray;
51 import android.database.Cursor;
52 import android.graphics.Bitmap;
53 import android.graphics.Canvas;
54 import android.graphics.Color;
55 import android.graphics.Rect;
56 import android.graphics.drawable.Drawable;
57 import android.media.AudioManager;
58 import android.media.session.MediaController;
59 import android.net.Uri;
60 import android.os.BadParcelableException;
61 import android.os.Build;
62 import android.os.Bundle;
63 import android.os.Handler;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.Parcelable;
67 import android.os.PersistableBundle;
68 import android.os.RemoteException;
69 import android.os.ServiceManager.ServiceNotFoundException;
70 import android.os.StrictMode;
71 import android.os.SystemProperties;
72 import android.os.UserHandle;
73 import android.text.Selection;
74 import android.text.SpannableStringBuilder;
75 import android.text.TextUtils;
76 import android.text.method.TextKeyListener;
77 import android.transition.Scene;
78 import android.transition.TransitionManager;
79 import android.util.ArrayMap;
80 import android.util.AttributeSet;
81 import android.util.EventLog;
82 import android.util.Log;
83 import android.util.PrintWriterPrinter;
84 import android.util.Slog;
85 import android.util.SparseArray;
86 import android.util.SuperNotCalledException;
87 import android.view.ActionMode;
88 import android.view.ContextMenu;
89 import android.view.ContextMenu.ContextMenuInfo;
90 import android.view.ContextThemeWrapper;
91 import android.view.DragAndDropPermissions;
92 import android.view.DragEvent;
93 import android.view.KeyEvent;
94 import android.view.KeyboardShortcutGroup;
95 import android.view.KeyboardShortcutInfo;
96 import android.view.LayoutInflater;
97 import android.view.Menu;
98 import android.view.MenuInflater;
99 import android.view.MenuItem;
100 import android.view.MotionEvent;
101 import android.view.SearchEvent;
102 import android.view.View;
103 import android.view.View.OnCreateContextMenuListener;
104 import android.view.ViewGroup;
105 import android.view.ViewGroup.LayoutParams;
106 import android.view.ViewManager;
107 import android.view.ViewRootImpl;
108 import android.view.ViewRootImpl.ActivityConfigCallback;
109 import android.view.Window;
110 import android.view.Window.WindowControllerCallback;
111 import android.view.WindowManager;
112 import android.view.WindowManagerGlobal;
113 import android.view.accessibility.AccessibilityEvent;
114 import android.view.autofill.AutofillManager;
115 import android.view.autofill.AutofillManager.AutofillClient;
116 import android.view.autofill.AutofillPopupWindow;
117 import android.view.autofill.IAutofillWindowPresenter;
118 import android.widget.AdapterView;
119 import android.widget.Toast;
120 import android.widget.Toolbar;
122 import com.android.internal.annotations.GuardedBy;
123 import com.android.internal.app.IVoiceInteractor;
124 import com.android.internal.app.ToolbarActionBar;
125 import com.android.internal.app.WindowDecorActionBar;
126 import com.android.internal.policy.DecorView;
127 import com.android.internal.policy.PhoneWindow;
129 import org.android_x86.analytics.AnalyticsHelper;
131 import java.io.FileDescriptor;
132 import java.io.PrintWriter;
133 import java.lang.annotation.Retention;
134 import java.lang.annotation.RetentionPolicy;
135 import java.util.ArrayList;
136 import java.util.HashMap;
137 import java.util.List;
140 * An activity is a single, focused thing that the user can do. Almost all
141 * activities interact with the user, so the Activity class takes care of
142 * creating a window for you in which you can place your UI with
143 * {@link #setContentView}. While activities are often presented to the user
144 * as full-screen windows, they can also be used in other ways: as floating
145 * windows (via a theme with {@link android.R.attr#windowIsFloating} set)
146 * or embedded inside of another activity (using {@link ActivityGroup}).
148 * There are two methods almost all subclasses of Activity will implement:
151 * <li> {@link #onCreate} is where you initialize your activity. Most
152 * importantly, here you will usually call {@link #setContentView(int)}
153 * with a layout resource defining your UI, and using {@link #findViewById}
154 * to retrieve the widgets in that UI that you need to interact with
157 * <li> {@link #onPause} is where you deal with the user leaving your
158 * activity. Most importantly, any changes made by the user should at this
159 * point be committed (usually to the
160 * {@link android.content.ContentProvider} holding the data).
163 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
164 * activity classes must have a corresponding
165 * {@link android.R.styleable#AndroidManifestActivity <activity>}
166 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
168 * <p>Topics covered here:
170 * <li><a href="#Fragments">Fragments</a>
171 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
172 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
173 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
174 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
175 * <li><a href="#Permissions">Permissions</a>
176 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
179 * <div class="special reference">
180 * <h3>Developer Guides</h3>
181 * <p>The Activity class is an important part of an application's overall lifecycle,
182 * and the way activities are launched and put together is a fundamental
183 * part of the platform's application model. For a detailed perspective on the structure of an
184 * Android application and how activities behave, please read the
185 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
186 * <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
187 * developer guides.</p>
189 * <p>You can also find a detailed discussion about how to create activities in the
190 * <a href="{@docRoot}guide/components/activities.html">Activities</a>
191 * developer guide.</p>
194 * <a name="Fragments"></a>
197 * <p>Starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}, Activity
198 * implementations can make use of the {@link Fragment} class to better
199 * modularize their code, build more sophisticated user interfaces for larger
200 * screens, and help scale their application between small and large screens.
202 * <a name="ActivityLifecycle"></a>
203 * <h3>Activity Lifecycle</h3>
205 * <p>Activities in the system are managed as an <em>activity stack</em>.
206 * When a new activity is started, it is placed on the top of the stack
207 * and becomes the running activity -- the previous activity always remains
208 * below it in the stack, and will not come to the foreground again until
209 * the new activity exits.</p>
211 * <p>An activity has essentially four states:</p>
213 * <li> If an activity is in the foreground of the screen (at the top of
215 * it is <em>active</em> or <em>running</em>. </li>
216 * <li>If an activity has lost focus but is still visible (that is, a new non-full-sized
217 * or transparent activity has focus on top of your activity), it
218 * is <em>paused</em>. A paused activity is completely alive (it
219 * maintains all state and member information and remains attached to
220 * the window manager), but can be killed by the system in extreme
221 * low memory situations.
222 * <li>If an activity is completely obscured by another activity,
223 * it is <em>stopped</em>. It still retains all state and member information,
224 * however, it is no longer visible to the user so its window is hidden
225 * and it will often be killed by the system when memory is needed
227 * <li>If an activity is paused or stopped, the system can drop the activity
228 * from memory by either asking it to finish, or simply killing its
229 * process. When it is displayed again to the user, it must be
230 * completely restarted and restored to its previous state.</li>
233 * <p>The following diagram shows the important state paths of an Activity.
234 * The square rectangles represent callback methods you can implement to
235 * perform operations when the Activity moves between states. The colored
236 * ovals are major states the Activity can be in.</p>
238 * <p><img src="../../../images/activity_lifecycle.png"
239 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
241 * <p>There are three key loops you may be interested in monitoring within your
245 * <li>The <b>entire lifetime</b> of an activity happens between the first call
246 * to {@link android.app.Activity#onCreate} through to a single final call
247 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
248 * of "global" state in onCreate(), and release all remaining resources in
249 * onDestroy(). For example, if it has a thread running in the background
250 * to download data from the network, it may create that thread in onCreate()
251 * and then stop the thread in onDestroy().
253 * <li>The <b>visible lifetime</b> of an activity happens between a call to
254 * {@link android.app.Activity#onStart} until a corresponding call to
255 * {@link android.app.Activity#onStop}. During this time the user can see the
256 * activity on-screen, though it may not be in the foreground and interacting
257 * with the user. Between these two methods you can maintain resources that
258 * are needed to show the activity to the user. For example, you can register
259 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
260 * that impact your UI, and unregister it in onStop() when the user no
261 * longer sees what you are displaying. The onStart() and onStop() methods
262 * can be called multiple times, as the activity becomes visible and hidden
265 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
266 * {@link android.app.Activity#onResume} until a corresponding call to
267 * {@link android.app.Activity#onPause}. During this time the activity is
268 * in front of all other activities and interacting with the user. An activity
269 * can frequently go between the resumed and paused states -- for example when
270 * the device goes to sleep, when an activity result is delivered, when a new
271 * intent is delivered -- so the code in these methods should be fairly
275 * <p>The entire lifecycle of an activity is defined by the following
276 * Activity methods. All of these are hooks that you can override
277 * to do appropriate work when the activity changes state. All
278 * activities will implement {@link android.app.Activity#onCreate}
279 * to do their initial setup; many will also implement
280 * {@link android.app.Activity#onPause} to commit changes to data and
281 * otherwise prepare to stop interacting with the user. You should always
282 * call up to your superclass when implementing these methods.</p>
285 * <pre class="prettyprint">
286 * public class Activity extends ApplicationContext {
287 * protected void onCreate(Bundle savedInstanceState);
289 * protected void onStart();
291 * protected void onRestart();
293 * protected void onResume();
295 * protected void onPause();
297 * protected void onStop();
299 * protected void onDestroy();
303 * <p>In general the movement through an activity's lifecycle looks like
306 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
307 * <colgroup align="left" span="3" />
308 * <colgroup align="left" />
309 * <colgroup align="center" />
310 * <colgroup align="center" />
313 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
317 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</td>
318 * <td>Called when the activity is first created.
319 * This is where you should do all of your normal static set up:
320 * create views, bind data to lists, etc. This method also
321 * provides you with a Bundle containing the activity's previously
322 * frozen state, if there was one.
323 * <p>Always followed by <code>onStart()</code>.</td>
324 * <td align="center">No</td>
325 * <td align="center"><code>onStart()</code></td>
328 * <tr><td rowspan="5" style="border-left: none; border-right: none;"> </td>
329 * <td colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</td>
330 * <td>Called after your activity has been stopped, prior to it being
332 * <p>Always followed by <code>onStart()</code></td>
333 * <td align="center">No</td>
334 * <td align="center"><code>onStart()</code></td>
337 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</td>
338 * <td>Called when the activity is becoming visible to the user.
339 * <p>Followed by <code>onResume()</code> if the activity comes
340 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
341 * <td align="center">No</td>
342 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
345 * <tr><td rowspan="2" style="border-left: none;"> </td>
346 * <td align="left" border="0">{@link android.app.Activity#onResume onResume()}</td>
347 * <td>Called when the activity will start
348 * interacting with the user. At this point your activity is at
349 * the top of the activity stack, with user input going to it.
350 * <p>Always followed by <code>onPause()</code>.</td>
351 * <td align="center">No</td>
352 * <td align="center"><code>onPause()</code></td>
355 * <tr><td align="left" border="0">{@link android.app.Activity#onPause onPause()}</td>
356 * <td>Called when the system is about to start resuming a previous
357 * activity. This is typically used to commit unsaved changes to
358 * persistent data, stop animations and other things that may be consuming
359 * CPU, etc. Implementations of this method must be very quick because
360 * the next activity will not be resumed until this method returns.
361 * <p>Followed by either <code>onResume()</code> if the activity
362 * returns back to the front, or <code>onStop()</code> if it becomes
363 * invisible to the user.</td>
364 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
365 * <td align="center"><code>onResume()</code> or<br>
366 * <code>onStop()</code></td>
369 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</td>
370 * <td>Called when the activity is no longer visible to the user, because
371 * another activity has been resumed and is covering this one. This
372 * may happen either because a new activity is being started, an existing
373 * one is being brought in front of this one, or this one is being
375 * <p>Followed by either <code>onRestart()</code> if
376 * this activity is coming back to interact with the user, or
377 * <code>onDestroy()</code> if this activity is going away.</td>
378 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
379 * <td align="center"><code>onRestart()</code> or<br>
380 * <code>onDestroy()</code></td>
383 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</td>
384 * <td>The final call you receive before your
385 * activity is destroyed. This can happen either because the
386 * activity is finishing (someone called {@link Activity#finish} on
387 * it, or because the system is temporarily destroying this
388 * instance of the activity to save space. You can distinguish
389 * between these two scenarios with the {@link
390 * Activity#isFinishing} method.</td>
391 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
392 * <td align="center"><em>nothing</em></td>
397 * <p>Note the "Killable" column in the above table -- for those methods that
398 * are marked as being killable, after that method returns the process hosting the
399 * activity may be killed by the system <em>at any time</em> without another line
400 * of its code being executed. Because of this, you should use the
401 * {@link #onPause} method to write any persistent data (such as user edits)
402 * to storage. In addition, the method
403 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
404 * in such a background state, allowing you to save away any dynamic instance
405 * state in your activity into the given Bundle, to be later received in
406 * {@link #onCreate} if the activity needs to be re-created.
407 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
408 * section for more information on how the lifecycle of a process is tied
409 * to the activities it is hosting. Note that it is important to save
410 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
411 * because the latter is not part of the lifecycle callbacks, so will not
412 * be called in every situation as described in its documentation.</p>
414 * <p class="note">Be aware that these semantics will change slightly between
415 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
416 * vs. those targeting prior platforms. Starting with Honeycomb, an application
417 * is not in the killable state until its {@link #onStop} has returned. This
418 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
419 * safely called after {@link #onPause()} and allows and application to safely
420 * wait until {@link #onStop()} to save persistent state.</p>
422 * <p>For those methods that are not marked as being killable, the activity's
423 * process will not be killed by the system starting from the time the method
424 * is called and continuing after it returns. Thus an activity is in the killable
425 * state, for example, between after <code>onPause()</code> to the start of
426 * <code>onResume()</code>.</p>
428 * <a name="ConfigurationChanges"></a>
429 * <h3>Configuration Changes</h3>
431 * <p>If the configuration of the device (as defined by the
432 * {@link Configuration Resources.Configuration} class) changes,
433 * then anything displaying a user interface will need to update to match that
434 * configuration. Because Activity is the primary mechanism for interacting
435 * with the user, it includes special support for handling configuration
438 * <p>Unless you specify otherwise, a configuration change (such as a change
439 * in screen orientation, language, input devices, etc) will cause your
440 * current activity to be <em>destroyed</em>, going through the normal activity
441 * lifecycle process of {@link #onPause},
442 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
443 * had been in the foreground or visible to the user, once {@link #onDestroy} is
444 * called in that instance then a new instance of the activity will be
445 * created, with whatever savedInstanceState the previous instance had generated
446 * from {@link #onSaveInstanceState}.</p>
448 * <p>This is done because any application resource,
449 * including layout files, can change based on any configuration value. Thus
450 * the only safe way to handle a configuration change is to re-retrieve all
451 * resources, including layouts, drawables, and strings. Because activities
452 * must already know how to save their state and re-create themselves from
453 * that state, this is a convenient way to have an activity restart itself
454 * with a new configuration.</p>
456 * <p>In some special cases, you may want to bypass restarting of your
457 * activity based on one or more types of configuration changes. This is
458 * done with the {@link android.R.attr#configChanges android:configChanges}
459 * attribute in its manifest. For any types of configuration changes you say
460 * that you handle there, you will receive a call to your current activity's
461 * {@link #onConfigurationChanged} method instead of being restarted. If
462 * a configuration change involves any that you do not handle, however, the
463 * activity will still be restarted and {@link #onConfigurationChanged}
464 * will not be called.</p>
466 * <a name="StartingActivities"></a>
467 * <h3>Starting Activities and Getting Results</h3>
469 * <p>The {@link android.app.Activity#startActivity}
470 * method is used to start a
471 * new activity, which will be placed at the top of the activity stack. It
472 * takes a single argument, an {@link android.content.Intent Intent},
473 * which describes the activity
474 * to be executed.</p>
476 * <p>Sometimes you want to get a result back from an activity when it
477 * ends. For example, you may start an activity that lets the user pick
478 * a person in a list of contacts; when it ends, it returns the person
479 * that was selected. To do this, you call the
480 * {@link android.app.Activity#startActivityForResult(Intent, int)}
481 * version with a second integer parameter identifying the call. The result
482 * will come back through your {@link android.app.Activity#onActivityResult}
485 * <p>When an activity exits, it can call
486 * {@link android.app.Activity#setResult(int)}
487 * to return data back to its parent. It must always supply a result code,
488 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
489 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
490 * return back an Intent containing any additional data it wants. All of this
491 * information appears back on the
492 * parent's <code>Activity.onActivityResult()</code>, along with the integer
493 * identifier it originally supplied.</p>
495 * <p>If a child activity fails for any reason (such as crashing), the parent
496 * activity will receive a result with the code RESULT_CANCELED.</p>
498 * <pre class="prettyprint">
499 * public class MyActivity extends Activity {
502 * static final int PICK_CONTACT_REQUEST = 0;
504 * public boolean onKeyDown(int keyCode, KeyEvent event) {
505 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
506 * // When the user center presses, let them pick a contact.
507 * startActivityForResult(
508 * new Intent(Intent.ACTION_PICK,
509 * new Uri("content://contacts")),
510 * PICK_CONTACT_REQUEST);
516 * protected void onActivityResult(int requestCode, int resultCode,
518 * if (requestCode == PICK_CONTACT_REQUEST) {
519 * if (resultCode == RESULT_OK) {
520 * // A contact was picked. Here we will just display it
522 * startActivity(new Intent(Intent.ACTION_VIEW, data));
529 * <a name="SavingPersistentState"></a>
530 * <h3>Saving Persistent State</h3>
532 * <p>There are generally two kinds of persistent state than an activity
533 * will deal with: shared document-like data (typically stored in a SQLite
534 * database using a {@linkplain android.content.ContentProvider content provider})
535 * and internal state such as user preferences.</p>
537 * <p>For content provider data, we suggest that activities use a
538 * "edit in place" user model. That is, any edits a user makes are effectively
539 * made immediately without requiring an additional confirmation step.
540 * Supporting this model is generally a simple matter of following two rules:</p>
543 * <li> <p>When creating a new document, the backing database entry or file for
544 * it is created immediately. For example, if the user chooses to write
545 * a new email, a new entry for that email is created as soon as they
546 * start entering data, so that if they go to any other activity after
547 * that point this email will now appear in the list of drafts.</p>
548 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
549 * commit to the backing content provider or file any changes the user
550 * has made. This ensures that those changes will be seen by any other
551 * activity that is about to run. You will probably want to commit
552 * your data even more aggressively at key times during your
553 * activity's lifecycle: for example before starting a new
554 * activity, before finishing your own activity, when the user
555 * switches between input fields, etc.</p>
558 * <p>This model is designed to prevent data loss when a user is navigating
559 * between activities, and allows the system to safely kill an activity (because
560 * system resources are needed somewhere else) at any time after it has been
561 * paused. Note this implies
562 * that the user pressing BACK from your activity does <em>not</em>
563 * mean "cancel" -- it means to leave the activity with its current contents
564 * saved away. Canceling edits in an activity must be provided through
565 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
567 * <p>See the {@linkplain android.content.ContentProvider content package} for
568 * more information about content providers. These are a key aspect of how
569 * different activities invoke and propagate data between themselves.</p>
571 * <p>The Activity class also provides an API for managing internal persistent state
572 * associated with an activity. This can be used, for example, to remember
573 * the user's preferred initial display in a calendar (day view or week view)
574 * or the user's default home page in a web browser.</p>
576 * <p>Activity persistent state is managed
577 * with the method {@link #getPreferences},
578 * allowing you to retrieve and
579 * modify a set of name/value pairs associated with the activity. To use
580 * preferences that are shared across multiple application components
581 * (activities, receivers, services, providers), you can use the underlying
582 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
583 * to retrieve a preferences
584 * object stored under a specific name.
585 * (Note that it is not possible to share settings data across application
586 * packages -- for that you will need a content provider.)</p>
588 * <p>Here is an excerpt from a calendar activity that stores the user's
589 * preferred view mode in its persistent settings:</p>
591 * <pre class="prettyprint">
592 * public class CalendarActivity extends Activity {
595 * static final int DAY_VIEW_MODE = 0;
596 * static final int WEEK_VIEW_MODE = 1;
598 * private SharedPreferences mPrefs;
599 * private int mCurViewMode;
601 * protected void onCreate(Bundle savedInstanceState) {
602 * super.onCreate(savedInstanceState);
604 * SharedPreferences mPrefs = getSharedPreferences();
605 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
608 * protected void onPause() {
611 * SharedPreferences.Editor ed = mPrefs.edit();
612 * ed.putInt("view_mode", mCurViewMode);
618 * <a name="Permissions"></a>
619 * <h3>Permissions</h3>
621 * <p>The ability to start a particular Activity can be enforced when it is
623 * manifest's {@link android.R.styleable#AndroidManifestActivity <activity>}
624 * tag. By doing so, other applications will need to declare a corresponding
625 * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>}
626 * element in their own manifest to be able to start that activity.
628 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
629 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
630 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
631 * Activity access to the specific URIs in the Intent. Access will remain
632 * until the Activity has finished (it will remain across the hosting
633 * process being killed and other temporary destruction). As of
634 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
635 * was already created and a new Intent is being delivered to
636 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
637 * to the existing ones it holds.
639 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
640 * document for more information on permissions and security in general.
642 * <a name="ProcessLifecycle"></a>
643 * <h3>Process Lifecycle</h3>
645 * <p>The Android system attempts to keep application process around for as
646 * long as possible, but eventually will need to remove old processes when
647 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
648 * Lifecycle</a>, the decision about which process to remove is intimately
649 * tied to the state of the user's interaction with it. In general, there
650 * are four states a process can be in based on the activities running in it,
651 * listed here in order of importance. The system will kill less important
652 * processes (the last ones) before it resorts to killing more important
653 * processes (the first ones).
656 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
657 * that the user is currently interacting with) is considered the most important.
658 * Its process will only be killed as a last resort, if it uses more memory
659 * than is available on the device. Generally at this point the device has
660 * reached a memory paging state, so this is required in order to keep the user
661 * interface responsive.
662 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
663 * but not in the foreground, such as one sitting behind a foreground dialog)
664 * is considered extremely important and will not be killed unless that is
665 * required to keep the foreground activity running.
666 * <li> <p>A <b>background activity</b> (an activity that is not visible to
667 * the user and has been paused) is no longer critical, so the system may
668 * safely kill its process to reclaim memory for other foreground or
669 * visible processes. If its process needs to be killed, when the user navigates
670 * back to the activity (making it visible on the screen again), its
671 * {@link #onCreate} method will be called with the savedInstanceState it had previously
672 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
673 * state as the user last left it.
674 * <li> <p>An <b>empty process</b> is one hosting no activities or other
675 * application components (such as {@link Service} or
676 * {@link android.content.BroadcastReceiver} classes). These are killed very
677 * quickly by the system as memory becomes low. For this reason, any
678 * background operation you do outside of an activity must be executed in the
679 * context of an activity BroadcastReceiver or Service to ensure that the system
680 * knows it needs to keep your process around.
683 * <p>Sometimes an Activity may need to do a long-running operation that exists
684 * independently of the activity lifecycle itself. An example may be a camera
685 * application that allows you to upload a picture to a web site. The upload
686 * may take a long time, and the application should allow the user to leave
687 * the application while it is executing. To accomplish this, your Activity
688 * should start a {@link Service} in which the upload takes place. This allows
689 * the system to properly prioritize your process (considering it to be more
690 * important than other non-visible applications) for the duration of the
691 * upload, independent of whether the original activity is paused, stopped,
694 public class Activity extends ContextThemeWrapper
695 implements LayoutInflater.Factory2,
696 Window.Callback, KeyEvent.Callback,
697 OnCreateContextMenuListener, ComponentCallbacks2,
698 Window.OnWindowDismissedCallback, WindowControllerCallback,
699 AutofillManager.AutofillClient {
700 private static final String TAG = "Activity";
701 private static final boolean DEBUG_LIFECYCLE = false;
703 /** Standard activity result: operation canceled. */
704 public static final int RESULT_CANCELED = 0;
705 /** Standard activity result: operation succeeded. */
706 public static final int RESULT_OK = -1;
707 /** Start of user-defined activity results. */
708 public static final int RESULT_FIRST_USER = 1;
710 /** @hide Task isn't finished when activity is finished */
711 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0;
713 * @hide Task is finished if the finishing activity is the root of the task. To preserve the
714 * past behavior the task is also removed from recents.
716 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1;
718 * @hide Task is finished along with the finishing activity, but it is not removed from
721 public static final int FINISH_TASK_WITH_ACTIVITY = 2;
723 static final String FRAGMENTS_TAG = "android:fragments";
724 private static final String LAST_AUTOFILL_ID = "android:lastAutofillId";
726 private static final String AUTOFILL_RESET_NEEDED = "@android:autofillResetNeeded";
727 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
728 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
729 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
730 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
731 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
732 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
733 "android:hasCurrentPermissionsRequest";
735 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
736 private static final String AUTO_FILL_AUTH_WHO_PREFIX = "@android:autoFillAuth:";
738 private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
740 private static class ManagedDialog {
744 private SparseArray<ManagedDialog> mManagedDialogs;
746 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
747 private Instrumentation mInstrumentation;
748 private IBinder mToken;
750 /*package*/ String mEmbeddedID;
751 private Application mApplication;
752 /*package*/ Intent mIntent;
753 /*package*/ String mReferrer;
754 private ComponentName mComponent;
755 /*package*/ ActivityInfo mActivityInfo;
756 /*package*/ ActivityThread mMainThread;
759 /*package*/ boolean mResumed;
760 /*package*/ boolean mStopped;
762 boolean mStartedActivity;
763 private boolean mDestroyed;
764 private boolean mAppsStatistics;
765 private boolean mDoReportFullyDrawn = true;
766 private boolean mRestoredFromBundle;
768 /** {@code true} if the activity lifecycle is in a state which supports picture-in-picture.
769 * This only affects the client-side exception, the actual state check still happens in AMS. */
770 private boolean mCanEnterPictureInPicture = false;
771 /** true if the activity is going through a transient pause */
772 /*package*/ boolean mTemporaryPause = false;
773 /** true if the activity is being destroyed in order to recreate it with a new configuration */
774 /*package*/ boolean mChangingConfigurations = false;
775 /*package*/ int mConfigChangeFlags;
776 /*package*/ Configuration mCurrentConfig;
777 private SearchManager mSearchManager;
778 private MenuInflater mMenuInflater;
780 /** The autofill manager. Always access via {@link #getAutofillManager()}. */
781 @Nullable private AutofillManager mAutofillManager;
783 static final class NonConfigurationInstances {
785 HashMap<String, Object> children;
786 FragmentManagerNonConfig fragments;
787 ArrayMap<String, LoaderManager> loaders;
788 VoiceInteractor voiceInteractor;
790 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
792 private Window mWindow;
794 private WindowManager mWindowManager;
795 /*package*/ View mDecor = null;
796 /*package*/ boolean mWindowAdded = false;
797 /*package*/ boolean mVisibleFromServer = false;
798 /*package*/ boolean mVisibleFromClient = true;
799 /*package*/ ActionBar mActionBar = null;
800 private boolean mEnableDefaultActionBarUp;
802 private VoiceInteractor mVoiceInteractor;
804 private CharSequence mTitle;
805 private int mTitleColor = 0;
807 // we must have a handler before the FragmentController is constructed
808 final Handler mHandler = new Handler();
809 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
811 private static final class ManagedCursor {
812 ManagedCursor(Cursor cursor) {
818 private final Cursor mCursor;
819 private boolean mReleased;
820 private boolean mUpdated;
823 @GuardedBy("mManagedCursors")
824 private final ArrayList<ManagedCursor> mManagedCursors = new ArrayList<>();
827 int mResultCode = RESULT_CANCELED;
829 Intent mResultData = null;
831 private TranslucentConversionListener mTranslucentCallback;
832 private boolean mChangeCanvasToTranslucent;
834 private SearchEvent mSearchEvent;
836 private boolean mTitleReady = false;
837 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
839 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
840 private SpannableStringBuilder mDefaultKeySsb = null;
842 private ActivityManager.TaskDescription mTaskDescription =
843 new ActivityManager.TaskDescription();
845 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
847 @SuppressWarnings("unused")
848 private final Object mInstanceTracker = StrictMode.trackActivity(this);
850 private Thread mUiThread;
852 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
853 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
854 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
856 private boolean mHasCurrentPermissionsRequest;
858 private boolean mAutoFillResetNeeded;
860 /** The last autofill id that was returned from {@link #getNextAutofillId()} */
861 private int mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
863 private AutofillPopupWindow mAutofillPopupWindow;
865 private static native String getDlWarning();
867 /** Return the intent that started this activity. */
868 public Intent getIntent() {
873 * Change the intent returned by {@link #getIntent}. This holds a
874 * reference to the given intent; it does not copy it. Often used in
875 * conjunction with {@link #onNewIntent}.
877 * @param newIntent The new Intent object to return from getIntent
882 public void setIntent(Intent newIntent) {
886 /** Return the application that owns this activity. */
887 public final Application getApplication() {
891 /** Is this activity embedded inside of another activity? */
892 public final boolean isChild() {
893 return mParent != null;
896 /** Return the parent activity if this view is an embedded child. */
897 public final Activity getParent() {
901 /** Retrieve the window manager for showing custom windows. */
902 public WindowManager getWindowManager() {
903 return mWindowManager;
907 * Retrieve the current {@link android.view.Window} for the activity.
908 * This can be used to directly access parts of the Window API that
909 * are not available through Activity/Screen.
911 * @return Window The current window, or null if the activity is not
914 public Window getWindow() {
919 * Return the LoaderManager for this activity, creating it if needed.
921 public LoaderManager getLoaderManager() {
922 return mFragments.getLoaderManager();
926 * Calls {@link android.view.Window#getCurrentFocus} on the
927 * Window of this Activity to return the currently focused view.
929 * @return View The current View with focus or null.
932 * @see android.view.Window#getCurrentFocus
935 public View getCurrentFocus() {
936 return mWindow != null ? mWindow.getCurrentFocus() : null;
940 * (Create and) return the autofill manager
942 * @return The autofill manager
944 @NonNull private AutofillManager getAutofillManager() {
945 if (mAutofillManager == null) {
946 mAutofillManager = getSystemService(AutofillManager.class);
949 return mAutofillManager;
953 protected void attachBaseContext(Context newBase) {
954 super.attachBaseContext(newBase);
955 newBase.setAutofillClient(this);
960 public final AutofillClient getAutofillClient() {
965 * Called when the activity is starting. This is where most initialization
966 * should go: calling {@link #setContentView(int)} to inflate the
967 * activity's UI, using {@link #findViewById} to programmatically interact
968 * with widgets in the UI, calling
969 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
970 * cursors for data being displayed, etc.
972 * <p>You can call {@link #finish} from within this function, in
973 * which case onDestroy() will be immediately called without any of the rest
974 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
975 * {@link #onPause}, etc) executing.
977 * <p><em>Derived classes must call through to the super class's
978 * implementation of this method. If they do not, an exception will be
981 * @param savedInstanceState If the activity is being re-initialized after
982 * previously being shut down then this Bundle contains the data it most
983 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
986 * @see #onSaveInstanceState
987 * @see #onRestoreInstanceState
992 protected void onCreate(@Nullable Bundle savedInstanceState) {
993 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
994 if (mLastNonConfigurationInstances != null) {
995 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
997 if (mActivityInfo.parentActivityName != null) {
998 if (mActionBar == null) {
999 mEnableDefaultActionBarUp = true;
1001 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
1004 if (savedInstanceState != null) {
1005 mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
1006 mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
1007 View.LAST_APP_AUTOFILL_ID);
1009 if (mAutoFillResetNeeded) {
1010 getAutofillManager().onCreate(savedInstanceState);
1013 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
1014 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
1015 ? mLastNonConfigurationInstances.fragments : null);
1017 mFragments.dispatchCreate();
1018 getApplication().dispatchActivityCreated(this, savedInstanceState);
1019 if (mVoiceInteractor != null) {
1020 mVoiceInteractor.attachActivity(this);
1022 mRestoredFromBundle = savedInstanceState != null;
1024 mAppsStatistics = SystemProperties.getBoolean("persist.sys.apps_statistics", false);
1028 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
1029 * the attribute {@link android.R.attr#persistableMode} set to
1030 * <code>persistAcrossReboots</code>.
1032 * @param savedInstanceState if the activity is being re-initialized after
1033 * previously being shut down then this Bundle contains the data it most
1034 * recently supplied in {@link #onSaveInstanceState}.
1035 * <b><i>Note: Otherwise it is null.</i></b>
1036 * @param persistentState if the activity is being re-initialized after
1037 * previously being shut down or powered off then this Bundle contains the data it most
1038 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
1039 * <b><i>Note: Otherwise it is null.</i></b>
1041 * @see #onCreate(android.os.Bundle)
1043 * @see #onSaveInstanceState
1044 * @see #onRestoreInstanceState
1045 * @see #onPostCreate
1047 public void onCreate(@Nullable Bundle savedInstanceState,
1048 @Nullable PersistableBundle persistentState) {
1049 onCreate(savedInstanceState);
1053 * The hook for {@link ActivityThread} to restore the state of this activity.
1055 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1056 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1058 * @param savedInstanceState contains the saved state
1060 final void performRestoreInstanceState(Bundle savedInstanceState) {
1061 onRestoreInstanceState(savedInstanceState);
1062 restoreManagedDialogs(savedInstanceState);
1066 * The hook for {@link ActivityThread} to restore the state of this activity.
1068 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1069 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1071 * @param savedInstanceState contains the saved state
1072 * @param persistentState contains the persistable saved state
1074 final void performRestoreInstanceState(Bundle savedInstanceState,
1075 PersistableBundle persistentState) {
1076 onRestoreInstanceState(savedInstanceState, persistentState);
1077 if (savedInstanceState != null) {
1078 restoreManagedDialogs(savedInstanceState);
1083 * This method is called after {@link #onStart} when the activity is
1084 * being re-initialized from a previously saved state, given here in
1085 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
1086 * to restore their state, but it is sometimes convenient to do it here
1087 * after all of the initialization has been done or to allow subclasses to
1088 * decide whether to use your default implementation. The default
1089 * implementation of this method performs a restore of any view state that
1090 * had previously been frozen by {@link #onSaveInstanceState}.
1092 * <p>This method is called between {@link #onStart} and
1093 * {@link #onPostCreate}.
1095 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1098 * @see #onPostCreate
1100 * @see #onSaveInstanceState
1102 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1103 if (mWindow != null) {
1104 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1105 if (windowState != null) {
1106 mWindow.restoreHierarchyState(windowState);
1112 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1113 * created with the attribute {@link android.R.attr#persistableMode} set to
1114 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1115 * came from the restored PersistableBundle first
1116 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1118 * <p>This method is called between {@link #onStart} and
1119 * {@link #onPostCreate}.
1121 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1123 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1124 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1126 * @see #onRestoreInstanceState(Bundle)
1128 * @see #onPostCreate
1130 * @see #onSaveInstanceState
1132 public void onRestoreInstanceState(Bundle savedInstanceState,
1133 PersistableBundle persistentState) {
1134 if (savedInstanceState != null) {
1135 onRestoreInstanceState(savedInstanceState);
1140 * Restore the state of any saved managed dialogs.
1142 * @param savedInstanceState The bundle to restore from.
1144 private void restoreManagedDialogs(Bundle savedInstanceState) {
1145 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1150 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1151 final int numDialogs = ids.length;
1152 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1153 for (int i = 0; i < numDialogs; i++) {
1154 final Integer dialogId = ids[i];
1155 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1156 if (dialogState != null) {
1157 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1158 // so tell createDialog() not to do it, otherwise we get an exception
1159 final ManagedDialog md = new ManagedDialog();
1160 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1161 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1162 if (md.mDialog != null) {
1163 mManagedDialogs.put(dialogId, md);
1164 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1165 md.mDialog.onRestoreInstanceState(dialogState);
1171 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1172 final Dialog dialog = onCreateDialog(dialogId, args);
1173 if (dialog == null) {
1176 dialog.dispatchOnCreate(state);
1180 private static String savedDialogKeyFor(int key) {
1181 return SAVED_DIALOG_KEY_PREFIX + key;
1184 private static String savedDialogArgsKeyFor(int key) {
1185 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1189 * Called when activity start-up is complete (after {@link #onStart}
1190 * and {@link #onRestoreInstanceState} have been called). Applications will
1191 * generally not implement this method; it is intended for system
1192 * classes to do final initialization after application code has run.
1194 * <p><em>Derived classes must call through to the super class's
1195 * implementation of this method. If they do not, an exception will be
1198 * @param savedInstanceState If the activity is being re-initialized after
1199 * previously being shut down then this Bundle contains the data it most
1200 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1204 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1207 onTitleChanged(getTitle(), getTitleColor());
1214 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1215 * created with the attribute {@link android.R.attr#persistableMode} set to
1216 * <code>persistAcrossReboots</code>.
1218 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1219 * @param persistentState The data caming from the PersistableBundle first
1220 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1224 public void onPostCreate(@Nullable Bundle savedInstanceState,
1225 @Nullable PersistableBundle persistentState) {
1226 onPostCreate(savedInstanceState);
1230 * Called after {@link #onCreate} — or after {@link #onRestart} when
1231 * the activity had been stopped, but is now again being displayed to the
1232 * user. It will be followed by {@link #onResume}.
1234 * <p><em>Derived classes must call through to the super class's
1235 * implementation of this method. If they do not, an exception will be
1243 protected void onStart() {
1244 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1247 mFragments.doLoaderStart();
1249 // region @android-x86-analytics
1251 if (mAppsStatistics) {
1252 AnalyticsHelper.hitScreen(this);
1255 getApplication().dispatchActivityStarted(this);
1257 if (mAutoFillResetNeeded) {
1258 AutofillManager afm = getAutofillManager();
1260 afm.onVisibleForAutofill();
1266 * Called after {@link #onStop} when the current activity is being
1267 * re-displayed to the user (the user has navigated back to it). It will
1268 * be followed by {@link #onStart} and then {@link #onResume}.
1270 * <p>For activities that are using raw {@link Cursor} objects (instead of
1271 * creating them through
1272 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1273 * this is usually the place
1274 * where the cursor should be requeried (because you had deactivated it in
1277 * <p><em>Derived classes must call through to the super class's
1278 * implementation of this method. If they do not, an exception will be
1286 protected void onRestart() {
1291 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1292 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1293 * to give the activity a hint that its state is no longer saved -- it will generally
1294 * be called after {@link #onSaveInstanceState} and prior to the activity being
1295 * resumed/started again.
1297 public void onStateNotSaved() {
1301 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1302 * {@link #onPause}, for your activity to start interacting with the user.
1303 * This is a good place to begin animations, open exclusive-access devices
1304 * (such as the camera), etc.
1306 * <p>Keep in mind that onResume is not the best indicator that your activity
1307 * is visible to the user; a system window such as the keyguard may be in
1308 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1309 * activity is visible to the user (for example, to resume a game).
1311 * <p><em>Derived classes must call through to the super class's
1312 * implementation of this method. If they do not, an exception will be
1315 * @see #onRestoreInstanceState
1317 * @see #onPostResume
1321 protected void onResume() {
1322 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1323 getApplication().dispatchActivityResumed(this);
1324 mActivityTransitionState.onResume(this, isTopOfTask());
1329 * Called when activity resume is complete (after {@link #onResume} has
1330 * been called). Applications will generally not implement this method;
1331 * it is intended for system classes to do final setup after application
1332 * resume code has run.
1334 * <p><em>Derived classes must call through to the super class's
1335 * implementation of this method. If they do not, an exception will be
1341 protected void onPostResume() {
1342 final Window win = getWindow();
1343 if (win != null) win.makeActive();
1344 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1348 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
1349 if (mVoiceInteractor != null) {
1350 for (Request activeRequest: mVoiceInteractor.getActiveRequests()) {
1351 activeRequest.cancel();
1352 activeRequest.clear();
1355 if (voiceInteractor == null) {
1356 mVoiceInteractor = null;
1358 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
1364 * Gets the next autofill ID.
1366 * <p>All IDs will be bigger than {@link View#LAST_APP_AUTOFILL_ID}. All IDs returned
1369 * @return A ID that is unique in the activity
1373 public int getNextAutofillId() {
1374 if (mLastAutofillId == Integer.MAX_VALUE - 1) {
1375 mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
1380 return mLastAutofillId;
1384 * Check whether this activity is running as part of a voice interaction with the user.
1385 * If true, it should perform its interaction with the user through the
1386 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1388 public boolean isVoiceInteraction() {
1389 return mVoiceInteractor != null;
1393 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1394 * of a voice interaction. That is, returns true if this activity was directly
1395 * started by the voice interaction service as the initiation of a voice interaction.
1396 * Otherwise, for example if it was started by another activity while under voice
1397 * interaction, returns false.
1399 public boolean isVoiceInteractionRoot() {
1401 return mVoiceInteractor != null
1402 && ActivityManager.getService().isRootVoiceInteraction(mToken);
1403 } catch (RemoteException e) {
1409 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1410 * interact with this activity.
1412 public VoiceInteractor getVoiceInteractor() {
1413 return mVoiceInteractor;
1417 * Queries whether the currently enabled voice interaction service supports returning
1418 * a voice interactor for use by the activity. This is valid only for the duration of the
1421 * @return whether the current voice interaction service supports local voice interaction
1423 public boolean isLocalVoiceInteractionSupported() {
1425 return ActivityManager.getService().supportsLocalVoiceInteraction();
1426 } catch (RemoteException re) {
1432 * Starts a local voice interaction session. When ready,
1433 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
1434 * to the registered voice interaction service.
1435 * @param privateOptions a Bundle of private arguments to the current voice interaction service
1437 public void startLocalVoiceInteraction(Bundle privateOptions) {
1439 ActivityManager.getService().startLocalVoiceInteraction(mToken, privateOptions);
1440 } catch (RemoteException re) {
1445 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
1446 * voice interaction session being started. You can now retrieve a voice interactor using
1447 * {@link #getVoiceInteractor()}.
1449 public void onLocalVoiceInteractionStarted() {
1453 * Callback to indicate that the local voice interaction has stopped either
1454 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
1455 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
1456 * is no longer valid after this.
1458 public void onLocalVoiceInteractionStopped() {
1462 * Request to terminate the current voice interaction that was previously started
1463 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
1464 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
1466 public void stopLocalVoiceInteraction() {
1468 ActivityManager.getService().stopLocalVoiceInteraction(mToken);
1469 } catch (RemoteException re) {
1474 * This is called for activities that set launchMode to "singleTop" in
1475 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1476 * flag when calling {@link #startActivity}. In either case, when the
1477 * activity is re-launched while at the top of the activity stack instead
1478 * of a new instance of the activity being started, onNewIntent() will be
1479 * called on the existing instance with the Intent that was used to
1482 * <p>An activity will always be paused before receiving a new intent, so
1483 * you can count on {@link #onResume} being called after this method.
1485 * <p>Note that {@link #getIntent} still returns the original Intent. You
1486 * can use {@link #setIntent} to update it to this new Intent.
1488 * @param intent The new intent that was started for the activity.
1494 protected void onNewIntent(Intent intent) {
1498 * The hook for {@link ActivityThread} to save the state of this activity.
1500 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1501 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1503 * @param outState The bundle to save the state to.
1505 final void performSaveInstanceState(Bundle outState) {
1506 onSaveInstanceState(outState);
1507 saveManagedDialogs(outState);
1508 mActivityTransitionState.saveState(outState);
1509 storeHasCurrentPermissionRequest(outState);
1510 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1514 * The hook for {@link ActivityThread} to save the state of this activity.
1516 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1517 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1519 * @param outState The bundle to save the state to.
1520 * @param outPersistentState The bundle to save persistent state to.
1522 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1523 onSaveInstanceState(outState, outPersistentState);
1524 saveManagedDialogs(outState);
1525 storeHasCurrentPermissionRequest(outState);
1526 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1527 ", " + outPersistentState);
1531 * Called to retrieve per-instance state from an activity before being killed
1532 * so that the state can be restored in {@link #onCreate} or
1533 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1534 * will be passed to both).
1536 * <p>This method is called before an activity may be killed so that when it
1537 * comes back some time in the future it can restore its state. For example,
1538 * if activity B is launched in front of activity A, and at some point activity
1539 * A is killed to reclaim resources, activity A will have a chance to save the
1540 * current state of its user interface via this method so that when the user
1541 * returns to activity A, the state of the user interface can be restored
1542 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1544 * <p>Do not confuse this method with activity lifecycle callbacks such as
1545 * {@link #onPause}, which is always called when an activity is being placed
1546 * in the background or on its way to destruction, or {@link #onStop} which
1547 * is called before destruction. One example of when {@link #onPause} and
1548 * {@link #onStop} is called and not this method is when a user navigates back
1549 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1550 * on B because that particular instance will never be restored, so the
1551 * system avoids calling it. An example when {@link #onPause} is called and
1552 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1553 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1554 * killed during the lifetime of B since the state of the user interface of
1555 * A will stay intact.
1557 * <p>The default implementation takes care of most of the UI per-instance
1558 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1559 * view in the hierarchy that has an id, and by saving the id of the currently
1560 * focused view (all of which is restored by the default implementation of
1561 * {@link #onRestoreInstanceState}). If you override this method to save additional
1562 * information not captured by each individual view, you will likely want to
1563 * call through to the default implementation, otherwise be prepared to save
1564 * all of the state of each view yourself.
1566 * <p>If called, this method will occur before {@link #onStop}. There are
1567 * no guarantees about whether it will occur before or after {@link #onPause}.
1569 * @param outState Bundle in which to place your saved state.
1572 * @see #onRestoreInstanceState
1575 protected void onSaveInstanceState(Bundle outState) {
1576 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1578 outState.putInt(LAST_AUTOFILL_ID, mLastAutofillId);
1579 Parcelable p = mFragments.saveAllState();
1581 outState.putParcelable(FRAGMENTS_TAG, p);
1583 if (mAutoFillResetNeeded) {
1584 outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
1585 getAutofillManager().onSaveInstanceState(outState);
1587 getApplication().dispatchActivitySaveInstanceState(this, outState);
1591 * This is the same as {@link #onSaveInstanceState} but is called for activities
1592 * created with the attribute {@link android.R.attr#persistableMode} set to
1593 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1594 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1595 * the first time that this activity is restarted following the next device reboot.
1597 * @param outState Bundle in which to place your saved state.
1598 * @param outPersistentState State which will be saved across reboots.
1600 * @see #onSaveInstanceState(Bundle)
1602 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1605 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1606 onSaveInstanceState(outState);
1610 * Save the state of any managed dialogs.
1612 * @param outState place to store the saved state.
1614 private void saveManagedDialogs(Bundle outState) {
1615 if (mManagedDialogs == null) {
1619 final int numDialogs = mManagedDialogs.size();
1620 if (numDialogs == 0) {
1624 Bundle dialogState = new Bundle();
1626 int[] ids = new int[mManagedDialogs.size()];
1628 // save each dialog's bundle, gather the ids
1629 for (int i = 0; i < numDialogs; i++) {
1630 final int key = mManagedDialogs.keyAt(i);
1632 final ManagedDialog md = mManagedDialogs.valueAt(i);
1633 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1634 if (md.mArgs != null) {
1635 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1639 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1640 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1645 * Called as part of the activity lifecycle when an activity is going into
1646 * the background, but has not (yet) been killed. The counterpart to
1647 * {@link #onResume}.
1649 * <p>When activity B is launched in front of activity A, this callback will
1650 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1651 * so be sure to not do anything lengthy here.
1653 * <p>This callback is mostly used for saving any persistent state the
1654 * activity is editing, to present a "edit in place" model to the user and
1655 * making sure nothing is lost if there are not enough resources to start
1656 * the new activity without first killing this one. This is also a good
1657 * place to do things like stop animations and other things that consume a
1658 * noticeable amount of CPU in order to make the switch to the next activity
1659 * as fast as possible, or to close resources that are exclusive access
1660 * such as the camera.
1662 * <p>In situations where the system needs more memory it may kill paused
1663 * processes to reclaim resources. Because of this, you should be sure
1664 * that all of your state is saved by the time you return from
1665 * this function. In general {@link #onSaveInstanceState} is used to save
1666 * per-instance state in the activity and this method is used to store
1667 * global persistent data (in content providers, files, etc.)
1669 * <p>After receiving this call you will usually receive a following call
1670 * to {@link #onStop} (after the next activity has been resumed and
1671 * displayed), however in some cases there will be a direct call back to
1672 * {@link #onResume} without going through the stopped state.
1674 * <p><em>Derived classes must call through to the super class's
1675 * implementation of this method. If they do not, an exception will be
1679 * @see #onSaveInstanceState
1683 protected void onPause() {
1684 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1685 getApplication().dispatchActivityPaused(this);
1690 * Called as part of the activity lifecycle when an activity is about to go
1691 * into the background as the result of user choice. For example, when the
1692 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1693 * when an incoming phone call causes the in-call Activity to be automatically
1694 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1695 * the activity being interrupted. In cases when it is invoked, this method
1696 * is called right before the activity's {@link #onPause} callback.
1698 * <p>This callback and {@link #onUserInteraction} are intended to help
1699 * activities manage status bar notifications intelligently; specifically,
1700 * for helping activities determine the proper time to cancel a notfication.
1702 * @see #onUserInteraction()
1704 protected void onUserLeaveHint() {
1708 * Generate a new thumbnail for this activity. This method is called before
1709 * pausing the activity, and should draw into <var>outBitmap</var> the
1710 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1711 * can use the given <var>canvas</var>, which is configured to draw into the
1712 * bitmap, for rendering if desired.
1714 * <p>The default implementation returns fails and does not draw a thumbnail;
1715 * this will result in the platform creating its own thumbnail if needed.
1717 * @param outBitmap The bitmap to contain the thumbnail.
1718 * @param canvas Can be used to render into the bitmap.
1720 * @return Return true if you have drawn into the bitmap; otherwise after
1721 * you return it will be filled with a default thumbnail.
1723 * @see #onCreateDescription
1724 * @see #onSaveInstanceState
1727 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1732 * Generate a new description for this activity. This method is called
1733 * before pausing the activity and can, if desired, return some textual
1734 * description of its current state to be displayed to the user.
1736 * <p>The default implementation returns null, which will cause you to
1737 * inherit the description from the previous activity. If all activities
1738 * return null, generally the label of the top activity will be used as the
1741 * @return A description of what the user is doing. It should be short and
1742 * sweet (only a few words).
1744 * @see #onCreateThumbnail
1745 * @see #onSaveInstanceState
1749 public CharSequence onCreateDescription() {
1754 * This is called when the user is requesting an assist, to build a full
1755 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1756 * application. You can override this method to place into the bundle anything
1757 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1758 * of the assist Intent.
1760 * <p>This function will be called after any global assist callbacks that had
1761 * been registered with {@link Application#registerOnProvideAssistDataListener
1762 * Application.registerOnProvideAssistDataListener}.
1764 public void onProvideAssistData(Bundle data) {
1768 * This is called when the user is requesting an assist, to provide references
1769 * to content related to the current activity. Before being called, the
1770 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1771 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1772 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1773 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1774 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1776 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1777 * context of the activity, and fill in its ClipData with additional content of
1778 * interest that the user is currently viewing. For example, an image gallery application
1779 * that has launched in to an activity allowing the user to swipe through pictures should
1780 * modify the intent to reference the current image they are looking it; such an
1781 * application when showing a list of pictures should add a ClipData that has
1782 * references to all of the pictures currently visible on screen.</p>
1784 * @param outContent The assist content to return.
1786 public void onProvideAssistContent(AssistContent outContent) {
1790 * Request the Keyboard Shortcuts screen to show up. This will trigger
1791 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
1793 public final void requestShowKeyboardShortcuts() {
1794 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
1795 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1796 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1800 * Dismiss the Keyboard Shortcuts screen.
1802 public final void dismissKeyboardShortcutsHelper() {
1803 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
1804 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1805 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1809 public void onProvideKeyboardShortcuts(
1810 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
1814 KeyboardShortcutGroup group = null;
1815 int menuSize = menu.size();
1816 for (int i = 0; i < menuSize; ++i) {
1817 final MenuItem item = menu.getItem(i);
1818 final CharSequence title = item.getTitle();
1819 final char alphaShortcut = item.getAlphabeticShortcut();
1820 final int alphaModifiers = item.getAlphabeticModifiers();
1821 if (title != null && alphaShortcut != MIN_VALUE) {
1822 if (group == null) {
1823 final int resource = mApplication.getApplicationInfo().labelRes;
1824 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
1826 group.addItem(new KeyboardShortcutInfo(
1827 title, alphaShortcut, alphaModifiers));
1830 if (group != null) {
1836 * Ask to have the current assistant shown to the user. This only works if the calling
1837 * activity is the current foreground activity. It is the same as calling
1838 * {@link android.service.voice.VoiceInteractionService#showSession
1839 * VoiceInteractionService.showSession} and requesting all of the possible context.
1840 * The receiver will always see
1841 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1842 * @return Returns true if the assistant was successfully invoked, else false. For example
1843 * false will be returned if the caller is not the current top activity.
1845 public boolean showAssist(Bundle args) {
1847 return ActivityManager.getService().showAssistFromActivity(mToken, args);
1848 } catch (RemoteException e) {
1854 * Called when you are no longer visible to the user. You will next
1855 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1856 * depending on later user activity.
1858 * <p><em>Derived classes must call through to the super class's
1859 * implementation of this method. If they do not, an exception will be
1864 * @see #onSaveInstanceState
1868 protected void onStop() {
1869 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1870 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1871 mActivityTransitionState.onStop();
1872 getApplication().dispatchActivityStopped(this);
1873 mTranslucentCallback = null;
1876 if (isFinishing()) {
1877 if (mAutoFillResetNeeded) {
1878 getAutofillManager().commit();
1879 } else if (mIntent != null
1880 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
1881 // Activity was launched when user tapped a link in the Autofill Save UI - since
1882 // user launched another activity, the Save UI should not be restored when this
1883 // activity is finished.
1884 getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_CANCEL,
1885 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
1891 * Perform any final cleanup before an activity is destroyed. This can
1892 * happen either because the activity is finishing (someone called
1893 * {@link #finish} on it, or because the system is temporarily destroying
1894 * this instance of the activity to save space. You can distinguish
1895 * between these two scenarios with the {@link #isFinishing} method.
1897 * <p><em>Note: do not count on this method being called as a place for
1898 * saving data! For example, if an activity is editing data in a content
1899 * provider, those edits should be committed in either {@link #onPause} or
1900 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1901 * free resources like threads that are associated with an activity, so
1902 * that a destroyed activity does not leave such things around while the
1903 * rest of its application is still running. There are situations where
1904 * the system will simply kill the activity's hosting process without
1905 * calling this method (or any others) in it, so it should not be used to
1906 * do things that are intended to remain around after the process goes
1909 * <p><em>Derived classes must call through to the super class's
1910 * implementation of this method. If they do not, an exception will be
1919 protected void onDestroy() {
1920 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1923 // dismiss any dialogs we are managing.
1924 if (mManagedDialogs != null) {
1925 final int numDialogs = mManagedDialogs.size();
1926 for (int i = 0; i < numDialogs; i++) {
1927 final ManagedDialog md = mManagedDialogs.valueAt(i);
1928 if (md.mDialog.isShowing()) {
1929 md.mDialog.dismiss();
1932 mManagedDialogs = null;
1935 // close any cursors we are managing.
1936 synchronized (mManagedCursors) {
1937 int numCursors = mManagedCursors.size();
1938 for (int i = 0; i < numCursors; i++) {
1939 ManagedCursor c = mManagedCursors.get(i);
1944 mManagedCursors.clear();
1947 // Close any open search dialog
1948 if (mSearchManager != null) {
1949 mSearchManager.stopSearch();
1952 if (mActionBar != null) {
1953 mActionBar.onDestroy();
1956 getApplication().dispatchActivityDestroyed(this);
1960 * Report to the system that your app is now fully drawn, purely for diagnostic
1961 * purposes (calling it does not impact the visible behavior of the activity).
1962 * This is only used to help instrument application launch times, so that the
1963 * app can report when it is fully in a usable state; without this, the only thing
1964 * the system itself can determine is the point at which the activity's window
1965 * is <em>first</em> drawn and displayed. To participate in app launch time
1966 * measurement, you should always call this method after first launch (when
1967 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1968 * entirely drawn your UI and populated with all of the significant data. You
1969 * can safely call this method any time after first launch as well, in which case
1970 * it will simply be ignored.
1972 public void reportFullyDrawn() {
1973 if (mDoReportFullyDrawn) {
1974 mDoReportFullyDrawn = false;
1976 ActivityManager.getService().reportActivityFullyDrawn(mToken, mRestoredFromBundle);
1977 } catch (RemoteException e) {
1983 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
1984 * visa-versa. This method provides the same configuration that will be sent in the following
1985 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
1987 * @see android.R.attr#resizeableActivity
1989 * @param isInMultiWindowMode True if the activity is in multi-window mode.
1990 * @param newConfig The new configuration of the activity with the state
1991 * {@param isInMultiWindowMode}.
1993 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
1994 // Left deliberately empty. There should be no side effects if a direct
1995 // subclass of Activity does not call super.
1996 onMultiWindowModeChanged(isInMultiWindowMode);
2000 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
2003 * @see android.R.attr#resizeableActivity
2005 * @param isInMultiWindowMode True if the activity is in multi-window mode.
2007 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
2010 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
2011 // Left deliberately empty. There should be no side effects if a direct
2012 // subclass of Activity does not call super.
2016 * Returns true if the activity is currently in multi-window mode.
2017 * @see android.R.attr#resizeableActivity
2019 * @return True if the activity is in multi-window mode.
2021 public boolean isInMultiWindowMode() {
2023 return ActivityManager.getService().isInMultiWindowMode(mToken);
2024 } catch (RemoteException e) {
2030 * Called by the system when the activity changes to and from picture-in-picture mode. This
2031 * method provides the same configuration that will be sent in the following
2032 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2034 * @see android.R.attr#supportsPictureInPicture
2036 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2037 * @param newConfig The new configuration of the activity with the state
2038 * {@param isInPictureInPictureMode}.
2040 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2041 Configuration newConfig) {
2042 // Left deliberately empty. There should be no side effects if a direct
2043 // subclass of Activity does not call super.
2044 onPictureInPictureModeChanged(isInPictureInPictureMode);
2048 * Called by the system when the activity changes to and from picture-in-picture mode.
2050 * @see android.R.attr#supportsPictureInPicture
2052 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2054 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
2057 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2058 // Left deliberately empty. There should be no side effects if a direct
2059 // subclass of Activity does not call super.
2063 * Returns true if the activity is currently in picture-in-picture mode.
2064 * @see android.R.attr#supportsPictureInPicture
2066 * @return True if the activity is in picture-in-picture mode.
2068 public boolean isInPictureInPictureMode() {
2070 return ActivityManager.getService().isInPictureInPictureMode(mToken);
2071 } catch (RemoteException e) {
2077 * Puts the activity in picture-in-picture mode if possible in the current system state. Any
2078 * prior calls to {@link #setPictureInPictureParams(PictureInPictureParams)} will still apply
2079 * when entering picture-in-picture through this call.
2081 * @see #enterPictureInPictureMode(PictureInPictureParams)
2082 * @see android.R.attr#supportsPictureInPicture
2085 public void enterPictureInPictureMode() {
2086 enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
2091 public boolean enterPictureInPictureMode(@NonNull PictureInPictureArgs args) {
2092 return enterPictureInPictureMode(PictureInPictureArgs.convert(args));
2096 * Puts the activity in picture-in-picture mode if possible in the current system state. The
2097 * set parameters in {@param params} will be combined with the parameters from prior calls to
2098 * {@link #setPictureInPictureParams(PictureInPictureParams)}.
2100 * The system may disallow entering picture-in-picture in various cases, including when the
2101 * activity is not visible, if the screen is locked or if the user has an activity pinned.
2103 * @see android.R.attr#supportsPictureInPicture
2104 * @see PictureInPictureParams
2106 * @param params non-null parameters to be combined with previously set parameters when entering
2107 * picture-in-picture.
2109 * @return true if the system puts this activity into picture-in-picture mode or was already
2110 * in picture-in-picture mode (@see {@link #isInPictureInPictureMode())
2112 public boolean enterPictureInPictureMode(@NonNull PictureInPictureParams params) {
2114 if (params == null) {
2115 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2117 if (!mCanEnterPictureInPicture) {
2118 throw new IllegalStateException("Activity must be resumed to enter"
2119 + " picture-in-picture");
2121 return ActivityManagerNative.getDefault().enterPictureInPictureMode(mToken, params);
2122 } catch (RemoteException e) {
2129 public void setPictureInPictureArgs(@NonNull PictureInPictureArgs args) {
2130 setPictureInPictureParams(PictureInPictureArgs.convert(args));
2134 * Updates the properties of the picture-in-picture activity, or sets it to be used later when
2135 * {@link #enterPictureInPictureMode()} is called.
2137 * @param params the new parameters for the picture-in-picture.
2139 public void setPictureInPictureParams(@NonNull PictureInPictureParams params) {
2141 if (params == null) {
2142 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2144 ActivityManagerNative.getDefault().setPictureInPictureParams(mToken, params);
2145 } catch (RemoteException e) {
2150 * Return the number of actions that will be displayed in the picture-in-picture UI when the
2151 * user interacts with the activity currently in picture-in-picture mode. This number may change
2152 * if the global configuration changes (ie. if the device is plugged into an external display),
2153 * but will always be larger than three.
2155 public int getMaxNumPictureInPictureActions() {
2157 return ActivityManagerNative.getDefault().getMaxNumPictureInPictureActions(mToken);
2158 } catch (RemoteException e) {
2163 void dispatchMovedToDisplay(int displayId, Configuration config) {
2164 updateDisplay(displayId);
2165 onMovedToDisplay(displayId, config);
2169 * Called by the system when the activity is moved from one display to another without
2170 * recreation. This means that this activity is declared to handle all changes to configuration
2171 * that happened when it was switched to another display, so it wasn't destroyed and created
2174 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
2175 * applied configuration actually changed. It is up to app developer to choose whether to handle
2176 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
2179 * <p>Use this callback to track changes to the displays if some activity functionality relies
2180 * on an association with some display properties.
2182 * @param displayId The id of the display to which activity was moved.
2183 * @param config Configuration of the activity resources on new display after move.
2185 * @see #onConfigurationChanged(Configuration)
2186 * @see View#onMovedToDisplay(int, Configuration)
2189 public void onMovedToDisplay(int displayId, Configuration config) {
2193 * Called by the system when the device configuration changes while your
2194 * activity is running. Note that this will <em>only</em> be called if
2195 * you have selected configurations you would like to handle with the
2196 * {@link android.R.attr#configChanges} attribute in your manifest. If
2197 * any configuration change occurs that is not selected to be reported
2198 * by that attribute, then instead of reporting it the system will stop
2199 * and restart the activity (to have it launched with the new
2202 * <p>At the time that this function has been called, your Resources
2203 * object will have been updated to return resource values matching the
2204 * new configuration.
2206 * @param newConfig The new device configuration.
2208 public void onConfigurationChanged(Configuration newConfig) {
2209 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
2212 mFragments.dispatchConfigurationChanged(newConfig);
2214 if (mWindow != null) {
2215 // Pass the configuration changed event to the window
2216 mWindow.onConfigurationChanged(newConfig);
2219 if (mActionBar != null) {
2220 // Do this last; the action bar will need to access
2221 // view changes from above.
2222 mActionBar.onConfigurationChanged(newConfig);
2227 * If this activity is being destroyed because it can not handle a
2228 * configuration parameter being changed (and thus its
2229 * {@link #onConfigurationChanged(Configuration)} method is
2230 * <em>not</em> being called), then you can use this method to discover
2231 * the set of changes that have occurred while in the process of being
2232 * destroyed. Note that there is no guarantee that these will be
2233 * accurate (other changes could have happened at any time), so you should
2234 * only use this as an optimization hint.
2236 * @return Returns a bit field of the configuration parameters that are
2237 * changing, as defined by the {@link android.content.res.Configuration}
2240 public int getChangingConfigurations() {
2241 return mConfigChangeFlags;
2245 * Retrieve the non-configuration instance data that was previously
2246 * returned by {@link #onRetainNonConfigurationInstance()}. This will
2247 * be available from the initial {@link #onCreate} and
2248 * {@link #onStart} calls to the new instance, allowing you to extract
2249 * any useful dynamic state from the previous instance.
2251 * <p>Note that the data you retrieve here should <em>only</em> be used
2252 * as an optimization for handling configuration changes. You should always
2253 * be able to handle getting a null pointer back, and an activity must
2254 * still be able to restore itself to its previous state (through the
2255 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2256 * function returns null.
2258 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2259 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2260 * available on older platforms through the Android support libraries.
2262 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
2265 public Object getLastNonConfigurationInstance() {
2266 return mLastNonConfigurationInstances != null
2267 ? mLastNonConfigurationInstances.activity : null;
2271 * Called by the system, as part of destroying an
2272 * activity due to a configuration change, when it is known that a new
2273 * instance will immediately be created for the new configuration. You
2274 * can return any object you like here, including the activity instance
2275 * itself, which can later be retrieved by calling
2276 * {@link #getLastNonConfigurationInstance()} in the new activity
2279 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2280 * or later, consider instead using a {@link Fragment} with
2281 * {@link Fragment#setRetainInstance(boolean)
2282 * Fragment.setRetainInstance(boolean}.</em>
2284 * <p>This function is called purely as an optimization, and you must
2285 * not rely on it being called. When it is called, a number of guarantees
2286 * will be made to help optimize configuration switching:
2288 * <li> The function will be called between {@link #onStop} and
2289 * {@link #onDestroy}.
2290 * <li> A new instance of the activity will <em>always</em> be immediately
2291 * created after this one's {@link #onDestroy()} is called. In particular,
2292 * <em>no</em> messages will be dispatched during this time (when the returned
2293 * object does not have an activity to be associated with).
2294 * <li> The object you return here will <em>always</em> be available from
2295 * the {@link #getLastNonConfigurationInstance()} method of the following
2296 * activity instance as described there.
2299 * <p>These guarantees are designed so that an activity can use this API
2300 * to propagate extensive state from the old to new activity instance, from
2301 * loaded bitmaps, to network connections, to evenly actively running
2302 * threads. Note that you should <em>not</em> propagate any data that
2303 * may change based on the configuration, including any data loaded from
2304 * resources such as strings, layouts, or drawables.
2306 * <p>The guarantee of no message handling during the switch to the next
2307 * activity simplifies use with active objects. For example if your retained
2308 * state is an {@link android.os.AsyncTask} you are guaranteed that its
2309 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
2310 * not be called from the call here until you execute the next instance's
2311 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
2312 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
2313 * running in a separate thread.)
2315 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2316 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2317 * available on older platforms through the Android support libraries.
2319 * @return any Object holding the desired state to propagate to the
2320 * next activity instance
2322 public Object onRetainNonConfigurationInstance() {
2327 * Retrieve the non-configuration instance data that was previously
2328 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
2329 * be available from the initial {@link #onCreate} and
2330 * {@link #onStart} calls to the new instance, allowing you to extract
2331 * any useful dynamic state from the previous instance.
2333 * <p>Note that the data you retrieve here should <em>only</em> be used
2334 * as an optimization for handling configuration changes. You should always
2335 * be able to handle getting a null pointer back, and an activity must
2336 * still be able to restore itself to its previous state (through the
2337 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2338 * function returns null.
2340 * @return Returns the object previously returned by
2341 * {@link #onRetainNonConfigurationChildInstances()}
2344 HashMap<String, Object> getLastNonConfigurationChildInstances() {
2345 return mLastNonConfigurationInstances != null
2346 ? mLastNonConfigurationInstances.children : null;
2350 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
2351 * it should return either a mapping from child activity id strings to arbitrary objects,
2352 * or null. This method is intended to be used by Activity framework subclasses that control a
2353 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
2354 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
2357 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
2361 NonConfigurationInstances retainNonConfigurationInstances() {
2362 Object activity = onRetainNonConfigurationInstance();
2363 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
2364 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
2366 // We're already stopped but we've been asked to retain.
2367 // Our fragments are taken care of but we need to mark the loaders for retention.
2368 // In order to do this correctly we need to restart the loaders first before
2369 // handing them off to the next activity.
2370 mFragments.doLoaderStart();
2371 mFragments.doLoaderStop(true);
2372 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
2374 if (activity == null && children == null && fragments == null && loaders == null
2375 && mVoiceInteractor == null) {
2379 NonConfigurationInstances nci = new NonConfigurationInstances();
2380 nci.activity = activity;
2381 nci.children = children;
2382 nci.fragments = fragments;
2383 nci.loaders = loaders;
2384 if (mVoiceInteractor != null) {
2385 mVoiceInteractor.retainInstance();
2386 nci.voiceInteractor = mVoiceInteractor;
2391 public void onLowMemory() {
2392 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
2394 mFragments.dispatchLowMemory();
2397 public void onTrimMemory(int level) {
2398 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
2400 mFragments.dispatchTrimMemory(level);
2404 * Return the FragmentManager for interacting with fragments associated
2405 * with this activity.
2407 public FragmentManager getFragmentManager() {
2408 return mFragments.getFragmentManager();
2412 * Called when a Fragment is being attached to this activity, immediately
2413 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
2414 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
2416 public void onAttachFragment(Fragment fragment) {
2421 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2422 * that gives the resulting {@link Cursor} to call
2423 * {@link #startManagingCursor} so that the activity will manage its
2424 * lifecycle for you.
2426 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2427 * or later, consider instead using {@link LoaderManager} instead, available
2428 * via {@link #getLoaderManager()}.</em>
2430 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2431 * this method, because the activity will do that for you at the appropriate time. However, if
2432 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2433 * not</em> automatically close the cursor and, in that case, you must call
2434 * {@link Cursor#close()}.</p>
2436 * @param uri The URI of the content provider to query.
2437 * @param projection List of columns to return.
2438 * @param selection SQL WHERE clause.
2439 * @param sortOrder SQL ORDER BY clause.
2441 * @return The Cursor that was returned by query().
2443 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2444 * @see #startManagingCursor
2447 * @deprecated Use {@link CursorLoader} instead.
2450 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2452 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
2454 startManagingCursor(c);
2461 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2462 * that gives the resulting {@link Cursor} to call
2463 * {@link #startManagingCursor} so that the activity will manage its
2464 * lifecycle for you.
2466 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2467 * or later, consider instead using {@link LoaderManager} instead, available
2468 * via {@link #getLoaderManager()}.</em>
2470 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2471 * this method, because the activity will do that for you at the appropriate time. However, if
2472 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2473 * not</em> automatically close the cursor and, in that case, you must call
2474 * {@link Cursor#close()}.</p>
2476 * @param uri The URI of the content provider to query.
2477 * @param projection List of columns to return.
2478 * @param selection SQL WHERE clause.
2479 * @param selectionArgs The arguments to selection, if any ?s are pesent
2480 * @param sortOrder SQL ORDER BY clause.
2482 * @return The Cursor that was returned by query().
2484 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2485 * @see #startManagingCursor
2487 * @deprecated Use {@link CursorLoader} instead.
2490 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2491 String[] selectionArgs, String sortOrder) {
2492 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2494 startManagingCursor(c);
2500 * This method allows the activity to take care of managing the given
2501 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2502 * That is, when the activity is stopped it will automatically call
2503 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2504 * it will call {@link Cursor#requery} for you. When the activity is
2505 * destroyed, all managed Cursors will be closed automatically.
2507 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2508 * or later, consider instead using {@link LoaderManager} instead, available
2509 * via {@link #getLoaderManager()}.</em>
2511 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2512 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2513 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2514 * <em>will not</em> automatically close the cursor and, in that case, you must call
2515 * {@link Cursor#close()}.</p>
2517 * @param c The Cursor to be managed.
2519 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2520 * @see #stopManagingCursor
2522 * @deprecated Use the new {@link android.content.CursorLoader} class with
2523 * {@link LoaderManager} instead; this is also
2524 * available on older platforms through the Android compatibility package.
2527 public void startManagingCursor(Cursor c) {
2528 synchronized (mManagedCursors) {
2529 mManagedCursors.add(new ManagedCursor(c));
2534 * Given a Cursor that was previously given to
2535 * {@link #startManagingCursor}, stop the activity's management of that
2538 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2539 * the system <em>will not</em> automatically close the cursor and you must call
2540 * {@link Cursor#close()}.</p>
2542 * @param c The Cursor that was being managed.
2544 * @see #startManagingCursor
2546 * @deprecated Use the new {@link android.content.CursorLoader} class with
2547 * {@link LoaderManager} instead; this is also
2548 * available on older platforms through the Android compatibility package.
2551 public void stopManagingCursor(Cursor c) {
2552 synchronized (mManagedCursors) {
2553 final int N = mManagedCursors.size();
2554 for (int i=0; i<N; i++) {
2555 ManagedCursor mc = mManagedCursors.get(i);
2556 if (mc.mCursor == c) {
2557 mManagedCursors.remove(i);
2565 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2570 public void setPersistent(boolean isPersistent) {
2574 * Finds a view that was identified by the {@code android:id} XML attribute
2575 * that was processed in {@link #onCreate}.
2577 * <strong>Note:</strong> In most cases -- depending on compiler support --
2578 * the resulting view is automatically cast to the target class type. If
2579 * the target class type is unconstrained, an explicit cast may be
2582 * @param id the ID to search for
2583 * @return a view with given ID if found, or {@code null} otherwise
2584 * @see View#findViewById(int)
2587 public <T extends View> T findViewById(@IdRes int id) {
2588 return getWindow().findViewById(id);
2592 * Retrieve a reference to this activity's ActionBar.
2594 * @return The Activity's ActionBar, or null if it does not have one.
2597 public ActionBar getActionBar() {
2598 initWindowDecorActionBar();
2603 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2606 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2607 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2608 * a traditional window decor action bar. The toolbar's menu will be populated with the
2609 * Activity's options menu and the navigation button will be wired through the standard
2610 * {@link android.R.id#home home} menu select action.</p>
2612 * <p>In order to use a Toolbar within the Activity's window content the application
2613 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2615 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
2617 public void setActionBar(@Nullable Toolbar toolbar) {
2618 final ActionBar ab = getActionBar();
2619 if (ab instanceof WindowDecorActionBar) {
2620 throw new IllegalStateException("This Activity already has an action bar supplied " +
2621 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2622 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2625 // If we reach here then we're setting a new action bar
2626 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
2627 mMenuInflater = null;
2629 // If we have an action bar currently, destroy it
2634 if (toolbar != null) {
2635 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2637 mWindow.setCallback(tbab.getWrappedWindowCallback());
2640 // Re-set the original window callback since we may have already set a Toolbar wrapper
2641 mWindow.setCallback(this);
2644 invalidateOptionsMenu();
2648 * Creates a new ActionBar, locates the inflated ActionBarView,
2649 * initializes the ActionBar with the view, and sets mActionBar.
2651 private void initWindowDecorActionBar() {
2652 Window window = getWindow();
2654 // Initializing the window decor can change window feature flags.
2655 // Make sure that we have the correct set before performing the test below.
2656 window.getDecorView();
2658 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2662 mActionBar = new WindowDecorActionBar(this);
2663 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2665 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2666 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2670 * Set the activity content from a layout resource. The resource will be
2671 * inflated, adding all top-level views to the activity.
2673 * @param layoutResID Resource ID to be inflated.
2675 * @see #setContentView(android.view.View)
2676 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2678 public void setContentView(@LayoutRes int layoutResID) {
2679 getWindow().setContentView(layoutResID);
2680 initWindowDecorActionBar();
2684 * Set the activity content to an explicit view. This view is placed
2685 * directly into the activity's view hierarchy. It can itself be a complex
2686 * view hierarchy. When calling this method, the layout parameters of the
2687 * specified view are ignored. Both the width and the height of the view are
2688 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2689 * your own layout parameters, invoke
2690 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2693 * @param view The desired content to display.
2695 * @see #setContentView(int)
2696 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2698 public void setContentView(View view) {
2699 getWindow().setContentView(view);
2700 initWindowDecorActionBar();
2704 * Set the activity content to an explicit view. This view is placed
2705 * directly into the activity's view hierarchy. It can itself be a complex
2708 * @param view The desired content to display.
2709 * @param params Layout parameters for the view.
2711 * @see #setContentView(android.view.View)
2712 * @see #setContentView(int)
2714 public void setContentView(View view, ViewGroup.LayoutParams params) {
2715 getWindow().setContentView(view, params);
2716 initWindowDecorActionBar();
2720 * Add an additional content view to the activity. Added after any existing
2721 * ones in the activity -- existing views are NOT removed.
2723 * @param view The desired content to display.
2724 * @param params Layout parameters for the view.
2726 public void addContentView(View view, ViewGroup.LayoutParams params) {
2727 getWindow().addContentView(view, params);
2728 initWindowDecorActionBar();
2732 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2733 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2735 * <p>This method will return non-null after content has been initialized (e.g. by using
2736 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2738 * @return This window's content TransitionManager or null if none is set.
2740 public TransitionManager getContentTransitionManager() {
2741 return getWindow().getTransitionManager();
2745 * Set the {@link TransitionManager} to use for default transitions in this window.
2746 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2748 * @param tm The TransitionManager to use for scene changes.
2750 public void setContentTransitionManager(TransitionManager tm) {
2751 getWindow().setTransitionManager(tm);
2755 * Retrieve the {@link Scene} representing this window's current content.
2756 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2758 * <p>This method will return null if the current content is not represented by a Scene.</p>
2760 * @return Current Scene being shown or null
2762 public Scene getContentScene() {
2763 return getWindow().getContentScene();
2767 * Sets whether this activity is finished when touched outside its window's
2770 public void setFinishOnTouchOutside(boolean finish) {
2771 mWindow.setCloseOnTouchOutside(finish);
2775 @IntDef(prefix = { "DEFAULT_KEYS_" }, value = {
2776 DEFAULT_KEYS_DISABLE,
2777 DEFAULT_KEYS_DIALER,
2778 DEFAULT_KEYS_SHORTCUT,
2779 DEFAULT_KEYS_SEARCH_LOCAL,
2780 DEFAULT_KEYS_SEARCH_GLOBAL
2782 @Retention(RetentionPolicy.SOURCE)
2783 @interface DefaultKeyMode {}
2786 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2789 * @see #setDefaultKeyMode
2791 static public final int DEFAULT_KEYS_DISABLE = 0;
2793 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2796 * @see #setDefaultKeyMode
2798 static public final int DEFAULT_KEYS_DIALER = 1;
2800 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2801 * default key handling.
2803 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2805 * @see #setDefaultKeyMode
2807 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2809 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2810 * will start an application-defined search. (If the application or activity does not
2811 * actually define a search, the the keys will be ignored.)
2813 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2815 * @see #setDefaultKeyMode
2817 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2820 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2821 * will start a global search (typically web search, but some platforms may define alternate
2822 * methods for global search)
2824 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2826 * @see #setDefaultKeyMode
2828 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2831 * Select the default key handling for this activity. This controls what
2832 * will happen to key events that are not otherwise handled. The default
2833 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2834 * floor. Other modes allow you to launch the dialer
2835 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2836 * menu without requiring the menu key be held down
2837 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2838 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2840 * <p>Note that the mode selected here does not impact the default
2841 * handling of system keys, such as the "back" and "menu" keys, and your
2842 * activity and its views always get a first chance to receive and handle
2843 * all application keys.
2845 * @param mode The desired default key mode constant.
2849 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2850 mDefaultKeyMode = mode;
2852 // Some modes use a SpannableStringBuilder to track & dispatch input events
2853 // This list must remain in sync with the switch in onKeyDown()
2855 case DEFAULT_KEYS_DISABLE:
2856 case DEFAULT_KEYS_SHORTCUT:
2857 mDefaultKeySsb = null; // not used in these modes
2859 case DEFAULT_KEYS_DIALER:
2860 case DEFAULT_KEYS_SEARCH_LOCAL:
2861 case DEFAULT_KEYS_SEARCH_GLOBAL:
2862 mDefaultKeySsb = new SpannableStringBuilder();
2863 Selection.setSelection(mDefaultKeySsb,0);
2866 throw new IllegalArgumentException();
2871 * Called when a key was pressed down and not handled by any of the views
2872 * inside of the activity. So, for example, key presses while the cursor
2873 * is inside a TextView will not trigger the event (unless it is a navigation
2874 * to another object) because TextView handles its own key presses.
2876 * <p>If the focused view didn't want this event, this method is called.
2878 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2879 * by calling {@link #onBackPressed()}, though the behavior varies based
2880 * on the application compatibility mode: for
2881 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2882 * it will set up the dispatch to call {@link #onKeyUp} where the action
2883 * will be performed; for earlier applications, it will perform the
2884 * action immediately in on-down, as those versions of the platform
2887 * <p>Other additional default key handling may be performed
2888 * if configured with {@link #setDefaultKeyMode}.
2890 * @return Return <code>true</code> to prevent this event from being propagated
2891 * further, or <code>false</code> to indicate that you have not handled
2892 * this event and it should continue to be propagated.
2894 * @see android.view.KeyEvent
2896 public boolean onKeyDown(int keyCode, KeyEvent event) {
2897 if (keyCode == KeyEvent.KEYCODE_BACK) {
2898 if (getApplicationInfo().targetSdkVersion
2899 >= Build.VERSION_CODES.ECLAIR) {
2900 event.startTracking();
2907 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2909 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2910 Window w = getWindow();
2911 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2912 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2913 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2917 } else if (keyCode == KeyEvent.KEYCODE_TAB) {
2918 // Don't consume TAB here since it's used for navigation. Arrow keys
2919 // aren't considered "typing keys" so they already won't get consumed.
2922 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2923 boolean clearSpannable = false;
2925 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2926 clearSpannable = true;
2929 handled = TextKeyListener.getInstance().onKeyDown(
2930 null, mDefaultKeySsb, keyCode, event);
2931 if (handled && mDefaultKeySsb.length() > 0) {
2932 // something useable has been typed - dispatch it now.
2934 final String str = mDefaultKeySsb.toString();
2935 clearSpannable = true;
2937 switch (mDefaultKeyMode) {
2938 case DEFAULT_KEYS_DIALER:
2939 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2940 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2941 startActivity(intent);
2943 case DEFAULT_KEYS_SEARCH_LOCAL:
2944 startSearch(str, false, null, false);
2946 case DEFAULT_KEYS_SEARCH_GLOBAL:
2947 startSearch(str, false, null, true);
2952 if (clearSpannable) {
2953 mDefaultKeySsb.clear();
2954 mDefaultKeySsb.clearSpans();
2955 Selection.setSelection(mDefaultKeySsb,0);
2962 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2963 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2966 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2971 * Called when a key was released and not handled by any of the views
2972 * inside of the activity. So, for example, key presses while the cursor
2973 * is inside a TextView will not trigger the event (unless it is a navigation
2974 * to another object) because TextView handles its own key presses.
2976 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2979 * @return Return <code>true</code> to prevent this event from being propagated
2980 * further, or <code>false</code> to indicate that you have not handled
2981 * this event and it should continue to be propagated.
2985 public boolean onKeyUp(int keyCode, KeyEvent event) {
2986 if (getApplicationInfo().targetSdkVersion
2987 >= Build.VERSION_CODES.ECLAIR) {
2988 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2989 && !event.isCanceled()) {
2998 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
2999 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
3002 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3007 * Called when the activity has detected the user's press of the back
3008 * key. The default implementation simply finishes the current activity,
3009 * but you can override this to do whatever you want.
3011 public void onBackPressed() {
3012 if (mActionBar != null && mActionBar.collapseActionView()) {
3016 FragmentManager fragmentManager = mFragments.getFragmentManager();
3018 if (fragmentManager.isStateSaved() || !fragmentManager.popBackStackImmediate()) {
3019 finishAfterTransition();
3024 * Called when a key shortcut event is not handled by any of the views in the Activity.
3025 * Override this method to implement global key shortcuts for the Activity.
3026 * Key shortcuts can also be implemented by setting the
3027 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
3029 * @param keyCode The value in event.getKeyCode().
3030 * @param event Description of the key event.
3031 * @return True if the key shortcut was handled.
3033 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
3034 // Let the Action Bar have a chance at handling the shortcut.
3035 ActionBar actionBar = getActionBar();
3036 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
3040 * Called when a touch screen event was not handled by any of the views
3041 * under it. This is most useful to process touch events that happen
3042 * outside of your window bounds, where there is no view to receive it.
3044 * @param event The touch screen event being processed.
3046 * @return Return true if you have consumed the event, false if you haven't.
3047 * The default implementation always returns false.
3049 public boolean onTouchEvent(MotionEvent event) {
3050 if (mWindow.shouldCloseOnTouch(this, event)) {
3059 * Called when the trackball was moved and not handled by any of the
3060 * views inside of the activity. So, for example, if the trackball moves
3061 * while focus is on a button, you will receive a call here because
3062 * buttons do not normally do anything with trackball events. The call
3063 * here happens <em>before</em> trackball movements are converted to
3064 * DPAD key events, which then get sent back to the view hierarchy, and
3065 * will be processed at the point for things like focus navigation.
3067 * @param event The trackball event being processed.
3069 * @return Return true if you have consumed the event, false if you haven't.
3070 * The default implementation always returns false.
3072 public boolean onTrackballEvent(MotionEvent event) {
3077 * Called when a generic motion event was not handled by any of the
3078 * views inside of the activity.
3080 * Generic motion events describe joystick movements, mouse hovers, track pad
3081 * touches, scroll wheel movements and other input events. The
3082 * {@link MotionEvent#getSource() source} of the motion event specifies
3083 * the class of input that was received. Implementations of this method
3084 * must examine the bits in the source before processing the event.
3085 * The following code example shows how this is done.
3087 * Generic motion events with source class
3088 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
3089 * are delivered to the view under the pointer. All other generic motion events are
3090 * delivered to the focused view.
3092 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
3093 * handle this event.
3096 * @param event The generic motion event being processed.
3098 * @return Return true if you have consumed the event, false if you haven't.
3099 * The default implementation always returns false.
3101 public boolean onGenericMotionEvent(MotionEvent event) {
3106 * Called whenever a key, touch, or trackball event is dispatched to the
3107 * activity. Implement this method if you wish to know that the user has
3108 * interacted with the device in some way while your activity is running.
3109 * This callback and {@link #onUserLeaveHint} are intended to help
3110 * activities manage status bar notifications intelligently; specifically,
3111 * for helping activities determine the proper time to cancel a notfication.
3113 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
3114 * be accompanied by calls to {@link #onUserInteraction}. This
3115 * ensures that your activity will be told of relevant user activity such
3116 * as pulling down the notification pane and touching an item there.
3118 * <p>Note that this callback will be invoked for the touch down action
3119 * that begins a touch gesture, but may not be invoked for the touch-moved
3120 * and touch-up actions that follow.
3122 * @see #onUserLeaveHint()
3124 public void onUserInteraction() {
3127 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
3128 // Update window manager if: we have a view, that view is
3129 // attached to its parent (which will be a RootView), and
3130 // this activity is not embedded.
3131 if (mParent == null) {
3132 View decor = mDecor;
3133 if (decor != null && decor.getParent() != null) {
3134 getWindowManager().updateViewLayout(decor, params);
3139 public void onContentChanged() {
3143 * Called when the current {@link Window} of the activity gains or loses
3144 * focus. This is the best indicator of whether this activity is visible
3145 * to the user. The default implementation clears the key tracking
3146 * state, so should always be called.
3148 * <p>Note that this provides information about global focus state, which
3149 * is managed independently of activity lifecycles. As such, while focus
3150 * changes will generally have some relation to lifecycle changes (an
3151 * activity that is stopped will not generally get window focus), you
3152 * should not rely on any particular order between the callbacks here and
3153 * those in the other lifecycle methods such as {@link #onResume}.
3155 * <p>As a general rule, however, a resumed activity will have window
3156 * focus... unless it has displayed other dialogs or popups that take
3157 * input focus, in which case the activity itself will not have focus
3158 * when the other windows have it. Likewise, the system may display
3159 * system-level windows (such as the status bar notification panel or
3160 * a system alert) which will temporarily take window input focus without
3161 * pausing the foreground activity.
3163 * @param hasFocus Whether the window of this activity has focus.
3165 * @see #hasWindowFocus()
3167 * @see View#onWindowFocusChanged(boolean)
3169 public void onWindowFocusChanged(boolean hasFocus) {
3173 * Called when the main window associated with the activity has been
3174 * attached to the window manager.
3175 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
3176 * for more information.
3177 * @see View#onAttachedToWindow
3179 public void onAttachedToWindow() {
3183 * Called when the main window associated with the activity has been
3184 * detached from the window manager.
3185 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
3186 * for more information.
3187 * @see View#onDetachedFromWindow
3189 public void onDetachedFromWindow() {
3193 * Returns true if this activity's <em>main</em> window currently has window focus.
3194 * Note that this is not the same as the view itself having focus.
3196 * @return True if this activity's main window currently has window focus.
3198 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
3200 public boolean hasWindowFocus() {
3201 Window w = getWindow();
3203 View d = w.getDecorView();
3205 return d.hasWindowFocus();
3212 * Called when the main window associated with the activity has been dismissed.
3216 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
3217 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
3218 if (suppressWindowTransition) {
3219 overridePendingTransition(0, 0);
3225 * Moves the activity from
3226 * {@link android.app.ActivityManager.StackId#FREEFORM_WORKSPACE_STACK_ID} to
3227 * {@link android.app.ActivityManager.StackId#FULLSCREEN_WORKSPACE_STACK_ID} stack.
3232 public void exitFreeformMode() throws RemoteException {
3233 ActivityManager.getService().exitFreeformMode(mToken);
3236 /** Returns the current stack Id for the window.
3240 public int getWindowStackId() throws RemoteException {
3241 return ActivityManager.getService().getActivityStackId(mToken);
3245 * Puts the activity in picture-in-picture mode if the activity supports.
3246 * @see android.R.attr#supportsPictureInPicture
3250 public void enterPictureInPictureModeIfPossible() {
3251 if (mActivityInfo.supportsPictureInPicture()) {
3252 enterPictureInPictureMode();
3257 * Called to process key events. You can override this to intercept all
3258 * key events before they are dispatched to the window. Be sure to call
3259 * this implementation for key events that should be handled normally.
3261 * @param event The key event.
3263 * @return boolean Return true if this event was consumed.
3265 public boolean dispatchKeyEvent(KeyEvent event) {
3266 onUserInteraction();
3268 // Let action bars open menus in response to the menu key prioritized over
3269 // the window handling it
3270 final int keyCode = event.getKeyCode();
3271 if (keyCode == KeyEvent.KEYCODE_MENU &&
3272 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
3276 Window win = getWindow();
3277 if (win.superDispatchKeyEvent(event)) {
3280 View decor = mDecor;
3281 if (decor == null) decor = win.getDecorView();
3282 return event.dispatch(this, decor != null
3283 ? decor.getKeyDispatcherState() : null, this);
3287 * Called to process a key shortcut event.
3288 * You can override this to intercept all key shortcut events before they are
3289 * dispatched to the window. Be sure to call this implementation for key shortcut
3290 * events that should be handled normally.
3292 * @param event The key shortcut event.
3293 * @return True if this event was consumed.
3295 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3296 onUserInteraction();
3297 if (getWindow().superDispatchKeyShortcutEvent(event)) {
3300 return onKeyShortcut(event.getKeyCode(), event);
3304 * Called to process touch screen events. You can override this to
3305 * intercept all touch screen events before they are dispatched to the
3306 * window. Be sure to call this implementation for touch screen events
3307 * that should be handled normally.
3309 * @param ev The touch screen event.
3311 * @return boolean Return true if this event was consumed.
3313 public boolean dispatchTouchEvent(MotionEvent ev) {
3314 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
3315 onUserInteraction();
3317 if (getWindow().superDispatchTouchEvent(ev)) {
3320 return onTouchEvent(ev);
3324 * Called to process trackball events. You can override this to
3325 * intercept all trackball events before they are dispatched to the
3326 * window. Be sure to call this implementation for trackball events
3327 * that should be handled normally.
3329 * @param ev The trackball event.
3331 * @return boolean Return true if this event was consumed.
3333 public boolean dispatchTrackballEvent(MotionEvent ev) {
3334 onUserInteraction();
3335 if (getWindow().superDispatchTrackballEvent(ev)) {
3338 return onTrackballEvent(ev);
3342 * Called to process generic motion events. You can override this to
3343 * intercept all generic motion events before they are dispatched to the
3344 * window. Be sure to call this implementation for generic motion events
3345 * that should be handled normally.
3347 * @param ev The generic motion event.
3349 * @return boolean Return true if this event was consumed.
3351 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3352 onUserInteraction();
3353 if (getWindow().superDispatchGenericMotionEvent(ev)) {
3356 return onGenericMotionEvent(ev);
3359 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3360 event.setClassName(getClass().getName());
3361 event.setPackageName(getPackageName());
3363 LayoutParams params = getWindow().getAttributes();
3364 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
3365 (params.height == LayoutParams.MATCH_PARENT);
3366 event.setFullScreen(isFullScreen);
3368 CharSequence title = getTitle();
3369 if (!TextUtils.isEmpty(title)) {
3370 event.getText().add(title);
3377 * Default implementation of
3378 * {@link android.view.Window.Callback#onCreatePanelView}
3379 * for activities. This
3380 * simply returns null so that all panel sub-windows will have the default
3384 public View onCreatePanelView(int featureId) {
3389 * Default implementation of
3390 * {@link android.view.Window.Callback#onCreatePanelMenu}
3391 * for activities. This calls through to the new
3392 * {@link #onCreateOptionsMenu} method for the
3393 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3394 * so that subclasses of Activity don't need to deal with feature codes.
3396 public boolean onCreatePanelMenu(int featureId, Menu menu) {
3397 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
3398 boolean show = onCreateOptionsMenu(menu);
3399 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
3406 * Default implementation of
3407 * {@link android.view.Window.Callback#onPreparePanel}
3408 * for activities. This
3409 * calls through to the new {@link #onPrepareOptionsMenu} method for the
3410 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3411 * panel, so that subclasses of
3412 * Activity don't need to deal with feature codes.
3414 public boolean onPreparePanel(int featureId, View view, Menu menu) {
3415 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
3416 boolean goforit = onPrepareOptionsMenu(menu);
3417 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
3426 * @return The default implementation returns true.
3428 public boolean onMenuOpened(int featureId, Menu menu) {
3429 if (featureId == Window.FEATURE_ACTION_BAR) {
3430 initWindowDecorActionBar();
3431 if (mActionBar != null) {
3432 mActionBar.dispatchMenuVisibilityChanged(true);
3434 Log.e(TAG, "Tried to open action bar menu with no action bar");
3441 * Default implementation of
3442 * {@link android.view.Window.Callback#onMenuItemSelected}
3443 * for activities. This calls through to the new
3444 * {@link #onOptionsItemSelected} method for the
3445 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3446 * panel, so that subclasses of
3447 * Activity don't need to deal with feature codes.
3449 public boolean onMenuItemSelected(int featureId, MenuItem item) {
3450 CharSequence titleCondensed = item.getTitleCondensed();
3452 switch (featureId) {
3453 case Window.FEATURE_OPTIONS_PANEL:
3454 // Put event logging here so it gets called even if subclass
3455 // doesn't call through to superclass's implmeentation of each
3456 // of these methods below
3457 if(titleCondensed != null) {
3458 EventLog.writeEvent(50000, 0, titleCondensed.toString());
3460 if (onOptionsItemSelected(item)) {
3463 if (mFragments.dispatchOptionsItemSelected(item)) {
3466 if (item.getItemId() == android.R.id.home && mActionBar != null &&
3467 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
3468 if (mParent == null) {
3469 return onNavigateUp();
3471 return mParent.onNavigateUpFromChild(this);
3476 case Window.FEATURE_CONTEXT_MENU:
3477 if(titleCondensed != null) {
3478 EventLog.writeEvent(50000, 1, titleCondensed.toString());
3480 if (onContextItemSelected(item)) {
3483 return mFragments.dispatchContextItemSelected(item);
3491 * Default implementation of
3492 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
3493 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
3494 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3495 * so that subclasses of Activity don't need to deal with feature codes.
3496 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
3497 * {@link #onContextMenuClosed(Menu)} will be called.
3499 public void onPanelClosed(int featureId, Menu menu) {
3500 switch (featureId) {
3501 case Window.FEATURE_OPTIONS_PANEL:
3502 mFragments.dispatchOptionsMenuClosed(menu);
3503 onOptionsMenuClosed(menu);
3506 case Window.FEATURE_CONTEXT_MENU:
3507 onContextMenuClosed(menu);
3510 case Window.FEATURE_ACTION_BAR:
3511 initWindowDecorActionBar();
3512 mActionBar.dispatchMenuVisibilityChanged(false);
3518 * Declare that the options menu has changed, so should be recreated.
3519 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
3520 * time it needs to be displayed.
3522 public void invalidateOptionsMenu() {
3523 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3524 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
3525 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
3530 * Initialize the contents of the Activity's standard options menu. You
3531 * should place your menu items in to <var>menu</var>.
3533 * <p>This is only called once, the first time the options menu is
3534 * displayed. To update the menu every time it is displayed, see
3535 * {@link #onPrepareOptionsMenu}.
3537 * <p>The default implementation populates the menu with standard system
3538 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
3539 * they will be correctly ordered with application-defined menu items.
3540 * Deriving classes should always call through to the base implementation.
3542 * <p>You can safely hold on to <var>menu</var> (and any items created
3543 * from it), making modifications to it as desired, until the next
3544 * time onCreateOptionsMenu() is called.
3546 * <p>When you add items to the menu, you can implement the Activity's
3547 * {@link #onOptionsItemSelected} method to handle them there.
3549 * @param menu The options menu in which you place your items.
3551 * @return You must return true for the menu to be displayed;
3552 * if you return false it will not be shown.
3554 * @see #onPrepareOptionsMenu
3555 * @see #onOptionsItemSelected
3557 public boolean onCreateOptionsMenu(Menu menu) {
3558 if (mParent != null) {
3559 return mParent.onCreateOptionsMenu(menu);
3565 * Prepare the Screen's standard options menu to be displayed. This is
3566 * called right before the menu is shown, every time it is shown. You can
3567 * use this method to efficiently enable/disable items or otherwise
3568 * dynamically modify the contents.
3570 * <p>The default implementation updates the system menu items based on the
3571 * activity's state. Deriving classes should always call through to the
3572 * base class implementation.
3574 * @param menu The options menu as last shown or first initialized by
3575 * onCreateOptionsMenu().
3577 * @return You must return true for the menu to be displayed;
3578 * if you return false it will not be shown.
3580 * @see #onCreateOptionsMenu
3582 public boolean onPrepareOptionsMenu(Menu menu) {
3583 if (mParent != null) {
3584 return mParent.onPrepareOptionsMenu(menu);
3590 * This hook is called whenever an item in your options menu is selected.
3591 * The default implementation simply returns false to have the normal
3592 * processing happen (calling the item's Runnable or sending a message to
3593 * its Handler as appropriate). You can use this method for any items
3594 * for which you would like to do processing without those other
3597 * <p>Derived classes should call through to the base class for it to
3598 * perform the default menu handling.</p>
3600 * @param item The menu item that was selected.
3602 * @return boolean Return false to allow normal menu processing to
3603 * proceed, true to consume it here.
3605 * @see #onCreateOptionsMenu
3607 public boolean onOptionsItemSelected(MenuItem item) {
3608 if (mParent != null) {
3609 return mParent.onOptionsItemSelected(item);
3615 * This method is called whenever the user chooses to navigate Up within your application's
3616 * activity hierarchy from the action bar.
3618 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3619 * was specified in the manifest for this activity or an activity-alias to it,
3620 * default Up navigation will be handled automatically. If any activity
3621 * along the parent chain requires extra Intent arguments, the Activity subclass
3622 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3623 * to supply those arguments.</p>
3625 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
3626 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3627 * from the design guide for more information about navigating within your app.</p>
3629 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3630 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3631 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3632 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3634 * @return true if Up navigation completed successfully and this Activity was finished,
3637 public boolean onNavigateUp() {
3638 // Automatically handle hierarchical Up navigation if the proper
3639 // metadata is available.
3640 Intent upIntent = getParentActivityIntent();
3641 if (upIntent != null) {
3642 if (mActivityInfo.taskAffinity == null) {
3643 // Activities with a null affinity are special; they really shouldn't
3644 // specify a parent activity intent in the first place. Just finish
3645 // the current activity and call it a day.
3647 } else if (shouldUpRecreateTask(upIntent)) {
3648 TaskStackBuilder b = TaskStackBuilder.create(this);
3649 onCreateNavigateUpTaskStack(b);
3650 onPrepareNavigateUpTaskStack(b);
3651 b.startActivities();
3653 // We can't finishAffinity if we have a result.
3654 // Fall back and simply finish the current activity instead.
3655 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3656 // Tell the developer what's going on to avoid hair-pulling.
3657 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3663 navigateUpTo(upIntent);
3671 * This is called when a child activity of this one attempts to navigate up.
3672 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3674 * @param child The activity making the call.
3676 public boolean onNavigateUpFromChild(Activity child) {
3677 return onNavigateUp();
3681 * Define the synthetic task stack that will be generated during Up navigation from
3684 * <p>The default implementation of this method adds the parent chain of this activity
3685 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3686 * may choose to override this method to construct the desired task stack in a different
3689 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3690 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3691 * returned by {@link #getParentActivityIntent()}.</p>
3693 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3694 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3696 * @param builder An empty TaskStackBuilder - the application should add intents representing
3697 * the desired task stack
3699 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3700 builder.addParentStack(this);
3704 * Prepare the synthetic task stack that will be generated during Up navigation
3705 * from a different task.
3707 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3708 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3709 * If any extra data should be added to these intents before launching the new task,
3710 * the application should override this method and add that data here.</p>
3712 * @param builder A TaskStackBuilder that has been populated with Intents by
3713 * onCreateNavigateUpTaskStack.
3715 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3719 * This hook is called whenever the options menu is being closed (either by the user canceling
3720 * the menu with the back/menu button, or when an item is selected).
3722 * @param menu The options menu as last shown or first initialized by
3723 * onCreateOptionsMenu().
3725 public void onOptionsMenuClosed(Menu menu) {
3726 if (mParent != null) {
3727 mParent.onOptionsMenuClosed(menu);
3732 * Programmatically opens the options menu. If the options menu is already
3733 * open, this method does nothing.
3735 public void openOptionsMenu() {
3736 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3737 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3738 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3743 * Progammatically closes the options menu. If the options menu is already
3744 * closed, this method does nothing.
3746 public void closeOptionsMenu() {
3747 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3748 (mActionBar == null || !mActionBar.closeOptionsMenu())) {
3749 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3754 * Called when a context menu for the {@code view} is about to be shown.
3755 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3756 * time the context menu is about to be shown and should be populated for
3757 * the view (or item inside the view for {@link AdapterView} subclasses,
3758 * this can be found in the {@code menuInfo})).
3760 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3761 * item has been selected.
3763 * It is not safe to hold onto the context menu after this method returns.
3766 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3770 * Registers a context menu to be shown for the given view (multiple views
3771 * can show the context menu). This method will set the
3772 * {@link OnCreateContextMenuListener} on the view to this activity, so
3773 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3774 * called when it is time to show the context menu.
3776 * @see #unregisterForContextMenu(View)
3777 * @param view The view that should show a context menu.
3779 public void registerForContextMenu(View view) {
3780 view.setOnCreateContextMenuListener(this);
3784 * Prevents a context menu to be shown for the given view. This method will remove the
3785 * {@link OnCreateContextMenuListener} on the view.
3787 * @see #registerForContextMenu(View)
3788 * @param view The view that should stop showing a context menu.
3790 public void unregisterForContextMenu(View view) {
3791 view.setOnCreateContextMenuListener(null);
3795 * Programmatically opens the context menu for a particular {@code view}.
3796 * The {@code view} should have been added via
3797 * {@link #registerForContextMenu(View)}.
3799 * @param view The view to show the context menu for.
3801 public void openContextMenu(View view) {
3802 view.showContextMenu();
3806 * Programmatically closes the most recently opened context menu, if showing.
3808 public void closeContextMenu() {
3809 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3810 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3815 * This hook is called whenever an item in a context menu is selected. The
3816 * default implementation simply returns false to have the normal processing
3817 * happen (calling the item's Runnable or sending a message to its Handler
3818 * as appropriate). You can use this method for any items for which you
3819 * would like to do processing without those other facilities.
3821 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3822 * View that added this menu item.
3824 * Derived classes should call through to the base class for it to perform
3825 * the default menu handling.
3827 * @param item The context menu item that was selected.
3828 * @return boolean Return false to allow normal context menu processing to
3829 * proceed, true to consume it here.
3831 public boolean onContextItemSelected(MenuItem item) {
3832 if (mParent != null) {
3833 return mParent.onContextItemSelected(item);
3839 * This hook is called whenever the context menu is being closed (either by
3840 * the user canceling the menu with the back/menu button, or when an item is
3843 * @param menu The context menu that is being closed.
3845 public void onContextMenuClosed(Menu menu) {
3846 if (mParent != null) {
3847 mParent.onContextMenuClosed(menu);
3852 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3855 protected Dialog onCreateDialog(int id) {
3860 * Callback for creating dialogs that are managed (saved and restored) for you
3861 * by the activity. The default implementation calls through to
3862 * {@link #onCreateDialog(int)} for compatibility.
3864 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3865 * or later, consider instead using a {@link DialogFragment} instead.</em>
3867 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3868 * this method the first time, and hang onto it thereafter. Any dialog
3869 * that is created by this method will automatically be saved and restored
3870 * for you, including whether it is showing.
3872 * <p>If you would like the activity to manage saving and restoring dialogs
3873 * for you, you should override this method and handle any ids that are
3874 * passed to {@link #showDialog}.
3876 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3877 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3879 * @param id The id of the dialog.
3880 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3881 * @return The dialog. If you return null, the dialog will not be created.
3883 * @see #onPrepareDialog(int, Dialog, Bundle)
3884 * @see #showDialog(int, Bundle)
3885 * @see #dismissDialog(int)
3886 * @see #removeDialog(int)
3888 * @deprecated Use the new {@link DialogFragment} class with
3889 * {@link FragmentManager} instead; this is also
3890 * available on older platforms through the Android compatibility package.
3894 protected Dialog onCreateDialog(int id, Bundle args) {
3895 return onCreateDialog(id);
3899 * @deprecated Old no-arguments version of
3900 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3903 protected void onPrepareDialog(int id, Dialog dialog) {
3904 dialog.setOwnerActivity(this);
3908 * Provides an opportunity to prepare a managed dialog before it is being
3909 * shown. The default implementation calls through to
3910 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3913 * Override this if you need to update a managed dialog based on the state
3914 * of the application each time it is shown. For example, a time picker
3915 * dialog might want to be updated with the current time. You should call
3916 * through to the superclass's implementation. The default implementation
3917 * will set this Activity as the owner activity on the Dialog.
3919 * @param id The id of the managed dialog.
3920 * @param dialog The dialog.
3921 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3922 * @see #onCreateDialog(int, Bundle)
3923 * @see #showDialog(int)
3924 * @see #dismissDialog(int)
3925 * @see #removeDialog(int)
3927 * @deprecated Use the new {@link DialogFragment} class with
3928 * {@link FragmentManager} instead; this is also
3929 * available on older platforms through the Android compatibility package.
3932 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3933 onPrepareDialog(id, dialog);
3937 * Simple version of {@link #showDialog(int, Bundle)} that does not
3938 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3939 * with null arguments.
3941 * @deprecated Use the new {@link DialogFragment} class with
3942 * {@link FragmentManager} instead; this is also
3943 * available on older platforms through the Android compatibility package.
3946 public final void showDialog(int id) {
3947 showDialog(id, null);
3951 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3952 * will be made with the same id the first time this is called for a given
3953 * id. From thereafter, the dialog will be automatically saved and restored.
3955 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3956 * or later, consider instead using a {@link DialogFragment} instead.</em>
3958 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3959 * be made to provide an opportunity to do any timely preparation.
3961 * @param id The id of the managed dialog.
3962 * @param args Arguments to pass through to the dialog. These will be saved
3963 * and restored for you. Note that if the dialog is already created,
3964 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3965 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3966 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3967 * @return Returns true if the Dialog was created; false is returned if
3968 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3971 * @see #onCreateDialog(int, Bundle)
3972 * @see #onPrepareDialog(int, Dialog, Bundle)
3973 * @see #dismissDialog(int)
3974 * @see #removeDialog(int)
3976 * @deprecated Use the new {@link DialogFragment} class with
3977 * {@link FragmentManager} instead; this is also
3978 * available on older platforms through the Android compatibility package.
3981 public final boolean showDialog(int id, Bundle args) {
3982 if (mManagedDialogs == null) {
3983 mManagedDialogs = new SparseArray<ManagedDialog>();
3985 ManagedDialog md = mManagedDialogs.get(id);
3987 md = new ManagedDialog();
3988 md.mDialog = createDialog(id, null, args);
3989 if (md.mDialog == null) {
3992 mManagedDialogs.put(id, md);
3996 onPrepareDialog(id, md.mDialog, args);
4002 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
4004 * @param id The id of the managed dialog.
4006 * @throws IllegalArgumentException if the id was not previously shown via
4007 * {@link #showDialog(int)}.
4009 * @see #onCreateDialog(int, Bundle)
4010 * @see #onPrepareDialog(int, Dialog, Bundle)
4011 * @see #showDialog(int)
4012 * @see #removeDialog(int)
4014 * @deprecated Use the new {@link DialogFragment} class with
4015 * {@link FragmentManager} instead; this is also
4016 * available on older platforms through the Android compatibility package.
4019 public final void dismissDialog(int id) {
4020 if (mManagedDialogs == null) {
4021 throw missingDialog(id);
4024 final ManagedDialog md = mManagedDialogs.get(id);
4026 throw missingDialog(id);
4028 md.mDialog.dismiss();
4032 * Creates an exception to throw if a user passed in a dialog id that is
4035 private IllegalArgumentException missingDialog(int id) {
4036 return new IllegalArgumentException("no dialog with id " + id + " was ever "
4037 + "shown via Activity#showDialog");
4041 * Removes any internal references to a dialog managed by this Activity.
4042 * If the dialog is showing, it will dismiss it as part of the clean up.
4044 * <p>This can be useful if you know that you will never show a dialog again and
4045 * want to avoid the overhead of saving and restoring it in the future.
4047 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
4048 * will not throw an exception if you try to remove an ID that does not
4049 * currently have an associated dialog.</p>
4051 * @param id The id of the managed dialog.
4053 * @see #onCreateDialog(int, Bundle)
4054 * @see #onPrepareDialog(int, Dialog, Bundle)
4055 * @see #showDialog(int)
4056 * @see #dismissDialog(int)
4058 * @deprecated Use the new {@link DialogFragment} class with
4059 * {@link FragmentManager} instead; this is also
4060 * available on older platforms through the Android compatibility package.
4063 public final void removeDialog(int id) {
4064 if (mManagedDialogs != null) {
4065 final ManagedDialog md = mManagedDialogs.get(id);
4067 md.mDialog.dismiss();
4068 mManagedDialogs.remove(id);
4074 * This hook is called when the user signals the desire to start a search.
4076 * <p>You can use this function as a simple way to launch the search UI, in response to a
4077 * menu item, search button, or other widgets within your activity. Unless overidden,
4078 * calling this function is the same as calling
4079 * {@link #startSearch startSearch(null, false, null, false)}, which launches
4080 * search for the current activity as specified in its manifest, see {@link SearchManager}.
4082 * <p>You can override this function to force global search, e.g. in response to a dedicated
4083 * search key, or to block search entirely (by simply returning false).
4085 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
4086 * implementation changes to simply return false and you must supply your own custom
4087 * implementation if you want to support search.</p>
4089 * @param searchEvent The {@link SearchEvent} that signaled this search.
4090 * @return Returns {@code true} if search launched, and {@code false} if the activity does
4091 * not respond to search. The default implementation always returns {@code true}, except
4092 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
4094 * @see android.app.SearchManager
4096 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
4097 mSearchEvent = searchEvent;
4098 boolean result = onSearchRequested();
4099 mSearchEvent = null;
4104 * @see #onSearchRequested(SearchEvent)
4106 public boolean onSearchRequested() {
4107 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
4108 != Configuration.UI_MODE_TYPE_TELEVISION) {
4109 startSearch(null, false, null, false);
4117 * During the onSearchRequested() callbacks, this function will return the
4118 * {@link SearchEvent} that triggered the callback, if it exists.
4120 * @return SearchEvent The SearchEvent that triggered the {@link
4121 * #onSearchRequested} callback.
4123 public final SearchEvent getSearchEvent() {
4124 return mSearchEvent;
4128 * This hook is called to launch the search UI.
4130 * <p>It is typically called from onSearchRequested(), either directly from
4131 * Activity.onSearchRequested() or from an overridden version in any given
4132 * Activity. If your goal is simply to activate search, it is preferred to call
4133 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
4134 * is to inject specific data such as context data, it is preferred to <i>override</i>
4135 * onSearchRequested(), so that any callers to it will benefit from the override.
4137 * @param initialQuery Any non-null non-empty string will be inserted as
4138 * pre-entered text in the search query box.
4139 * @param selectInitialQuery If true, the initial query will be preselected, which means that
4140 * any further typing will replace it. This is useful for cases where an entire pre-formed
4141 * query is being inserted. If false, the selection point will be placed at the end of the
4142 * inserted query. This is useful when the inserted query is text that the user entered,
4143 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
4144 * if initialQuery is a non-empty string.</i>
4145 * @param appSearchData An application can insert application-specific
4146 * context here, in order to improve quality or specificity of its own
4147 * searches. This data will be returned with SEARCH intent(s). Null if
4148 * no extra data is required.
4149 * @param globalSearch If false, this will only launch the search that has been specifically
4150 * defined by the application (which is usually defined as a local search). If no default
4151 * search is defined in the current application or activity, global search will be launched.
4152 * If true, this will always launch a platform-global (e.g. web-based) search instead.
4154 * @see android.app.SearchManager
4155 * @see #onSearchRequested
4157 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
4158 @Nullable Bundle appSearchData, boolean globalSearch) {
4159 ensureSearchManager();
4160 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
4161 appSearchData, globalSearch);
4165 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
4166 * the search dialog. Made available for testing purposes.
4168 * @param query The query to trigger. If empty, the request will be ignored.
4169 * @param appSearchData An application can insert application-specific
4170 * context here, in order to improve quality or specificity of its own
4171 * searches. This data will be returned with SEARCH intent(s). Null if
4172 * no extra data is required.
4174 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
4175 ensureSearchManager();
4176 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
4180 * Request that key events come to this activity. Use this if your
4181 * activity has no views with focus, but the activity still wants
4182 * a chance to process key events.
4184 * @see android.view.Window#takeKeyEvents
4186 public void takeKeyEvents(boolean get) {
4187 getWindow().takeKeyEvents(get);
4191 * Enable extended window features. This is a convenience for calling
4192 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
4194 * @param featureId The desired feature as defined in
4195 * {@link android.view.Window}.
4196 * @return Returns true if the requested feature is supported and now
4199 * @see android.view.Window#requestFeature
4201 public final boolean requestWindowFeature(int featureId) {
4202 return getWindow().requestFeature(featureId);
4206 * Convenience for calling
4207 * {@link android.view.Window#setFeatureDrawableResource}.
4209 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
4210 getWindow().setFeatureDrawableResource(featureId, resId);
4214 * Convenience for calling
4215 * {@link android.view.Window#setFeatureDrawableUri}.
4217 public final void setFeatureDrawableUri(int featureId, Uri uri) {
4218 getWindow().setFeatureDrawableUri(featureId, uri);
4222 * Convenience for calling
4223 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
4225 public final void setFeatureDrawable(int featureId, Drawable drawable) {
4226 getWindow().setFeatureDrawable(featureId, drawable);
4230 * Convenience for calling
4231 * {@link android.view.Window#setFeatureDrawableAlpha}.
4233 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
4234 getWindow().setFeatureDrawableAlpha(featureId, alpha);
4238 * Convenience for calling
4239 * {@link android.view.Window#getLayoutInflater}.
4242 public LayoutInflater getLayoutInflater() {
4243 return getWindow().getLayoutInflater();
4247 * Returns a {@link MenuInflater} with this context.
4250 public MenuInflater getMenuInflater() {
4251 // Make sure that action views can get an appropriate theme.
4252 if (mMenuInflater == null) {
4253 initWindowDecorActionBar();
4254 if (mActionBar != null) {
4255 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
4257 mMenuInflater = new MenuInflater(this);
4260 return mMenuInflater;
4264 public void setTheme(int resid) {
4265 super.setTheme(resid);
4266 mWindow.setTheme(resid);
4270 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
4272 if (mParent == null) {
4273 super.onApplyThemeResource(theme, resid, first);
4276 theme.setTo(mParent.getTheme());
4277 } catch (Exception e) {
4280 theme.applyStyle(resid, false);
4283 // Get the primary color and update the TaskDescription for this activity
4284 TypedArray a = theme.obtainStyledAttributes(
4285 com.android.internal.R.styleable.ActivityTaskDescription);
4286 if (mTaskDescription.getPrimaryColor() == 0) {
4287 int colorPrimary = a.getColor(
4288 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
4289 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
4290 mTaskDescription.setPrimaryColor(colorPrimary);
4294 int colorBackground = a.getColor(
4295 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
4296 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
4297 mTaskDescription.setBackgroundColor(colorBackground);
4300 final int statusBarColor = a.getColor(
4301 com.android.internal.R.styleable.ActivityTaskDescription_statusBarColor, 0);
4302 if (statusBarColor != 0) {
4303 mTaskDescription.setStatusBarColor(statusBarColor);
4306 final int navigationBarColor = a.getColor(
4307 com.android.internal.R.styleable.ActivityTaskDescription_navigationBarColor, 0);
4308 if (navigationBarColor != 0) {
4309 mTaskDescription.setNavigationBarColor(navigationBarColor);
4313 setTaskDescription(mTaskDescription);
4317 * Requests permissions to be granted to this application. These permissions
4318 * must be requested in your manifest, they should not be granted to your app,
4319 * and they should have protection level {@link android.content.pm.PermissionInfo
4320 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
4321 * the platform or a third-party app.
4323 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
4324 * are granted at install time if requested in the manifest. Signature permissions
4325 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
4326 * install time if requested in the manifest and the signature of your app matches
4327 * the signature of the app declaring the permissions.
4330 * If your app does not have the requested permissions the user will be presented
4331 * with UI for accepting them. After the user has accepted or rejected the
4332 * requested permissions you will receive a callback on {@link
4333 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
4334 * permissions were granted or not.
4337 * Note that requesting a permission does not guarantee it will be granted and
4338 * your app should be able to run without having this permission.
4341 * This method may start an activity allowing the user to choose which permissions
4342 * to grant and which to reject. Hence, you should be prepared that your activity
4343 * may be paused and resumed. Further, granting some permissions may require
4344 * a restart of you application. In such a case, the system will recreate the
4345 * activity stack before delivering the result to {@link
4346 * #onRequestPermissionsResult(int, String[], int[])}.
4349 * When checking whether you have a permission you should use {@link
4350 * #checkSelfPermission(String)}.
4353 * Calling this API for permissions already granted to your app would show UI
4354 * to the user to decide whether the app can still hold these permissions. This
4355 * can be useful if the way your app uses data guarded by the permissions
4356 * changes significantly.
4359 * You cannot request a permission if your activity sets {@link
4360 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
4361 * <code>true</code> because in this case the activity would not receive
4362 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
4365 * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html">
4366 * RuntimePermissions</a> sample app demonstrates how to use this method to
4367 * request permissions at run time.
4370 * @param permissions The requested permissions. Must me non-null and not empty.
4371 * @param requestCode Application specific request code to match with a result
4372 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
4375 * @throws IllegalArgumentException if requestCode is negative.
4377 * @see #onRequestPermissionsResult(int, String[], int[])
4378 * @see #checkSelfPermission(String)
4379 * @see #shouldShowRequestPermissionRationale(String)
4381 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
4382 if (requestCode < 0) {
4383 throw new IllegalArgumentException("requestCode should be >= 0");
4385 if (mHasCurrentPermissionsRequest) {
4386 Log.w(TAG, "Can reqeust only one set of permissions at a time");
4387 // Dispatch the callback with empty arrays which means a cancellation.
4388 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
4391 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
4392 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
4393 mHasCurrentPermissionsRequest = true;
4397 * Callback for the result from requesting permissions. This method
4398 * is invoked for every call on {@link #requestPermissions(String[], int)}.
4400 * <strong>Note:</strong> It is possible that the permissions request interaction
4401 * with the user is interrupted. In this case you will receive empty permissions
4402 * and results arrays which should be treated as a cancellation.
4405 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
4406 * @param permissions The requested permissions. Never null.
4407 * @param grantResults The grant results for the corresponding permissions
4408 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
4409 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
4411 * @see #requestPermissions(String[], int)
4413 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
4414 @NonNull int[] grantResults) {
4415 /* callback - no nothing */
4419 * Gets whether you should show UI with rationale for requesting a permission.
4420 * You should do this only if you do not have the permission and the context in
4421 * which the permission is requested does not clearly communicate to the user
4422 * what would be the benefit from granting this permission.
4424 * For example, if you write a camera app, requesting the camera permission
4425 * would be expected by the user and no rationale for why it is requested is
4426 * needed. If however, the app needs location for tagging photos then a non-tech
4427 * savvy user may wonder how location is related to taking photos. In this case
4428 * you may choose to show UI with rationale of requesting this permission.
4431 * @param permission A permission your app wants to request.
4432 * @return Whether you can show permission rationale UI.
4434 * @see #checkSelfPermission(String)
4435 * @see #requestPermissions(String[], int)
4436 * @see #onRequestPermissionsResult(int, String[], int[])
4438 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
4439 return getPackageManager().shouldShowRequestPermissionRationale(permission);
4443 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
4446 * @param intent The intent to start.
4447 * @param requestCode If >= 0, this code will be returned in
4448 * onActivityResult() when the activity exits.
4450 * @throws android.content.ActivityNotFoundException
4452 * @see #startActivity
4454 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
4455 startActivityForResult(intent, requestCode, null);
4459 * Launch an activity for which you would like a result when it finished.
4460 * When this activity exits, your
4461 * onActivityResult() method will be called with the given requestCode.
4462 * Using a negative requestCode is the same as calling
4463 * {@link #startActivity} (the activity is not launched as a sub-activity).
4465 * <p>Note that this method should only be used with Intent protocols
4466 * that are defined to return a result. In other protocols (such as
4467 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
4468 * not get the result when you expect. For example, if the activity you
4469 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
4470 * run in your task and thus you will immediately receive a cancel result.
4472 * <p>As a special case, if you call startActivityForResult() with a requestCode
4473 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
4474 * activity, then your window will not be displayed until a result is
4475 * returned back from the started activity. This is to avoid visible
4476 * flickering when redirecting to another activity.
4478 * <p>This method throws {@link android.content.ActivityNotFoundException}
4479 * if there was no Activity found to run the given Intent.
4481 * @param intent The intent to start.
4482 * @param requestCode If >= 0, this code will be returned in
4483 * onActivityResult() when the activity exits.
4484 * @param options Additional options for how the Activity should be started.
4485 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4486 * Context.startActivity(Intent, Bundle)} for more details.
4488 * @throws android.content.ActivityNotFoundException
4490 * @see #startActivity
4492 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
4493 @Nullable Bundle options) {
4494 if (mParent == null) {
4495 options = transferSpringboardActivityOptions(options);
4496 Instrumentation.ActivityResult ar =
4497 mInstrumentation.execStartActivity(
4498 this, mMainThread.getApplicationThread(), mToken, this,
4499 intent, requestCode, options);
4501 mMainThread.sendActivityResult(
4502 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4503 ar.getResultData());
4505 if (requestCode >= 0) {
4506 // If this start is requesting a result, we can avoid making
4507 // the activity visible until the result is received. Setting
4508 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4509 // activity hidden during this time, to avoid flickering.
4510 // This can only be done when a result is requested because
4511 // that guarantees we will get information back when the
4512 // activity is finished, no matter what happens to it.
4513 mStartedActivity = true;
4516 cancelInputsAndStartExitTransition(options);
4517 // TODO Consider clearing/flushing other event sources and events for child windows.
4519 if (options != null) {
4520 mParent.startActivityFromChild(this, intent, requestCode, options);
4522 // Note we want to go through this method for compatibility with
4523 // existing applications that may have overridden it.
4524 mParent.startActivityFromChild(this, intent, requestCode);
4530 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
4532 * @param options The ActivityOptions bundle used to start an Activity.
4534 private void cancelInputsAndStartExitTransition(Bundle options) {
4535 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
4536 if (decor != null) {
4537 decor.cancelPendingInputEvents();
4539 if (options != null && !isTopOfTask()) {
4540 mActivityTransitionState.startExitOutTransition(this, options);
4545 * Returns whether there are any activity transitions currently running on this
4546 * activity. A return value of {@code true} can mean that either an enter or
4547 * exit transition is running, including whether the background of the activity
4548 * is animating as a part of that transition.
4550 * @return true if a transition is currently running on this activity, false otherwise.
4552 public boolean isActivityTransitionRunning() {
4553 return mActivityTransitionState.isTransitionRunning();
4556 private Bundle transferSpringboardActivityOptions(Bundle options) {
4557 if (options == null && (mWindow != null && !mWindow.isActive())) {
4558 final ActivityOptions activityOptions = getActivityOptions();
4559 if (activityOptions != null &&
4560 activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
4561 return activityOptions.toBundle();
4568 * @hide Implement to provide correct calling token.
4570 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
4571 startActivityForResultAsUser(intent, requestCode, null, user);
4575 * @hide Implement to provide correct calling token.
4577 public void startActivityForResultAsUser(Intent intent, int requestCode,
4578 @Nullable Bundle options, UserHandle user) {
4579 startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
4583 * @hide Implement to provide correct calling token.
4585 public void startActivityForResultAsUser(Intent intent, String resultWho, int requestCode,
4586 @Nullable Bundle options, UserHandle user) {
4587 if (mParent != null) {
4588 throw new RuntimeException("Can't be called from a child");
4590 options = transferSpringboardActivityOptions(options);
4591 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4592 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
4595 mMainThread.sendActivityResult(
4596 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4598 if (requestCode >= 0) {
4599 // If this start is requesting a result, we can avoid making
4600 // the activity visible until the result is received. Setting
4601 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4602 // activity hidden during this time, to avoid flickering.
4603 // This can only be done when a result is requested because
4604 // that guarantees we will get information back when the
4605 // activity is finished, no matter what happens to it.
4606 mStartedActivity = true;
4609 cancelInputsAndStartExitTransition(options);
4613 * @hide Implement to provide correct calling token.
4615 public void startActivityAsUser(Intent intent, UserHandle user) {
4616 startActivityAsUser(intent, null, user);
4620 * @hide Implement to provide correct calling token.
4622 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4623 if (mParent != null) {
4624 throw new RuntimeException("Can't be called from a child");
4626 options = transferSpringboardActivityOptions(options);
4627 Instrumentation.ActivityResult ar =
4628 mInstrumentation.execStartActivity(
4629 this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
4630 intent, -1, options, user);
4632 mMainThread.sendActivityResult(
4633 mToken, mEmbeddedID, -1, ar.getResultCode(),
4634 ar.getResultData());
4636 cancelInputsAndStartExitTransition(options);
4640 * Start a new activity as if it was started by the activity that started our
4641 * current activity. This is for the resolver and chooser activities, which operate
4642 * as intermediaries that dispatch their intent to the target the user selects -- to
4643 * do this, they must perform all security checks including permission grants as if
4644 * their launch had come from the original activity.
4645 * @param intent The Intent to start.
4646 * @param options ActivityOptions or null.
4647 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4648 * caller it is doing the start is, is actually allowed to start the target activity.
4649 * If you set this to true, you must set an explicit component in the Intent and do any
4650 * appropriate security checks yourself.
4651 * @param userId The user the new activity should run as.
4654 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4655 boolean ignoreTargetSecurity, int userId) {
4656 if (mParent != null) {
4657 throw new RuntimeException("Can't be called from a child");
4659 options = transferSpringboardActivityOptions(options);
4660 Instrumentation.ActivityResult ar =
4661 mInstrumentation.execStartActivityAsCaller(
4662 this, mMainThread.getApplicationThread(), mToken, this,
4663 intent, -1, options, ignoreTargetSecurity, userId);
4665 mMainThread.sendActivityResult(
4666 mToken, mEmbeddedID, -1, ar.getResultCode(),
4667 ar.getResultData());
4669 cancelInputsAndStartExitTransition(options);
4673 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4674 * Intent, int, int, int, Bundle)} with no options.
4676 * @param intent The IntentSender to launch.
4677 * @param requestCode If >= 0, this code will be returned in
4678 * onActivityResult() when the activity exits.
4679 * @param fillInIntent If non-null, this will be provided as the
4680 * intent parameter to {@link IntentSender#sendIntent}.
4681 * @param flagsMask Intent flags in the original IntentSender that you
4682 * would like to change.
4683 * @param flagsValues Desired values for any bits set in
4684 * <var>flagsMask</var>
4685 * @param extraFlags Always set to 0.
4687 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4688 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4689 throws IntentSender.SendIntentException {
4690 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4691 flagsValues, extraFlags, null);
4695 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4696 * to use a IntentSender to describe the activity to be started. If
4697 * the IntentSender is for an activity, that activity will be started
4698 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4699 * here; otherwise, its associated action will be executed (such as
4700 * sending a broadcast) as if you had called
4701 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4703 * @param intent The IntentSender to launch.
4704 * @param requestCode If >= 0, this code will be returned in
4705 * onActivityResult() when the activity exits.
4706 * @param fillInIntent If non-null, this will be provided as the
4707 * intent parameter to {@link IntentSender#sendIntent}.
4708 * @param flagsMask Intent flags in the original IntentSender that you
4709 * would like to change.
4710 * @param flagsValues Desired values for any bits set in
4711 * <var>flagsMask</var>
4712 * @param extraFlags Always set to 0.
4713 * @param options Additional options for how the Activity should be started.
4714 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4715 * Context.startActivity(Intent, Bundle)} for more details. If options
4716 * have also been supplied by the IntentSender, options given here will
4717 * override any that conflict with those given by the IntentSender.
4719 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4720 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4721 Bundle options) throws IntentSender.SendIntentException {
4722 if (mParent == null) {
4723 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
4724 flagsMask, flagsValues, options);
4725 } else if (options != null) {
4726 mParent.startIntentSenderFromChild(this, intent, requestCode,
4727 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4729 // Note we want to go through this call for compatibility with
4730 // existing applications that may have overridden the method.
4731 mParent.startIntentSenderFromChild(this, intent, requestCode,
4732 fillInIntent, flagsMask, flagsValues, extraFlags);
4736 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
4737 Intent fillInIntent, int flagsMask, int flagsValues,
4739 throws IntentSender.SendIntentException {
4741 String resolvedType = null;
4742 if (fillInIntent != null) {
4743 fillInIntent.migrateExtraStreamToClipData();
4744 fillInIntent.prepareToLeaveProcess(this);
4745 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4747 int result = ActivityManager.getService()
4748 .startActivityIntentSender(mMainThread.getApplicationThread(),
4749 intent != null ? intent.getTarget() : null,
4750 intent != null ? intent.getWhitelistToken() : null,
4751 fillInIntent, resolvedType, mToken, who,
4752 requestCode, flagsMask, flagsValues, options);
4753 if (result == ActivityManager.START_CANCELED) {
4754 throw new IntentSender.SendIntentException();
4756 Instrumentation.checkStartActivityResult(result, null);
4757 } catch (RemoteException e) {
4759 if (requestCode >= 0) {
4760 // If this start is requesting a result, we can avoid making
4761 // the activity visible until the result is received. Setting
4762 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4763 // activity hidden during this time, to avoid flickering.
4764 // This can only be done when a result is requested because
4765 // that guarantees we will get information back when the
4766 // activity is finished, no matter what happens to it.
4767 mStartedActivity = true;
4772 * Same as {@link #startActivity(Intent, Bundle)} with no options
4775 * @param intent The intent to start.
4777 * @throws android.content.ActivityNotFoundException
4779 * @see #startActivity(Intent, Bundle)
4780 * @see #startActivityForResult
4783 public void startActivity(Intent intent) {
4784 this.startActivity(intent, null);
4788 * Launch a new activity. You will not receive any information about when
4789 * the activity exits. This implementation overrides the base version,
4790 * providing information about
4791 * the activity performing the launch. Because of this additional
4792 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4793 * required; if not specified, the new activity will be added to the
4794 * task of the caller.
4796 * <p>This method throws {@link android.content.ActivityNotFoundException}
4797 * if there was no Activity found to run the given Intent.
4799 * @param intent The intent to start.
4800 * @param options Additional options for how the Activity should be started.
4801 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4802 * Context.startActivity(Intent, Bundle)} for more details.
4804 * @throws android.content.ActivityNotFoundException
4806 * @see #startActivity(Intent)
4807 * @see #startActivityForResult
4810 public void startActivity(Intent intent, @Nullable Bundle options) {
4811 if (options != null) {
4812 startActivityForResult(intent, -1, options);
4814 // Note we want to go through this call for compatibility with
4815 // applications that may have overridden the method.
4816 startActivityForResult(intent, -1);
4821 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4824 * @param intents The intents to start.
4826 * @throws android.content.ActivityNotFoundException
4828 * @see #startActivities(Intent[], Bundle)
4829 * @see #startActivityForResult
4832 public void startActivities(Intent[] intents) {
4833 startActivities(intents, null);
4837 * Launch a new activity. You will not receive any information about when
4838 * the activity exits. This implementation overrides the base version,
4839 * providing information about
4840 * the activity performing the launch. Because of this additional
4841 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4842 * required; if not specified, the new activity will be added to the
4843 * task of the caller.
4845 * <p>This method throws {@link android.content.ActivityNotFoundException}
4846 * if there was no Activity found to run the given Intent.
4848 * @param intents The intents to start.
4849 * @param options Additional options for how the Activity should be started.
4850 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4851 * Context.startActivity(Intent, Bundle)} for more details.
4853 * @throws android.content.ActivityNotFoundException
4855 * @see #startActivities(Intent[])
4856 * @see #startActivityForResult
4859 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4860 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4861 mToken, this, intents, options);
4865 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4868 * @param intent The IntentSender to launch.
4869 * @param fillInIntent If non-null, this will be provided as the
4870 * intent parameter to {@link IntentSender#sendIntent}.
4871 * @param flagsMask Intent flags in the original IntentSender that you
4872 * would like to change.
4873 * @param flagsValues Desired values for any bits set in
4874 * <var>flagsMask</var>
4875 * @param extraFlags Always set to 0.
4877 public void startIntentSender(IntentSender intent,
4878 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4879 throws IntentSender.SendIntentException {
4880 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4885 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4887 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4888 * for more information.
4890 * @param intent The IntentSender to launch.
4891 * @param fillInIntent If non-null, this will be provided as the
4892 * intent parameter to {@link IntentSender#sendIntent}.
4893 * @param flagsMask Intent flags in the original IntentSender that you
4894 * would like to change.
4895 * @param flagsValues Desired values for any bits set in
4896 * <var>flagsMask</var>
4897 * @param extraFlags Always set to 0.
4898 * @param options Additional options for how the Activity should be started.
4899 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4900 * Context.startActivity(Intent, Bundle)} for more details. If options
4901 * have also been supplied by the IntentSender, options given here will
4902 * override any that conflict with those given by the IntentSender.
4904 public void startIntentSender(IntentSender intent,
4905 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4906 Bundle options) throws IntentSender.SendIntentException {
4907 if (options != null) {
4908 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4909 flagsValues, extraFlags, options);
4911 // Note we want to go through this call for compatibility with
4912 // applications that may have overridden the method.
4913 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4914 flagsValues, extraFlags);
4919 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4922 * @param intent The intent to start.
4923 * @param requestCode If >= 0, this code will be returned in
4924 * onActivityResult() when the activity exits, as described in
4925 * {@link #startActivityForResult}.
4927 * @return If a new activity was launched then true is returned; otherwise
4928 * false is returned and you must handle the Intent yourself.
4930 * @see #startActivity
4931 * @see #startActivityForResult
4933 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4935 return startActivityIfNeeded(intent, requestCode, null);
4939 * A special variation to launch an activity only if a new activity
4940 * instance is needed to handle the given Intent. In other words, this is
4941 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4942 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4943 * singleTask or singleTop
4944 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4946 * that handles <var>intent</var> is the same as your currently running
4947 * activity, then a new instance is not needed. In this case, instead of
4948 * the normal behavior of calling {@link #onNewIntent} this function will
4949 * return and you can handle the Intent yourself.
4951 * <p>This function can only be called from a top-level activity; if it is
4952 * called from a child activity, a runtime exception will be thrown.
4954 * @param intent The intent to start.
4955 * @param requestCode If >= 0, this code will be returned in
4956 * onActivityResult() when the activity exits, as described in
4957 * {@link #startActivityForResult}.
4958 * @param options Additional options for how the Activity should be started.
4959 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4960 * Context.startActivity(Intent, Bundle)} for more details.
4962 * @return If a new activity was launched then true is returned; otherwise
4963 * false is returned and you must handle the Intent yourself.
4965 * @see #startActivity
4966 * @see #startActivityForResult
4968 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4969 int requestCode, @Nullable Bundle options) {
4970 if (mParent == null) {
4971 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4973 Uri referrer = onProvideReferrer();
4974 if (referrer != null) {
4975 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4977 intent.migrateExtraStreamToClipData();
4978 intent.prepareToLeaveProcess(this);
4979 result = ActivityManager.getService()
4980 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4981 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4982 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4984 } catch (RemoteException e) {
4988 Instrumentation.checkStartActivityResult(result, intent);
4990 if (requestCode >= 0) {
4991 // If this start is requesting a result, we can avoid making
4992 // the activity visible until the result is received. Setting
4993 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4994 // activity hidden during this time, to avoid flickering.
4995 // This can only be done when a result is requested because
4996 // that guarantees we will get information back when the
4997 // activity is finished, no matter what happens to it.
4998 mStartedActivity = true;
5000 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
5003 throw new UnsupportedOperationException(
5004 "startActivityIfNeeded can only be called from a top-level activity");
5008 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
5011 * @param intent The intent to dispatch to the next activity. For
5012 * correct behavior, this must be the same as the Intent that started
5013 * your own activity; the only changes you can make are to the extras
5016 * @return Returns a boolean indicating whether there was another Activity
5017 * to start: true if there was a next activity to start, false if there
5018 * wasn't. In general, if true is returned you will then want to call
5019 * finish() on yourself.
5021 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
5022 return startNextMatchingActivity(intent, null);
5026 * Special version of starting an activity, for use when you are replacing
5027 * other activity components. You can use this to hand the Intent off
5028 * to the next Activity that can handle it. You typically call this in
5029 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
5031 * @param intent The intent to dispatch to the next activity. For
5032 * correct behavior, this must be the same as the Intent that started
5033 * your own activity; the only changes you can make are to the extras
5035 * @param options Additional options for how the Activity should be started.
5036 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5037 * Context.startActivity(Intent, Bundle)} for more details.
5039 * @return Returns a boolean indicating whether there was another Activity
5040 * to start: true if there was a next activity to start, false if there
5041 * wasn't. In general, if true is returned you will then want to call
5042 * finish() on yourself.
5044 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
5045 @Nullable Bundle options) {
5046 if (mParent == null) {
5048 intent.migrateExtraStreamToClipData();
5049 intent.prepareToLeaveProcess(this);
5050 return ActivityManager.getService()
5051 .startNextMatchingActivity(mToken, intent, options);
5052 } catch (RemoteException e) {
5058 throw new UnsupportedOperationException(
5059 "startNextMatchingActivity can only be called from a top-level activity");
5063 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
5066 * @param child The activity making the call.
5067 * @param intent The intent to start.
5068 * @param requestCode Reply request code. < 0 if reply is not requested.
5070 * @throws android.content.ActivityNotFoundException
5072 * @see #startActivity
5073 * @see #startActivityForResult
5075 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5077 startActivityFromChild(child, intent, requestCode, null);
5081 * This is called when a child activity of this one calls its
5082 * {@link #startActivity} or {@link #startActivityForResult} method.
5084 * <p>This method throws {@link android.content.ActivityNotFoundException}
5085 * if there was no Activity found to run the given Intent.
5087 * @param child The activity making the call.
5088 * @param intent The intent to start.
5089 * @param requestCode Reply request code. < 0 if reply is not requested.
5090 * @param options Additional options for how the Activity should be started.
5091 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5092 * Context.startActivity(Intent, Bundle)} for more details.
5094 * @throws android.content.ActivityNotFoundException
5096 * @see #startActivity
5097 * @see #startActivityForResult
5099 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5100 int requestCode, @Nullable Bundle options) {
5101 options = transferSpringboardActivityOptions(options);
5102 Instrumentation.ActivityResult ar =
5103 mInstrumentation.execStartActivity(
5104 this, mMainThread.getApplicationThread(), mToken, child,
5105 intent, requestCode, options);
5107 mMainThread.sendActivityResult(
5108 mToken, child.mEmbeddedID, requestCode,
5109 ar.getResultCode(), ar.getResultData());
5111 cancelInputsAndStartExitTransition(options);
5115 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
5118 * @param fragment The fragment making the call.
5119 * @param intent The intent to start.
5120 * @param requestCode Reply request code. < 0 if reply is not requested.
5122 * @throws android.content.ActivityNotFoundException
5124 * @see Fragment#startActivity
5125 * @see Fragment#startActivityForResult
5127 public void startActivityFromFragment(@NonNull Fragment fragment,
5128 @RequiresPermission Intent intent, int requestCode) {
5129 startActivityFromFragment(fragment, intent, requestCode, null);
5133 * This is called when a Fragment in this activity calls its
5134 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
5137 * <p>This method throws {@link android.content.ActivityNotFoundException}
5138 * if there was no Activity found to run the given Intent.
5140 * @param fragment The fragment making the call.
5141 * @param intent The intent to start.
5142 * @param requestCode Reply request code. < 0 if reply is not requested.
5143 * @param options Additional options for how the Activity should be started.
5144 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5145 * Context.startActivity(Intent, Bundle)} for more details.
5147 * @throws android.content.ActivityNotFoundException
5149 * @see Fragment#startActivity
5150 * @see Fragment#startActivityForResult
5152 public void startActivityFromFragment(@NonNull Fragment fragment,
5153 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
5154 startActivityForResult(fragment.mWho, intent, requestCode, options);
5160 public void startActivityAsUserFromFragment(@NonNull Fragment fragment,
5161 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
5163 startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
5170 public void startActivityForResult(
5171 String who, Intent intent, int requestCode, @Nullable Bundle options) {
5172 Uri referrer = onProvideReferrer();
5173 if (referrer != null) {
5174 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5176 options = transferSpringboardActivityOptions(options);
5177 Instrumentation.ActivityResult ar =
5178 mInstrumentation.execStartActivity(
5179 this, mMainThread.getApplicationThread(), mToken, who,
5180 intent, requestCode, options);
5182 mMainThread.sendActivityResult(
5183 mToken, who, requestCode,
5184 ar.getResultCode(), ar.getResultData());
5186 cancelInputsAndStartExitTransition(options);
5193 public boolean canStartActivityForResult() {
5198 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
5199 * int, Intent, int, int, int, Bundle)} with no options.
5201 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5202 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5204 throws IntentSender.SendIntentException {
5205 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
5206 flagsMask, flagsValues, extraFlags, null);
5210 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
5211 * taking a IntentSender; see
5212 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5213 * for more information.
5215 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5216 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5217 int extraFlags, @Nullable Bundle options)
5218 throws IntentSender.SendIntentException {
5219 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
5220 flagsMask, flagsValues, options);
5224 * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see
5225 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5226 * for more information.
5230 public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent,
5231 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5232 int extraFlags, @Nullable Bundle options)
5233 throws IntentSender.SendIntentException {
5234 startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent,
5235 flagsMask, flagsValues, options);
5239 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
5240 * or {@link #finish} to specify an explicit transition animation to
5243 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
5244 * to using this with starting activities is to supply the desired animation
5245 * information through a {@link ActivityOptions} bundle to
5246 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
5247 * you to specify a custom animation even when starting an activity from
5248 * outside the context of the current top activity.
5250 * @param enterAnim A resource ID of the animation resource to use for
5251 * the incoming activity. Use 0 for no animation.
5252 * @param exitAnim A resource ID of the animation resource to use for
5253 * the outgoing activity. Use 0 for no animation.
5255 public void overridePendingTransition(int enterAnim, int exitAnim) {
5257 ActivityManager.getService().overridePendingTransition(
5258 mToken, getPackageName(), enterAnim, exitAnim);
5259 } catch (RemoteException e) {
5264 * Call this to set the result that your activity will return to its
5267 * @param resultCode The result code to propagate back to the originating
5268 * activity, often RESULT_CANCELED or RESULT_OK
5270 * @see #RESULT_CANCELED
5272 * @see #RESULT_FIRST_USER
5273 * @see #setResult(int, Intent)
5275 public final void setResult(int resultCode) {
5276 synchronized (this) {
5277 mResultCode = resultCode;
5283 * Call this to set the result that your activity will return to its
5286 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
5287 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
5288 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
5289 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
5290 * Activity receiving the result access to the specific URIs in the Intent.
5291 * Access will remain until the Activity has finished (it will remain across the hosting
5292 * process being killed and other temporary destruction) and will be added
5293 * to any existing set of URI permissions it already holds.
5295 * @param resultCode The result code to propagate back to the originating
5296 * activity, often RESULT_CANCELED or RESULT_OK
5297 * @param data The data to propagate back to the originating activity.
5299 * @see #RESULT_CANCELED
5301 * @see #RESULT_FIRST_USER
5302 * @see #setResult(int)
5304 public final void setResult(int resultCode, Intent data) {
5305 synchronized (this) {
5306 mResultCode = resultCode;
5312 * Return information about who launched this activity. If the launching Intent
5313 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
5314 * that will be returned as-is; otherwise, if known, an
5315 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
5316 * package name that started the Intent will be returned. This may return null if no
5317 * referrer can be identified -- it is neither explicitly specified, nor is it known which
5318 * application package was involved.
5320 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
5321 * return the referrer that submitted that new intent to the activity. Otherwise, it
5322 * always returns the referrer of the original Intent.</p>
5324 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
5325 * referrer information, applications can spoof it.</p>
5328 public Uri getReferrer() {
5329 Intent intent = getIntent();
5331 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
5332 if (referrer != null) {
5335 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
5336 if (referrerName != null) {
5337 return Uri.parse(referrerName);
5339 } catch (BadParcelableException e) {
5340 Log.w(TAG, "Cannot read referrer from intent;"
5341 + " intent extras contain unknown custom Parcelable objects");
5343 if (mReferrer != null) {
5344 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
5350 * Override to generate the desired referrer for the content currently being shown
5351 * by the app. The default implementation returns null, meaning the referrer will simply
5352 * be the android-app: of the package name of this activity. Return a non-null Uri to
5353 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
5355 public Uri onProvideReferrer() {
5360 * Return the name of the package that invoked this activity. This is who
5361 * the data in {@link #setResult setResult()} will be sent to. You can
5362 * use this information to validate that the recipient is allowed to
5365 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5366 * did not use the {@link #startActivityForResult}
5367 * form that includes a request code), then the calling package will be
5370 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
5371 * the result from this method was unstable. If the process hosting the calling
5372 * package was no longer running, it would return null instead of the proper package
5373 * name. You can use {@link #getCallingActivity()} and retrieve the package name
5374 * from that instead.</p>
5376 * @return The package of the activity that will receive your
5377 * reply, or null if none.
5380 public String getCallingPackage() {
5382 return ActivityManager.getService().getCallingPackage(mToken);
5383 } catch (RemoteException e) {
5389 * Return the name of the activity that invoked this activity. This is
5390 * who the data in {@link #setResult setResult()} will be sent to. You
5391 * can use this information to validate that the recipient is allowed to
5394 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5395 * did not use the {@link #startActivityForResult}
5396 * form that includes a request code), then the calling package will be
5399 * @return The ComponentName of the activity that will receive your
5400 * reply, or null if none.
5403 public ComponentName getCallingActivity() {
5405 return ActivityManager.getService().getCallingActivity(mToken);
5406 } catch (RemoteException e) {
5412 * Control whether this activity's main window is visible. This is intended
5413 * only for the special case of an activity that is not going to show a
5414 * UI itself, but can't just finish prior to onResume() because it needs
5415 * to wait for a service binding or such. Setting this to false allows
5416 * you to prevent your UI from being shown during that time.
5418 * <p>The default value for this is taken from the
5419 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
5421 public void setVisible(boolean visible) {
5422 if (mVisibleFromClient != visible) {
5423 mVisibleFromClient = visible;
5424 if (mVisibleFromServer) {
5425 if (visible) makeVisible();
5426 else mDecor.setVisibility(View.INVISIBLE);
5431 void makeVisible() {
5432 if (!mWindowAdded) {
5433 ViewManager wm = getWindowManager();
5434 wm.addView(mDecor, getWindow().getAttributes());
5435 mWindowAdded = true;
5437 mDecor.setVisibility(View.VISIBLE);
5441 * Check to see whether this activity is in the process of finishing,
5442 * either because you called {@link #finish} on it or someone else
5443 * has requested that it finished. This is often used in
5444 * {@link #onPause} to determine whether the activity is simply pausing or
5445 * completely finishing.
5447 * @return If the activity is finishing, returns true; else returns false.
5451 public boolean isFinishing() {
5456 * Returns true if the final {@link #onDestroy()} call has been made
5457 * on the Activity, so this instance is now dead.
5459 public boolean isDestroyed() {
5464 * Check to see whether this activity is in the process of being destroyed in order to be
5465 * recreated with a new configuration. This is often used in
5466 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
5467 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
5469 * @return If the activity is being torn down in order to be recreated with a new configuration,
5470 * returns true; else returns false.
5472 public boolean isChangingConfigurations() {
5473 return mChangingConfigurations;
5477 * Cause this Activity to be recreated with a new instance. This results
5478 * in essentially the same flow as when the Activity is created due to
5479 * a configuration change -- the current instance will go through its
5480 * lifecycle to {@link #onDestroy} and a new instance then created after it.
5482 public void recreate() {
5483 if (mParent != null) {
5484 throw new IllegalStateException("Can only be called on top-level activity");
5486 if (Looper.myLooper() != mMainThread.getLooper()) {
5487 throw new IllegalStateException("Must be called from main thread");
5490 ActivityManager.getService().requestActivityRelaunch(mToken);
5491 } catch (RemoteException e) {
5496 * Finishes the current activity and specifies whether to remove the task associated with this
5499 private void finish(int finishTask) {
5500 if (mParent == null) {
5503 synchronized (this) {
5504 resultCode = mResultCode;
5505 resultData = mResultData;
5507 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
5509 if (resultData != null) {
5510 resultData.prepareToLeaveProcess(this);
5512 if (ActivityManager.getService()
5513 .finishActivity(mToken, resultCode, resultData, finishTask)) {
5516 } catch (RemoteException e) {
5520 mParent.finishFromChild(this);
5523 // Activity was launched when user tapped a link in the Autofill Save UI - Save UI must
5525 if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
5526 getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_RESTORE,
5527 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
5532 * Call this when your activity is done and should be closed. The
5533 * ActivityResult is propagated back to whoever launched you via
5534 * onActivityResult().
5536 public void finish() {
5537 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
5541 * Finish this activity as well as all activities immediately below it
5542 * in the current task that have the same affinity. This is typically
5543 * used when an application can be launched on to another task (such as
5544 * from an ACTION_VIEW of a content type it understands) and the user
5545 * has used the up navigation to switch out of the current task and in
5546 * to its own task. In this case, if the user has navigated down into
5547 * any other activities of the second application, all of those should
5548 * be removed from the original task as part of the task switch.
5550 * <p>Note that this finish does <em>not</em> allow you to deliver results
5551 * to the previous activity, and an exception will be thrown if you are trying
5554 public void finishAffinity() {
5555 if (mParent != null) {
5556 throw new IllegalStateException("Can not be called from an embedded activity");
5558 if (mResultCode != RESULT_CANCELED || mResultData != null) {
5559 throw new IllegalStateException("Can not be called to deliver a result");
5562 if (ActivityManager.getService().finishActivityAffinity(mToken)) {
5565 } catch (RemoteException e) {
5571 * This is called when a child activity of this one calls its
5572 * {@link #finish} method. The default implementation simply calls
5573 * finish() on this activity (the parent), finishing the entire group.
5575 * @param child The activity making the call.
5579 public void finishFromChild(Activity child) {
5584 * Reverses the Activity Scene entry Transition and triggers the calling Activity
5585 * to reverse its exit Transition. When the exit Transition completes,
5586 * {@link #finish()} is called. If no entry Transition was used, finish() is called
5587 * immediately and the Activity exit Transition is run.
5588 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
5590 public void finishAfterTransition() {
5591 if (!mActivityTransitionState.startExitBackTransition(this)) {
5597 * Force finish another activity that you had previously started with
5598 * {@link #startActivityForResult}.
5600 * @param requestCode The request code of the activity that you had
5601 * given to startActivityForResult(). If there are multiple
5602 * activities started with this request code, they
5603 * will all be finished.
5605 public void finishActivity(int requestCode) {
5606 if (mParent == null) {
5608 ActivityManager.getService()
5609 .finishSubActivity(mToken, mEmbeddedID, requestCode);
5610 } catch (RemoteException e) {
5614 mParent.finishActivityFromChild(this, requestCode);
5619 * This is called when a child activity of this one calls its
5622 * @param child The activity making the call.
5623 * @param requestCode Request code that had been used to start the
5626 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
5628 ActivityManager.getService()
5629 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
5630 } catch (RemoteException e) {
5636 * Call this when your activity is done and should be closed and the task should be completely
5637 * removed as a part of finishing the root activity of the task.
5639 public void finishAndRemoveTask() {
5640 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
5644 * Ask that the local app instance of this activity be released to free up its memory.
5645 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5646 * a new instance of the activity will later be re-created if needed due to the user
5647 * navigating back to it.
5649 * @return Returns true if the activity was in a state that it has started the process
5650 * of destroying its current instance; returns false if for any reason this could not
5651 * be done: it is currently visible to the user, it is already being destroyed, it is
5652 * being finished, it hasn't yet saved its state, etc.
5654 public boolean releaseInstance() {
5656 return ActivityManager.getService().releaseActivityInstance(mToken);
5657 } catch (RemoteException e) {
5664 * Called when an activity you launched exits, giving you the requestCode
5665 * you started it with, the resultCode it returned, and any additional
5666 * data from it. The <var>resultCode</var> will be
5667 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5668 * didn't return any result, or crashed during its operation.
5670 * <p>You will receive this call immediately before onResume() when your
5671 * activity is re-starting.
5673 * <p>This method is never invoked if your activity sets
5674 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5675 * <code>true</code>.
5677 * @param requestCode The integer request code originally supplied to
5678 * startActivityForResult(), allowing you to identify who this
5680 * @param resultCode The integer result code returned by the child activity
5681 * through its setResult().
5682 * @param data An Intent, which can return result data to the caller
5683 * (various data can be attached to Intent "extras").
5685 * @see #startActivityForResult
5686 * @see #createPendingResult
5687 * @see #setResult(int)
5689 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5693 * Called when an activity you launched with an activity transition exposes this
5694 * Activity through a returning activity transition, giving you the resultCode
5695 * and any additional data from it. This method will only be called if the activity
5696 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5697 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5699 * <p>The purpose of this function is to let the called Activity send a hint about
5700 * its state so that this underlying Activity can prepare to be exposed. A call to
5701 * this method does not guarantee that the called Activity has or will be exiting soon.
5702 * It only indicates that it will expose this Activity's Window and it has
5703 * some data to pass to prepare it.</p>
5705 * @param resultCode The integer result code returned by the child activity
5706 * through its setResult().
5707 * @param data An Intent, which can return result data to the caller
5708 * (various data can be attached to Intent "extras").
5710 public void onActivityReenter(int resultCode, Intent data) {
5714 * Create a new PendingIntent object which you can hand to others
5715 * for them to use to send result data back to your
5716 * {@link #onActivityResult} callback. The created object will be either
5717 * one-shot (becoming invalid after a result is sent back) or multiple
5718 * (allowing any number of results to be sent through it).
5720 * @param requestCode Private request code for the sender that will be
5721 * associated with the result data when it is returned. The sender can not
5722 * modify this value, allowing you to identify incoming results.
5723 * @param data Default data to supply in the result, which may be modified
5725 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5726 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5727 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5728 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5729 * or any of the flags as supported by
5730 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5731 * of the intent that can be supplied when the actual send happens.
5733 * @return Returns an existing or new PendingIntent matching the given
5734 * parameters. May return null only if
5735 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5738 * @see PendingIntent
5740 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5741 @PendingIntent.Flags int flags) {
5742 String packageName = getPackageName();
5744 data.prepareToLeaveProcess(this);
5745 IIntentSender target =
5746 ActivityManager.getService().getIntentSender(
5747 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5748 mParent == null ? mToken : mParent.mToken,
5749 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5750 UserHandle.myUserId());
5751 return target != null ? new PendingIntent(target) : null;
5752 } catch (RemoteException e) {
5759 * Change the desired orientation of this activity. If the activity
5760 * is currently in the foreground or otherwise impacting the screen
5761 * orientation, the screen will immediately be changed (possibly causing
5762 * the activity to be restarted). Otherwise, this will be used the next
5763 * time the activity is visible.
5765 * @param requestedOrientation An orientation constant as used in
5766 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5768 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5769 if (mParent == null) {
5771 ActivityManager.getService().setRequestedOrientation(
5772 mToken, requestedOrientation);
5773 } catch (RemoteException e) {
5777 mParent.setRequestedOrientation(requestedOrientation);
5782 * Return the current requested orientation of the activity. This will
5783 * either be the orientation requested in its component's manifest, or
5784 * the last requested orientation given to
5785 * {@link #setRequestedOrientation(int)}.
5787 * @return Returns an orientation constant as used in
5788 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5790 @ActivityInfo.ScreenOrientation
5791 public int getRequestedOrientation() {
5792 if (mParent == null) {
5794 return ActivityManager.getService()
5795 .getRequestedOrientation(mToken);
5796 } catch (RemoteException e) {
5800 return mParent.getRequestedOrientation();
5802 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5806 * Return the identifier of the task this activity is in. This identifier
5807 * will remain the same for the lifetime of the activity.
5809 * @return Task identifier, an opaque integer.
5811 public int getTaskId() {
5813 return ActivityManager.getService()
5814 .getTaskForActivity(mToken, false);
5815 } catch (RemoteException e) {
5821 * Return whether this activity is the root of a task. The root is the
5822 * first activity in a task.
5824 * @return True if this is the root activity, else false.
5827 public boolean isTaskRoot() {
5829 return ActivityManager.getService().getTaskForActivity(mToken, true) >= 0;
5830 } catch (RemoteException e) {
5836 * Move the task containing this activity to the back of the activity
5837 * stack. The activity's order within the task is unchanged.
5839 * @param nonRoot If false then this only works if the activity is the root
5840 * of a task; if true it will work for any activity in
5843 * @return If the task was moved (or it was already at the
5844 * back) true is returned, else false.
5846 public boolean moveTaskToBack(boolean nonRoot) {
5848 return ActivityManager.getService().moveActivityTaskToBack(
5850 } catch (RemoteException e) {
5857 * Returns class name for this activity with the package prefix removed.
5858 * This is the default name used to read and write settings.
5860 * @return The local class name.
5863 public String getLocalClassName() {
5864 final String pkg = getPackageName();
5865 final String cls = mComponent.getClassName();
5866 int packageLen = pkg.length();
5867 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5868 || cls.charAt(packageLen) != '.') {
5871 return cls.substring(packageLen+1);
5875 * Returns complete component name of this activity.
5877 * @return Returns the complete component name for this activity
5879 public ComponentName getComponentName()
5885 * Temporary method on O-MR1 only.
5890 public ComponentName getComponentNameForAutofill() {
5895 * Retrieve a {@link SharedPreferences} object for accessing preferences
5896 * that are private to this activity. This simply calls the underlying
5897 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5898 * class name as the preferences name.
5900 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5903 * @return Returns the single SharedPreferences instance that can be used
5904 * to retrieve and modify the preference values.
5906 public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
5907 return getSharedPreferences(getLocalClassName(), mode);
5910 private void ensureSearchManager() {
5911 if (mSearchManager != null) {
5916 mSearchManager = new SearchManager(this, null);
5917 } catch (ServiceNotFoundException e) {
5918 throw new IllegalStateException(e);
5923 public Object getSystemService(@ServiceName @NonNull String name) {
5924 if (getBaseContext() == null) {
5925 throw new IllegalStateException(
5926 "System services not available to Activities before onCreate()");
5929 if (WINDOW_SERVICE.equals(name)) {
5930 return mWindowManager;
5931 } else if (SEARCH_SERVICE.equals(name)) {
5932 ensureSearchManager();
5933 return mSearchManager;
5935 return super.getSystemService(name);
5939 * Change the title associated with this activity. If this is a
5940 * top-level activity, the title for its window will change. If it
5941 * is an embedded activity, the parent can do whatever it wants
5944 public void setTitle(CharSequence title) {
5946 onTitleChanged(title, mTitleColor);
5948 if (mParent != null) {
5949 mParent.onChildTitleChanged(this, title);
5954 * Change the title associated with this activity. If this is a
5955 * top-level activity, the title for its window will change. If it
5956 * is an embedded activity, the parent can do whatever it wants
5959 public void setTitle(int titleId) {
5960 setTitle(getText(titleId));
5964 * Change the color of the title associated with this activity.
5966 * This method is deprecated starting in API Level 11 and replaced by action
5967 * bar styles. For information on styling the Action Bar, read the <a
5968 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5971 * @deprecated Use action bar styles instead.
5974 public void setTitleColor(int textColor) {
5975 mTitleColor = textColor;
5976 onTitleChanged(mTitle, textColor);
5979 public final CharSequence getTitle() {
5983 public final int getTitleColor() {
5987 protected void onTitleChanged(CharSequence title, int color) {
5989 final Window win = getWindow();
5991 win.setTitle(title);
5993 win.setTitleColor(color);
5996 if (mActionBar != null) {
5997 mActionBar.setWindowTitle(title);
6002 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
6006 * Sets information describing the task with this activity for presentation inside the Recents
6007 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
6008 * are traversed in order from the topmost activity to the bottommost. The traversal continues
6009 * for each property until a suitable value is found. For each task the taskDescription will be
6010 * returned in {@link android.app.ActivityManager.TaskDescription}.
6012 * @see ActivityManager#getRecentTasks
6013 * @see android.app.ActivityManager.TaskDescription
6015 * @param taskDescription The TaskDescription properties that describe the task with this activity
6017 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
6018 if (mTaskDescription != taskDescription) {
6019 mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
6020 // Scale the icon down to something reasonable if it is provided
6021 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
6022 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
6023 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
6025 mTaskDescription.setIcon(icon);
6029 ActivityManager.getService().setTaskDescription(mToken, mTaskDescription);
6030 } catch (RemoteException e) {
6035 * Sets the visibility of the progress bar in the title.
6037 * In order for the progress bar to be shown, the feature must be requested
6038 * via {@link #requestWindowFeature(int)}.
6040 * @param visible Whether to show the progress bars in the title.
6041 * @deprecated No longer supported starting in API 21.
6044 public final void setProgressBarVisibility(boolean visible) {
6045 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
6046 Window.PROGRESS_VISIBILITY_OFF);
6050 * Sets the visibility of the indeterminate progress bar in the title.
6052 * In order for the progress bar to be shown, the feature must be requested
6053 * via {@link #requestWindowFeature(int)}.
6055 * @param visible Whether to show the progress bars in the title.
6056 * @deprecated No longer supported starting in API 21.
6059 public final void setProgressBarIndeterminateVisibility(boolean visible) {
6060 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
6061 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
6065 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
6066 * is always indeterminate).
6068 * In order for the progress bar to be shown, the feature must be requested
6069 * via {@link #requestWindowFeature(int)}.
6071 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
6072 * @deprecated No longer supported starting in API 21.
6075 public final void setProgressBarIndeterminate(boolean indeterminate) {
6076 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6077 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
6078 : Window.PROGRESS_INDETERMINATE_OFF);
6082 * Sets the progress for the progress bars in the title.
6084 * In order for the progress bar to be shown, the feature must be requested
6085 * via {@link #requestWindowFeature(int)}.
6087 * @param progress The progress for the progress bar. Valid ranges are from
6088 * 0 to 10000 (both inclusive). If 10000 is given, the progress
6089 * bar will be completely filled and will fade out.
6090 * @deprecated No longer supported starting in API 21.
6093 public final void setProgress(int progress) {
6094 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
6098 * Sets the secondary progress for the progress bar in the title. This
6099 * progress is drawn between the primary progress (set via
6100 * {@link #setProgress(int)} and the background. It can be ideal for media
6101 * scenarios such as showing the buffering progress while the default
6102 * progress shows the play progress.
6104 * In order for the progress bar to be shown, the feature must be requested
6105 * via {@link #requestWindowFeature(int)}.
6107 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
6108 * 0 to 10000 (both inclusive).
6109 * @deprecated No longer supported starting in API 21.
6112 public final void setSecondaryProgress(int secondaryProgress) {
6113 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6114 secondaryProgress + Window.PROGRESS_SECONDARY_START);
6118 * Suggests an audio stream whose volume should be changed by the hardware
6121 * The suggested audio stream will be tied to the window of this Activity.
6122 * Volume requests which are received while the Activity is in the
6123 * foreground will affect this stream.
6125 * It is not guaranteed that the hardware volume controls will always change
6126 * this stream's volume (for example, if a call is in progress, its stream's
6127 * volume may be changed instead). To reset back to the default, use
6128 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
6130 * @param streamType The type of the audio stream whose volume should be
6131 * changed by the hardware volume controls.
6133 public final void setVolumeControlStream(int streamType) {
6134 getWindow().setVolumeControlStream(streamType);
6138 * Gets the suggested audio stream whose volume should be changed by the
6139 * hardware volume controls.
6141 * @return The suggested audio stream type whose volume should be changed by
6142 * the hardware volume controls.
6143 * @see #setVolumeControlStream(int)
6145 public final int getVolumeControlStream() {
6146 return getWindow().getVolumeControlStream();
6150 * Sets a {@link MediaController} to send media keys and volume changes to.
6152 * The controller will be tied to the window of this Activity. Media key and
6153 * volume events which are received while the Activity is in the foreground
6154 * will be forwarded to the controller and used to invoke transport controls
6155 * or adjust the volume. This may be used instead of or in addition to
6156 * {@link #setVolumeControlStream} to affect a specific session instead of a
6159 * It is not guaranteed that the hardware volume controls will always change
6160 * this session's volume (for example, if a call is in progress, its
6161 * stream's volume may be changed instead). To reset back to the default use
6162 * null as the controller.
6164 * @param controller The controller for the session which should receive
6165 * media keys and volume changes.
6167 public final void setMediaController(MediaController controller) {
6168 getWindow().setMediaController(controller);
6172 * Gets the controller which should be receiving media key and volume events
6173 * while this activity is in the foreground.
6175 * @return The controller which should receive events.
6176 * @see #setMediaController(android.media.session.MediaController)
6178 public final MediaController getMediaController() {
6179 return getWindow().getMediaController();
6183 * Runs the specified action on the UI thread. If the current thread is the UI
6184 * thread, then the action is executed immediately. If the current thread is
6185 * not the UI thread, the action is posted to the event queue of the UI thread.
6187 * @param action the action to run on the UI thread
6190 public final void runOnUiThread(Runnable action) {
6191 if (Thread.currentThread() != mUiThread) {
6192 mHandler.post(action);
6199 * Standard implementation of
6200 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
6201 * inflating with the LayoutInflater returned by {@link #getSystemService}.
6202 * This implementation does nothing and is for
6203 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
6204 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
6206 * @see android.view.LayoutInflater#createView
6207 * @see android.view.Window#getLayoutInflater
6210 public View onCreateView(String name, Context context, AttributeSet attrs) {
6215 * Standard implementation of
6216 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
6217 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
6218 * This implementation handles <fragment> tags to embed fragments inside
6221 * @see android.view.LayoutInflater#createView
6222 * @see android.view.Window#getLayoutInflater
6224 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
6225 if (!"fragment".equals(name)) {
6226 return onCreateView(name, context, attrs);
6229 return mFragments.onCreateView(parent, name, context, attrs);
6233 * Print the Activity's state into the given stream. This gets invoked if
6234 * you run "adb shell dumpsys activity <activity_component_name>".
6236 * @param prefix Desired prefix to prepend at each line of output.
6237 * @param fd The raw file descriptor that the dump is being sent to.
6238 * @param writer The PrintWriter to which you should dump your state. This will be
6239 * closed for you after you return.
6240 * @param args additional arguments to the dump request.
6242 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6243 dumpInner(prefix, fd, writer, args);
6246 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6247 writer.print(prefix); writer.print("Local Activity ");
6248 writer.print(Integer.toHexString(System.identityHashCode(this)));
6249 writer.println(" State:");
6250 String innerPrefix = prefix + " ";
6251 writer.print(innerPrefix); writer.print("mResumed=");
6252 writer.print(mResumed); writer.print(" mStopped=");
6253 writer.print(mStopped); writer.print(" mFinished=");
6254 writer.println(mFinished);
6255 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
6256 writer.println(mChangingConfigurations);
6257 writer.print(innerPrefix); writer.print("mCurrentConfig=");
6258 writer.println(mCurrentConfig);
6260 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
6261 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
6262 if (mVoiceInteractor != null) {
6263 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
6266 if (getWindow() != null &&
6267 getWindow().peekDecorView() != null &&
6268 getWindow().peekDecorView().getViewRootImpl() != null) {
6269 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
6272 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
6274 final AutofillManager afm = getAutofillManager();
6276 afm.dump(prefix, writer);
6281 * Bit indicating that this activity is "immersive" and should not be
6282 * interrupted by notifications if possible.
6284 * This value is initially set by the manifest property
6285 * <code>android:immersive</code> but may be changed at runtime by
6286 * {@link #setImmersive}.
6288 * @see #setImmersive(boolean)
6289 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6291 public boolean isImmersive() {
6293 return ActivityManager.getService().isImmersive(mToken);
6294 } catch (RemoteException e) {
6300 * Indication of whether this is the highest level activity in this task. Can be used to
6301 * determine whether an activity launched by this activity was placed in the same task or
6304 * @return true if this is the topmost, non-finishing activity in its task.
6306 private boolean isTopOfTask() {
6307 if (mToken == null || mWindow == null) {
6311 return ActivityManager.getService().isTopOfTask(getActivityToken());
6312 } catch (RemoteException e) {
6318 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
6319 * fullscreen opaque Activity.
6321 * Call this whenever the background of a translucent Activity has changed to become opaque.
6322 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
6324 * This call has no effect on non-translucent activities or on activities with the
6325 * {@link android.R.attr#windowIsFloating} attribute.
6327 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6329 * @see TranslucentConversionListener
6334 public void convertFromTranslucent() {
6336 mTranslucentCallback = null;
6337 if (ActivityManager.getService().convertFromTranslucent(mToken)) {
6338 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
6340 } catch (RemoteException e) {
6346 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
6347 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
6349 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
6350 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
6351 * be called indicating that it is safe to make this activity translucent again. Until
6352 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
6353 * behind the frontmost Activity will be indeterminate.
6355 * This call has no effect on non-translucent activities or on activities with the
6356 * {@link android.R.attr#windowIsFloating} attribute.
6358 * @param callback the method to call when all visible Activities behind this one have been
6359 * drawn and it is safe to make this Activity translucent again.
6360 * @param options activity options delivered to the activity below this one. The options
6361 * are retrieved using {@link #getActivityOptions}.
6362 * @return <code>true</code> if Window was opaque and will become translucent or
6363 * <code>false</code> if window was translucent and no change needed to be made.
6365 * @see #convertFromTranslucent()
6366 * @see TranslucentConversionListener
6371 public boolean convertToTranslucent(TranslucentConversionListener callback,
6372 ActivityOptions options) {
6373 boolean drawComplete;
6375 mTranslucentCallback = callback;
6376 mChangeCanvasToTranslucent = ActivityManager.getService().convertToTranslucent(
6377 mToken, options == null ? null : options.toBundle());
6378 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6379 drawComplete = true;
6380 } catch (RemoteException e) {
6381 // Make callback return as though it timed out.
6382 mChangeCanvasToTranslucent = false;
6383 drawComplete = false;
6385 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
6386 // Window is already translucent.
6387 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6389 return mChangeCanvasToTranslucent;
6393 void onTranslucentConversionComplete(boolean drawComplete) {
6394 if (mTranslucentCallback != null) {
6395 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6396 mTranslucentCallback = null;
6398 if (mChangeCanvasToTranslucent) {
6399 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6404 public void onNewActivityOptions(ActivityOptions options) {
6405 mActivityTransitionState.setEnterActivityOptions(this, options);
6407 mActivityTransitionState.enterReady(this);
6412 * Retrieve the ActivityOptions passed in from the launching activity or passed back
6413 * from an activity launched by this activity in its call to {@link
6414 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
6416 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
6419 ActivityOptions getActivityOptions() {
6421 return ActivityOptions.fromBundle(
6422 ActivityManager.getService().getActivityOptions(mToken));
6423 } catch (RemoteException e) {
6429 * Activities that want to remain visible behind a translucent activity above them must call
6430 * this method anytime between the start of {@link #onResume()} and the return from
6431 * {@link #onPause()}. If this call is successful then the activity will remain visible after
6432 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
6434 * <p>The actions of this call are reset each time that this activity is brought to the
6435 * front. That is, every time {@link #onResume()} is called the activity will be assumed
6436 * to not have requested visible behind. Therefore, if you want this activity to continue to
6437 * be visible in the background you must call this method again.
6439 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
6440 * for dialog and translucent activities.
6442 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
6443 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
6445 * <p>False will be returned any time this method is called between the return of onPause and
6446 * the next call to onResume.
6448 * @deprecated This method's functionality is no longer supported as of
6449 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6451 * @param visible true to notify the system that the activity wishes to be visible behind other
6452 * translucent activities, false to indicate otherwise. Resources must be
6453 * released when passing false to this method.
6455 * @return the resulting visibiity state. If true the activity will remain visible beyond
6456 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
6457 * then the activity may not count on being visible behind other translucent activities,
6458 * and must stop any media playback and release resources.
6459 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
6460 * the return value must be checked.
6462 * @see #onVisibleBehindCanceled()
6465 public boolean requestVisibleBehind(boolean visible) {
6470 * Called when a translucent activity over this activity is becoming opaque or another
6471 * activity is being launched. Activities that override this method must call
6472 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
6474 * <p>When this method is called the activity has 500 msec to release any resources it may be
6475 * using while visible in the background.
6476 * If the activity has not returned from this method in 500 msec the system will destroy
6477 * the activity and kill the process in order to recover the resources for another
6478 * process. Otherwise {@link #onStop()} will be called following return.
6480 * @see #requestVisibleBehind(boolean)
6482 * @deprecated This method's functionality is no longer supported as of
6483 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6487 public void onVisibleBehindCanceled() {
6492 * Translucent activities may call this to determine if there is an activity below them that
6493 * is currently set to be visible in the background.
6495 * @deprecated This method's functionality is no longer supported as of
6496 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6498 * @return true if an activity below is set to visible according to the most recent call to
6499 * {@link #requestVisibleBehind(boolean)}, false otherwise.
6501 * @see #requestVisibleBehind(boolean)
6502 * @see #onVisibleBehindCanceled()
6503 * @see #onBackgroundVisibleBehindChanged(boolean)
6508 public boolean isBackgroundVisibleBehind() {
6513 * The topmost foreground activity will receive this call when the background visibility state
6514 * of the activity below it changes.
6516 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
6517 * due to a background activity finishing itself.
6519 * @deprecated This method's functionality is no longer supported as of
6520 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6522 * @param visible true if a background activity is visible, false otherwise.
6524 * @see #requestVisibleBehind(boolean)
6525 * @see #onVisibleBehindCanceled()
6530 public void onBackgroundVisibleBehindChanged(boolean visible) {
6534 * Activities cannot draw during the period that their windows are animating in. In order
6535 * to know when it is safe to begin drawing they can override this method which will be
6536 * called when the entering animation has completed.
6538 public void onEnterAnimationComplete() {
6544 public void dispatchEnterAnimationComplete() {
6545 onEnterAnimationComplete();
6546 if (getWindow() != null && getWindow().getDecorView() != null) {
6547 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
6552 * Adjust the current immersive mode setting.
6554 * Note that changing this value will have no effect on the activity's
6555 * {@link android.content.pm.ActivityInfo} structure; that is, if
6556 * <code>android:immersive</code> is set to <code>true</code>
6557 * in the application's manifest entry for this activity, the {@link
6558 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
6559 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6560 * FLAG_IMMERSIVE} bit set.
6562 * @see #isImmersive()
6563 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6565 public void setImmersive(boolean i) {
6567 ActivityManager.getService().setImmersive(mToken, i);
6568 } catch (RemoteException e) {
6574 * Enable or disable virtual reality (VR) mode for this Activity.
6576 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
6577 * while this Activity has user focus.</p>
6579 * <p>It is recommended that applications additionally declare
6580 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
6581 * transitions when switching between VR activities.</p>
6583 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
6584 * VR mode will not be started. Developers can handle this case as follows:</p>
6587 * String servicePackage = "com.whatever.app";
6588 * String serviceClass = "com.whatever.app.MyVrListenerService";
6590 * // Name of the component of the VrListenerService to start.
6591 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
6594 * setVrModeEnabled(true, myComponentName);
6595 * } catch (PackageManager.NameNotFoundException e) {
6596 * List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
6597 * boolean isInstalled = false;
6598 * for (ApplicationInfo app : installed) {
6599 * if (app.packageName.equals(servicePackage)) {
6600 * isInstalled = true;
6604 * if (isInstalled) {
6605 * // Package is installed, but not enabled in Settings. Let user enable it.
6606 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
6608 * // Package is not installed. Send an intent to download this.
6609 * sentIntentToLaunchAppStore(servicePackage);
6614 * @param enabled {@code true} to enable this mode.
6615 * @param requestedComponent the name of the component to use as a
6616 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
6618 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
6619 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
6620 * not been enabled in user settings.
6622 * @see android.content.pm.PackageManager#FEATURE_VR_MODE
6623 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
6624 * @see android.service.vr.VrListenerService
6625 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
6626 * @see android.R.attr#enableVrMode
6628 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
6629 throws PackageManager.NameNotFoundException {
6631 if (ActivityManager.getService().setVrMode(mToken, enabled, requestedComponent)
6633 throw new PackageManager.NameNotFoundException(
6634 requestedComponent.flattenToString());
6636 } catch (RemoteException e) {
6642 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
6644 * @param callback Callback that will manage lifecycle events for this action mode
6645 * @return The ActionMode that was started, or null if it was canceled
6650 public ActionMode startActionMode(ActionMode.Callback callback) {
6651 return mWindow.getDecorView().startActionMode(callback);
6655 * Start an action mode of the given type.
6657 * @param callback Callback that will manage lifecycle events for this action mode
6658 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6659 * @return The ActionMode that was started, or null if it was canceled
6664 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6665 return mWindow.getDecorView().startActionMode(callback, type);
6669 * Give the Activity a chance to control the UI for an action mode requested
6672 * <p>Note: If you are looking for a notification callback that an action mode
6673 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
6675 * @param callback The callback that should control the new action mode
6676 * @return The new action mode, or <code>null</code> if the activity does not want to
6677 * provide special handling for this action mode. (It will be handled by the system.)
6681 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
6682 // Only Primary ActionModes are represented in the ActionBar.
6683 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
6684 initWindowDecorActionBar();
6685 if (mActionBar != null) {
6686 return mActionBar.startActionMode(callback);
6697 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
6699 mActionModeTypeStarting = type;
6700 return onWindowStartingActionMode(callback);
6702 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
6707 * Notifies the Activity that an action mode has been started.
6708 * Activity subclasses overriding this method should call the superclass implementation.
6710 * @param mode The new action mode.
6714 public void onActionModeStarted(ActionMode mode) {
6718 * Notifies the activity that an action mode has finished.
6719 * Activity subclasses overriding this method should call the superclass implementation.
6721 * @param mode The action mode that just finished.
6725 public void onActionModeFinished(ActionMode mode) {
6729 * Returns true if the app should recreate the task when navigating 'up' from this activity
6730 * by using targetIntent.
6732 * <p>If this method returns false the app can trivially call
6733 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
6734 * up navigation. If this method returns false, the app should synthesize a new task stack
6735 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6737 * @param targetIntent An intent representing the target destination for up navigation
6738 * @return true if navigating up should recreate a new task stack, false if the same task
6739 * should be used for the destination
6741 public boolean shouldUpRecreateTask(Intent targetIntent) {
6743 PackageManager pm = getPackageManager();
6744 ComponentName cn = targetIntent.getComponent();
6746 cn = targetIntent.resolveActivity(pm);
6748 ActivityInfo info = pm.getActivityInfo(cn, 0);
6749 if (info.taskAffinity == null) {
6752 return ActivityManager.getService()
6753 .shouldUpRecreateTask(mToken, info.taskAffinity);
6754 } catch (RemoteException e) {
6756 } catch (NameNotFoundException e) {
6762 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6763 * in the process. If the activity indicated by upIntent already exists in the task's history,
6764 * this activity and all others before the indicated activity in the history stack will be
6767 * <p>If the indicated activity does not appear in the history stack, this will finish
6768 * each activity in this task until the root activity of the task is reached, resulting in
6769 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6770 * when an activity may be reached by a path not passing through a canonical parent
6773 * <p>This method should be used when performing up navigation from within the same task
6774 * as the destination. If up navigation should cross tasks in some cases, see
6775 * {@link #shouldUpRecreateTask(Intent)}.</p>
6777 * @param upIntent An intent representing the target destination for up navigation
6779 * @return true if up navigation successfully reached the activity indicated by upIntent and
6780 * upIntent was delivered to it. false if an instance of the indicated activity could
6781 * not be found and this activity was simply finished normally.
6783 public boolean navigateUpTo(Intent upIntent) {
6784 if (mParent == null) {
6785 ComponentName destInfo = upIntent.getComponent();
6786 if (destInfo == null) {
6787 destInfo = upIntent.resolveActivity(getPackageManager());
6788 if (destInfo == null) {
6791 upIntent = new Intent(upIntent);
6792 upIntent.setComponent(destInfo);
6796 synchronized (this) {
6797 resultCode = mResultCode;
6798 resultData = mResultData;
6800 if (resultData != null) {
6801 resultData.prepareToLeaveProcess(this);
6804 upIntent.prepareToLeaveProcess(this);
6805 return ActivityManager.getService().navigateUpTo(mToken, upIntent,
6806 resultCode, resultData);
6807 } catch (RemoteException e) {
6811 return mParent.navigateUpToFromChild(this, upIntent);
6816 * This is called when a child activity of this one calls its
6817 * {@link #navigateUpTo} method. The default implementation simply calls
6818 * navigateUpTo(upIntent) on this activity (the parent).
6820 * @param child The activity making the call.
6821 * @param upIntent An intent representing the target destination for up navigation
6823 * @return true if up navigation successfully reached the activity indicated by upIntent and
6824 * upIntent was delivered to it. false if an instance of the indicated activity could
6825 * not be found and this activity was simply finished normally.
6827 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6828 return navigateUpTo(upIntent);
6832 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6833 * this activity's logical parent. The logical parent is named in the application's manifest
6834 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6835 * Activity subclasses may override this method to modify the Intent returned by
6836 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6837 * the parent intent entirely.
6839 * @return a new Intent targeting the defined parent of this activity or null if
6840 * there is no valid parent.
6843 public Intent getParentActivityIntent() {
6844 final String parentName = mActivityInfo.parentActivityName;
6845 if (TextUtils.isEmpty(parentName)) {
6849 // If the parent itself has no parent, generate a main activity intent.
6850 final ComponentName target = new ComponentName(this, parentName);
6852 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6853 final String parentActivity = parentInfo.parentActivityName;
6854 final Intent parentIntent = parentActivity == null
6855 ? Intent.makeMainActivity(target)
6856 : new Intent().setComponent(target);
6857 return parentIntent;
6858 } catch (NameNotFoundException e) {
6859 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6866 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6867 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6868 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6869 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6871 * @param callback Used to manipulate shared element transitions on the launched Activity.
6873 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6874 if (callback == null) {
6875 callback = SharedElementCallback.NULL_CALLBACK;
6877 mEnterTransitionListener = callback;
6881 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6882 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6883 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6884 * calls will only come when returning from the started Activity.
6885 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6887 * @param callback Used to manipulate shared element transitions on the launching Activity.
6889 public void setExitSharedElementCallback(SharedElementCallback callback) {
6890 if (callback == null) {
6891 callback = SharedElementCallback.NULL_CALLBACK;
6893 mExitTransitionListener = callback;
6897 * Postpone the entering activity transition when Activity was started with
6898 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6899 * android.util.Pair[])}.
6900 * <p>This method gives the Activity the ability to delay starting the entering and
6901 * shared element transitions until all data is loaded. Until then, the Activity won't
6902 * draw into its window, leaving the window transparent. This may also cause the
6903 * returning animation to be delayed until data is ready. This method should be
6904 * called in {@link #onCreate(android.os.Bundle)} or in
6905 * {@link #onActivityReenter(int, android.content.Intent)}.
6906 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6907 * start the transitions. If the Activity did not use
6908 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6909 * android.util.Pair[])}, then this method does nothing.</p>
6911 public void postponeEnterTransition() {
6912 mActivityTransitionState.postponeEnterTransition();
6916 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6917 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6918 * to have your Activity start drawing.
6920 public void startPostponedEnterTransition() {
6921 mActivityTransitionState.startPostponedEnterTransition();
6925 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
6926 * access permissions for content URIs associated with the {@link DragEvent}.
6927 * @param event Drag event
6928 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
6929 * Null if no content URIs are associated with the event or if permissions could not be granted.
6931 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
6932 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
6933 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
6934 return dragAndDropPermissions;
6939 // ------------------ Internal API ------------------
6941 final void setParent(Activity parent) {
6945 final void attach(Context context, ActivityThread aThread,
6946 Instrumentation instr, IBinder token, int ident,
6947 Application application, Intent intent, ActivityInfo info,
6948 CharSequence title, Activity parent, String id,
6949 NonConfigurationInstances lastNonConfigurationInstances,
6950 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6951 Window window, ActivityConfigCallback activityConfigCallback) {
6952 attachBaseContext(context);
6954 mFragments.attachHost(null /*parent*/);
6956 mWindow = new PhoneWindow(this, window, activityConfigCallback);
6957 mWindow.setWindowControllerCallback(this);
6958 mWindow.setCallback(this);
6959 mWindow.setOnWindowDismissedCallback(this);
6960 mWindow.getLayoutInflater().setPrivateFactory(this);
6961 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6962 mWindow.setSoftInputMode(info.softInputMode);
6964 if (info.uiOptions != 0) {
6965 mWindow.setUiOptions(info.uiOptions);
6967 mUiThread = Thread.currentThread();
6969 mMainThread = aThread;
6970 mInstrumentation = instr;
6973 mApplication = application;
6975 mReferrer = referrer;
6976 mComponent = intent.getComponent();
6977 mActivityInfo = info;
6981 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6982 if (voiceInteractor != null) {
6983 if (lastNonConfigurationInstances != null) {
6984 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6986 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6991 mWindow.setWindowManager(
6992 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6993 mToken, mComponent.flattenToString(),
6994 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6995 if (mParent != null) {
6996 mWindow.setContainer(mParent.getWindow());
6998 mWindowManager = mWindow.getWindowManager();
6999 mCurrentConfig = config;
7001 mWindow.setColorMode(info.colorMode);
7005 public final IBinder getActivityToken() {
7006 return mParent != null ? mParent.getActivityToken() : mToken;
7009 final void performCreate(Bundle icicle) {
7010 performCreate(icicle, null);
7013 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7014 mCanEnterPictureInPicture = true;
7015 restoreHasCurrentPermissionRequest(icicle);
7016 if (persistentState != null) {
7017 onCreate(icicle, persistentState);
7021 mActivityTransitionState.readState(icicle);
7023 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
7024 com.android.internal.R.styleable.Window_windowNoDisplay, false);
7025 mFragments.dispatchActivityCreated();
7026 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7029 final void performNewIntent(Intent intent) {
7030 mCanEnterPictureInPicture = true;
7031 onNewIntent(intent);
7034 final void performStart() {
7035 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7036 mFragments.noteStateNotSaved();
7038 mFragments.execPendingActions();
7039 mInstrumentation.callActivityOnStart(this);
7041 throw new SuperNotCalledException(
7042 "Activity " + mComponent.toShortString() +
7043 " did not call through to super.onStart()");
7045 mFragments.dispatchStart();
7046 mFragments.reportLoaderStart();
7048 // This property is set for all builds except final release
7049 boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
7050 boolean isAppDebuggable =
7051 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7053 if (isAppDebuggable || isDlwarningEnabled) {
7054 String dlwarning = getDlWarning();
7055 if (dlwarning != null) {
7056 String appName = getApplicationInfo().loadLabel(getPackageManager())
7058 String warning = "Detected problems with app native libraries\n" +
7059 "(please consult log for detail):\n" + dlwarning;
7060 if (isAppDebuggable) {
7061 new AlertDialog.Builder(this).
7063 setMessage(warning).
7064 setPositiveButton(android.R.string.ok, null).
7065 setCancelable(false).
7068 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
7073 mActivityTransitionState.enterReady(this);
7076 final void performRestart() {
7077 mCanEnterPictureInPicture = true;
7078 mFragments.noteStateNotSaved();
7080 if (mToken != null && mParent == null) {
7081 // No need to check mStopped, the roots will check if they were actually stopped.
7082 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
7088 synchronized (mManagedCursors) {
7089 final int N = mManagedCursors.size();
7090 for (int i=0; i<N; i++) {
7091 ManagedCursor mc = mManagedCursors.get(i);
7092 if (mc.mReleased || mc.mUpdated) {
7093 if (!mc.mCursor.requery()) {
7094 if (getApplicationInfo().targetSdkVersion
7095 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
7096 throw new IllegalStateException(
7097 "trying to requery an already closed cursor "
7101 mc.mReleased = false;
7102 mc.mUpdated = false;
7108 mInstrumentation.callActivityOnRestart(this);
7110 throw new SuperNotCalledException(
7111 "Activity " + mComponent.toShortString() +
7112 " did not call through to super.onRestart()");
7118 final void performResume() {
7121 mFragments.execPendingActions();
7123 mLastNonConfigurationInstances = null;
7126 // mResumed is set by the instrumentation
7127 mInstrumentation.callActivityOnResume(this);
7129 throw new SuperNotCalledException(
7130 "Activity " + mComponent.toShortString() +
7131 " did not call through to super.onResume()");
7134 // invisible activities must be finished before onResume() completes
7135 if (!mVisibleFromClient && !mFinished) {
7136 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
7137 if (getApplicationInfo().targetSdkVersion
7138 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
7139 throw new IllegalStateException(
7140 "Activity " + mComponent.toShortString() +
7141 " did not call finish() prior to onResume() completing");
7145 // Now really resume, and install the current status bar and menu.
7148 mFragments.dispatchResume();
7149 mFragments.execPendingActions();
7153 throw new SuperNotCalledException(
7154 "Activity " + mComponent.toShortString() +
7155 " did not call through to super.onPostResume()");
7159 final void performPause() {
7160 mDoReportFullyDrawn = false;
7161 mFragments.dispatchPause();
7165 if (!mCalled && getApplicationInfo().targetSdkVersion
7166 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
7167 throw new SuperNotCalledException(
7168 "Activity " + mComponent.toShortString() +
7169 " did not call through to super.onPause()");
7174 final void performUserLeaving() {
7175 onUserInteraction();
7179 final void performStop(boolean preserveWindow) {
7180 mDoReportFullyDrawn = false;
7181 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
7183 // Disallow entering picture-in-picture after the activity has been stopped
7184 mCanEnterPictureInPicture = false;
7187 if (mWindow != null) {
7188 mWindow.closeAllPanels();
7191 // If we're preserving the window, don't setStoppedState to true, since we
7192 // need the window started immediately again. Stopping the window will
7193 // destroys hardware resources and causes flicker.
7194 if (!preserveWindow && mToken != null && mParent == null) {
7195 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
7198 mFragments.dispatchStop();
7201 mInstrumentation.callActivityOnStop(this);
7203 throw new SuperNotCalledException(
7204 "Activity " + mComponent.toShortString() +
7205 " did not call through to super.onStop()");
7208 synchronized (mManagedCursors) {
7209 final int N = mManagedCursors.size();
7210 for (int i=0; i<N; i++) {
7211 ManagedCursor mc = mManagedCursors.get(i);
7212 if (!mc.mReleased) {
7213 mc.mCursor.deactivate();
7214 mc.mReleased = true;
7224 final void performDestroy() {
7227 mFragments.dispatchDestroy();
7229 mFragments.doLoaderDestroy();
7230 if (mVoiceInteractor != null) {
7231 mVoiceInteractor.detachActivity();
7235 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
7236 Configuration newConfig) {
7237 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7238 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
7240 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7241 if (mWindow != null) {
7242 mWindow.onMultiWindowModeChanged();
7244 onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7247 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
7248 Configuration newConfig) {
7249 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7250 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
7252 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7253 if (mWindow != null) {
7254 mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
7256 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7262 public final boolean isResumed() {
7266 private void storeHasCurrentPermissionRequest(Bundle bundle) {
7267 if (bundle != null && mHasCurrentPermissionsRequest) {
7268 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
7272 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
7273 if (bundle != null) {
7274 mHasCurrentPermissionsRequest = bundle.getBoolean(
7275 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
7279 void dispatchActivityResult(String who, int requestCode,
7280 int resultCode, Intent data) {
7282 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
7283 + ", resCode=" + resultCode + ", data=" + data);
7284 mFragments.noteStateNotSaved();
7286 onActivityResult(requestCode, resultCode, data);
7287 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
7288 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
7289 if (TextUtils.isEmpty(who)) {
7290 dispatchRequestPermissionsResult(requestCode, data);
7292 Fragment frag = mFragments.findFragmentByWho(who);
7294 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
7297 } else if (who.startsWith("@android:view:")) {
7298 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
7299 getActivityToken());
7300 for (ViewRootImpl viewRoot : views) {
7301 if (viewRoot.getView() != null
7302 && viewRoot.getView().dispatchActivityResult(
7303 who, requestCode, resultCode, data)) {
7307 } else if (who.startsWith(AUTO_FILL_AUTH_WHO_PREFIX)) {
7308 Intent resultData = (resultCode == Activity.RESULT_OK) ? data : null;
7309 getAutofillManager().onAuthenticationResult(requestCode, resultData);
7311 Fragment frag = mFragments.findFragmentByWho(who);
7313 frag.onActivityResult(requestCode, resultCode, data);
7319 * Request to put this Activity in a mode where the user is locked to the
7322 * This will prevent the user from launching other apps, going to settings, or reaching the
7323 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
7324 * values permit launching while locked.
7326 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
7327 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
7328 * Lock Task mode. The user will not be able to exit this mode until
7329 * {@link Activity#stopLockTask()} is called.
7331 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
7332 * then the system will prompt the user with a dialog requesting permission to enter
7333 * this mode. When entered through this method the user can exit at any time through
7334 * an action described by the request dialog. Calling stopLockTask will also exit the
7337 * @see android.R.attr#lockTaskMode
7339 public void startLockTask() {
7341 ActivityManager.getService().startLockTaskModeByToken(mToken);
7342 } catch (RemoteException e) {
7347 * Allow the user to switch away from the current task.
7349 * Called to end the mode started by {@link Activity#startLockTask}. This
7350 * can only be called by activities that have successfully called
7351 * startLockTask previously.
7353 * This will allow the user to exit this app and move onto other activities.
7354 * <p>Note: This method should only be called when the activity is user-facing. That is,
7355 * between onResume() and onPause().
7356 * <p>Note: If there are other tasks below this one that are also locked then calling this
7357 * method will immediately finish this task and resume the previous locked one, remaining in
7360 * @see android.R.attr#lockTaskMode
7361 * @see ActivityManager#getLockTaskModeState()
7363 public void stopLockTask() {
7365 ActivityManager.getService().stopLockTaskMode();
7366 } catch (RemoteException e) {
7371 * Shows the user the system defined message for telling the user how to exit
7372 * lock task mode. The task containing this activity must be in lock task mode at the time
7373 * of this call for the message to be displayed.
7375 public void showLockTaskEscapeMessage() {
7377 ActivityManager.getService().showLockTaskEscapeMessage(mToken);
7378 } catch (RemoteException e) {
7383 * Check whether the caption on freeform windows is displayed directly on the content.
7385 * @return True if caption is displayed on content, false if it pushes the content down.
7387 * @see #setOverlayWithDecorCaptionEnabled(boolean)
7390 public boolean isOverlayWithDecorCaptionEnabled() {
7391 return mWindow.isOverlayWithDecorCaptionEnabled();
7395 * Set whether the caption should displayed directly on the content rather than push it down.
7397 * This affects only freeform windows since they display the caption and only the main
7398 * window of the activity. The caption is used to drag the window around and also shows
7399 * maximize and close action buttons.
7402 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
7403 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
7407 * Interface for informing a translucent {@link Activity} once all visible activities below it
7408 * have completed drawing. This is necessary only after an {@link Activity} has been made
7409 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
7410 * translucent again following a call to {@link
7411 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7417 public interface TranslucentConversionListener {
7419 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
7420 * below the top one have been redrawn. Following this callback it is safe to make the top
7421 * Activity translucent because the underlying Activity has been drawn.
7423 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
7424 * occurred waiting for the Activity to complete drawing.
7426 * @see Activity#convertFromTranslucent()
7427 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
7429 public void onTranslucentConversionComplete(boolean drawComplete);
7432 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
7433 mHasCurrentPermissionsRequest = false;
7434 // If the package installer crashed we may have not data - best effort.
7435 String[] permissions = (data != null) ? data.getStringArrayExtra(
7436 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7437 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7438 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7439 onRequestPermissionsResult(requestCode, permissions, grantResults);
7442 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
7443 Fragment fragment) {
7444 // If the package installer crashed we may have not data - best effort.
7445 String[] permissions = (data != null) ? data.getStringArrayExtra(
7446 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7447 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7448 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7449 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
7454 final public void autofillCallbackAuthenticate(int authenticationId, IntentSender intent,
7455 Intent fillInIntent) {
7457 startIntentSenderForResultInner(intent, AUTO_FILL_AUTH_WHO_PREFIX,
7458 authenticationId, fillInIntent, 0, 0, null);
7459 } catch (IntentSender.SendIntentException e) {
7460 Log.e(TAG, "authenticate() failed for intent:" + intent, e);
7466 final public void autofillCallbackResetableStateAvailable() {
7467 mAutoFillResetNeeded = true;
7472 final public boolean autofillCallbackRequestShowFillUi(@NonNull View anchor, int width,
7473 int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter) {
7474 final boolean wasShowing;
7476 if (mAutofillPopupWindow == null) {
7478 mAutofillPopupWindow = new AutofillPopupWindow(presenter);
7480 wasShowing = mAutofillPopupWindow.isShowing();
7482 mAutofillPopupWindow.update(anchor, 0, 0, width, height, anchorBounds);
7484 return !wasShowing && mAutofillPopupWindow.isShowing();
7489 final public boolean autofillCallbackRequestHideFillUi() {
7490 if (mAutofillPopupWindow == null) {
7493 mAutofillPopupWindow.dismiss();
7494 mAutofillPopupWindow = null;
7500 @NonNull public View[] findViewsByAutofillIdTraversal(@NonNull int[] viewIds) {
7501 final View[] views = new View[viewIds.length];
7502 final ArrayList<ViewRootImpl> roots =
7503 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7505 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7506 final View rootView = roots.get(rootNum).getView();
7508 if (rootView != null) {
7509 for (int viewNum = 0; viewNum < viewIds.length; viewNum++) {
7510 if (views[viewNum] == null) {
7511 views[viewNum] = rootView.findViewByAutofillIdTraversal(
7523 @Nullable public View findViewByAutofillIdTraversal(int viewId) {
7524 final ArrayList<ViewRootImpl> roots =
7525 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7526 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7527 final View rootView = roots.get(rootNum).getView();
7529 if (rootView != null) {
7530 final View view = rootView.findViewByAutofillIdTraversal(viewId);
7542 @NonNull public boolean[] getViewVisibility(@NonNull int[] viewIds) {
7543 final boolean[] isVisible = new boolean[viewIds.length];
7544 final View views[] = findViewsByAutofillIdTraversal(viewIds);
7546 for (int i = 0; i < viewIds.length; i++) {
7547 View view = views[i];
7549 isVisible[i] = false;
7553 isVisible[i] = true;
7555 // Check if the view is visible by checking all parents
7557 if (view instanceof DecorView && view.getViewRootImpl() == view.getParent()) {
7561 if (view.getVisibility() != View.VISIBLE) {
7562 isVisible[i] = false;
7566 if (view.getParent() instanceof View) {
7567 view = (View) view.getParent();
7579 public boolean isVisibleForAutofill() {
7584 * If set to true, this indicates to the system that it should never take a
7585 * screenshot of the activity to be used as a representation while it is not in a started state.
7587 * Note that the system may use the window background of the theme instead to represent
7588 * the window when it is not running.
7590 * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
7591 * this only affects the behavior when the activity's screenshot would be used as a
7592 * representation when the activity is not in a started state, i.e. in Overview. The system may
7593 * still take screenshots of the activity in other contexts; for example, when the user takes a
7594 * screenshot of the entire screen, or when the active
7595 * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
7596 * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
7598 * @param disable {@code true} to disable preview screenshots; {@code false} otherwise.
7602 public void setDisablePreviewScreenshots(boolean disable) {
7604 ActivityManager.getService().setDisablePreviewScreenshots(mToken, disable);
7605 } catch (RemoteException e) {
7606 Log.e(TAG, "Failed to call setDisablePreviewScreenshots", e);
7611 * Specifies whether an {@link Activity} should be shown on top of the the lock screen whenever
7612 * the lockscreen is up and the activity is resumed. Normally an activity will be transitioned
7613 * to the stopped state if it is started while the lockscreen is up, but with this flag set the
7614 * activity will remain in the resumed state visible on-top of the lock screen. This value can
7615 * be set as a manifest attribute using {@link android.R.attr#showWhenLocked}.
7617 * @param showWhenLocked {@code true} to show the {@link Activity} on top of the lock screen;
7618 * {@code false} otherwise.
7619 * @see #setTurnScreenOn(boolean)
7620 * @see android.R.attr#turnScreenOn
7621 * @see android.R.attr#showWhenLocked
7623 public void setShowWhenLocked(boolean showWhenLocked) {
7625 ActivityManager.getService().setShowWhenLocked(mToken, showWhenLocked);
7626 } catch (RemoteException e) {
7627 Log.e(TAG, "Failed to call setShowWhenLocked", e);
7632 * Specifies whether the screen should be turned on when the {@link Activity} is resumed.
7633 * Normally an activity will be transitioned to the stopped state if it is started while the
7634 * screen if off, but with this flag set the activity will cause the screen to turn on if the
7635 * activity will be visible and resumed due to the screen coming on. The screen will not be
7636 * turned on if the activity won't be visible after the screen is turned on. This flag is
7637 * normally used in conjunction with the {@link android.R.attr#showWhenLocked} flag to make sure
7638 * the activity is visible after the screen is turned on when the lockscreen is up. In addition,
7639 * if this flag is set and the activity calls {@link
7640 * KeyguardManager#requestDismissKeyguard(Activity, KeyguardManager.KeyguardDismissCallback)}
7641 * the screen will turn on.
7643 * @param turnScreenOn {@code true} to turn on the screen; {@code false} otherwise.
7645 * @see #setShowWhenLocked(boolean)
7646 * @see android.R.attr#turnScreenOn
7647 * @see android.R.attr#showWhenLocked
7649 public void setTurnScreenOn(boolean turnScreenOn) {
7651 ActivityManager.getService().setTurnScreenOn(mToken, turnScreenOn);
7652 } catch (RemoteException e) {
7653 Log.e(TAG, "Failed to call setTurnScreenOn", e);
7657 class HostCallbacks extends FragmentHostCallback<Activity> {
7658 public HostCallbacks() {
7659 super(Activity.this /*activity*/);
7663 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
7664 Activity.this.dump(prefix, fd, writer, args);
7668 public boolean onShouldSaveFragmentState(Fragment fragment) {
7669 return !isFinishing();
7673 public LayoutInflater onGetLayoutInflater() {
7674 final LayoutInflater result = Activity.this.getLayoutInflater();
7675 if (onUseFragmentManagerInflaterFactory()) {
7676 return result.cloneInContext(Activity.this);
7682 public boolean onUseFragmentManagerInflaterFactory() {
7683 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
7684 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
7688 public Activity onGetHost() {
7689 return Activity.this;
7693 public void onInvalidateOptionsMenu() {
7694 Activity.this.invalidateOptionsMenu();
7698 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
7700 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
7704 public void onStartActivityAsUserFromFragment(
7705 Fragment fragment, Intent intent, int requestCode, Bundle options,
7707 Activity.this.startActivityAsUserFromFragment(
7708 fragment, intent, requestCode, options, user);
7712 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
7713 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
7714 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
7715 if (mParent == null) {
7716 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
7717 flagsMask, flagsValues, options);
7718 } else if (options != null) {
7719 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode,
7720 fillInIntent, flagsMask, flagsValues, extraFlags, options);
7725 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
7727 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
7728 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
7729 startActivityForResult(who, intent, requestCode, null);
7733 public boolean onHasWindowAnimations() {
7734 return getWindow() != null;
7738 public int onGetWindowAnimations() {
7739 final Window w = getWindow();
7740 return (w == null) ? 0 : w.getAttributes().windowAnimations;
7744 public void onAttachFragment(Fragment fragment) {
7745 Activity.this.onAttachFragment(fragment);
7750 public <T extends View> T onFindViewById(int id) {
7751 return Activity.this.findViewById(id);
7755 public boolean onHasView() {
7756 final Window w = getWindow();
7757 return (w != null && w.peekDecorView() != null);