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 android.os.Build.VERSION_CODES.O_MR1;
21 import static java.lang.Character.MIN_VALUE;
23 import android.annotation.CallSuper;
24 import android.annotation.DrawableRes;
25 import android.annotation.IdRes;
26 import android.annotation.IntDef;
27 import android.annotation.LayoutRes;
28 import android.annotation.MainThread;
29 import android.annotation.NonNull;
30 import android.annotation.Nullable;
31 import android.annotation.RequiresPermission;
32 import android.annotation.StyleRes;
33 import android.annotation.SystemApi;
34 import android.app.VoiceInteractor.Request;
35 import android.app.admin.DevicePolicyManager;
36 import android.app.assist.AssistContent;
37 import android.content.ComponentCallbacks2;
38 import android.content.ComponentName;
39 import android.content.ContentResolver;
40 import android.content.Context;
41 import android.content.CursorLoader;
42 import android.content.IIntentSender;
43 import android.content.Intent;
44 import android.content.IntentSender;
45 import android.content.SharedPreferences;
46 import android.content.pm.ActivityInfo;
47 import android.content.pm.ApplicationInfo;
48 import android.content.pm.PackageManager;
49 import android.content.pm.PackageManager.NameNotFoundException;
50 import android.content.res.Configuration;
51 import android.content.res.Resources;
52 import android.content.res.TypedArray;
53 import android.database.Cursor;
54 import android.graphics.Bitmap;
55 import android.graphics.Canvas;
56 import android.graphics.Color;
57 import android.graphics.Rect;
58 import android.graphics.drawable.Drawable;
59 import android.media.AudioManager;
60 import android.media.session.MediaController;
61 import android.net.Uri;
62 import android.os.BadParcelableException;
63 import android.os.Build;
64 import android.os.Bundle;
65 import android.os.Handler;
66 import android.os.IBinder;
67 import android.os.Looper;
68 import android.os.Parcelable;
69 import android.os.PersistableBundle;
70 import android.os.RemoteException;
71 import android.os.ServiceManager.ServiceNotFoundException;
72 import android.os.StrictMode;
73 import android.os.SystemProperties;
74 import android.os.UserHandle;
75 import android.text.Selection;
76 import android.text.SpannableStringBuilder;
77 import android.text.TextUtils;
78 import android.text.method.TextKeyListener;
79 import android.transition.Scene;
80 import android.transition.TransitionManager;
81 import android.util.ArrayMap;
82 import android.util.AttributeSet;
83 import android.util.EventLog;
84 import android.util.Log;
85 import android.util.PrintWriterPrinter;
86 import android.util.Slog;
87 import android.util.SparseArray;
88 import android.util.SuperNotCalledException;
89 import android.view.ActionMode;
90 import android.view.ContextMenu;
91 import android.view.ContextMenu.ContextMenuInfo;
92 import android.view.ContextThemeWrapper;
93 import android.view.DragAndDropPermissions;
94 import android.view.DragEvent;
95 import android.view.KeyEvent;
96 import android.view.KeyboardShortcutGroup;
97 import android.view.KeyboardShortcutInfo;
98 import android.view.LayoutInflater;
99 import android.view.Menu;
100 import android.view.MenuInflater;
101 import android.view.MenuItem;
102 import android.view.MotionEvent;
103 import android.view.SearchEvent;
104 import android.view.View;
105 import android.view.View.OnCreateContextMenuListener;
106 import android.view.ViewGroup;
107 import android.view.ViewGroup.LayoutParams;
108 import android.view.ViewManager;
109 import android.view.ViewRootImpl;
110 import android.view.ViewRootImpl.ActivityConfigCallback;
111 import android.view.Window;
112 import android.view.Window.WindowControllerCallback;
113 import android.view.WindowManager;
114 import android.view.WindowManagerGlobal;
115 import android.view.accessibility.AccessibilityEvent;
116 import android.view.autofill.AutofillManager;
117 import android.view.autofill.AutofillManager.AutofillClient;
118 import android.view.autofill.AutofillPopupWindow;
119 import android.view.autofill.IAutofillWindowPresenter;
120 import android.widget.AdapterView;
121 import android.widget.Toast;
122 import android.widget.Toolbar;
124 import com.android.internal.annotations.GuardedBy;
125 import com.android.internal.app.IVoiceInteractor;
126 import com.android.internal.app.ToolbarActionBar;
127 import com.android.internal.app.WindowDecorActionBar;
128 import com.android.internal.policy.DecorView;
129 import com.android.internal.policy.PhoneWindow;
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 mDoReportFullyDrawn = true;
765 private boolean mRestoredFromBundle;
767 /** {@code true} if the activity lifecycle is in a state which supports picture-in-picture.
768 * This only affects the client-side exception, the actual state check still happens in AMS. */
769 private boolean mCanEnterPictureInPicture = false;
770 /** true if the activity is going through a transient pause */
771 /*package*/ boolean mTemporaryPause = false;
772 /** true if the activity is being destroyed in order to recreate it with a new configuration */
773 /*package*/ boolean mChangingConfigurations = false;
774 /*package*/ int mConfigChangeFlags;
775 /*package*/ Configuration mCurrentConfig;
776 private SearchManager mSearchManager;
777 private MenuInflater mMenuInflater;
779 /** The autofill manager. Always access via {@link #getAutofillManager()}. */
780 @Nullable private AutofillManager mAutofillManager;
782 static final class NonConfigurationInstances {
784 HashMap<String, Object> children;
785 FragmentManagerNonConfig fragments;
786 ArrayMap<String, LoaderManager> loaders;
787 VoiceInteractor voiceInteractor;
789 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
791 private Window mWindow;
793 private WindowManager mWindowManager;
794 /*package*/ View mDecor = null;
795 /*package*/ boolean mWindowAdded = false;
796 /*package*/ boolean mVisibleFromServer = false;
797 /*package*/ boolean mVisibleFromClient = true;
798 /*package*/ ActionBar mActionBar = null;
799 private boolean mEnableDefaultActionBarUp;
801 private VoiceInteractor mVoiceInteractor;
803 private CharSequence mTitle;
804 private int mTitleColor = 0;
806 // we must have a handler before the FragmentController is constructed
807 final Handler mHandler = new Handler();
808 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
810 private static final class ManagedCursor {
811 ManagedCursor(Cursor cursor) {
817 private final Cursor mCursor;
818 private boolean mReleased;
819 private boolean mUpdated;
822 @GuardedBy("mManagedCursors")
823 private final ArrayList<ManagedCursor> mManagedCursors = new ArrayList<>();
826 int mResultCode = RESULT_CANCELED;
828 Intent mResultData = null;
830 private TranslucentConversionListener mTranslucentCallback;
831 private boolean mChangeCanvasToTranslucent;
833 private SearchEvent mSearchEvent;
835 private boolean mTitleReady = false;
836 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
838 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
839 private SpannableStringBuilder mDefaultKeySsb = null;
841 private ActivityManager.TaskDescription mTaskDescription =
842 new ActivityManager.TaskDescription();
844 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
846 @SuppressWarnings("unused")
847 private final Object mInstanceTracker = StrictMode.trackActivity(this);
849 private Thread mUiThread;
851 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
852 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
853 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
855 private boolean mHasCurrentPermissionsRequest;
857 private boolean mAutoFillResetNeeded;
859 /** The last autofill id that was returned from {@link #getNextAutofillId()} */
860 private int mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
862 private AutofillPopupWindow mAutofillPopupWindow;
864 private static native String getDlWarning();
866 /** Return the intent that started this activity. */
867 public Intent getIntent() {
872 * Change the intent returned by {@link #getIntent}. This holds a
873 * reference to the given intent; it does not copy it. Often used in
874 * conjunction with {@link #onNewIntent}.
876 * @param newIntent The new Intent object to return from getIntent
881 public void setIntent(Intent newIntent) {
885 /** Return the application that owns this activity. */
886 public final Application getApplication() {
890 /** Is this activity embedded inside of another activity? */
891 public final boolean isChild() {
892 return mParent != null;
895 /** Return the parent activity if this view is an embedded child. */
896 public final Activity getParent() {
900 /** Retrieve the window manager for showing custom windows. */
901 public WindowManager getWindowManager() {
902 return mWindowManager;
906 * Retrieve the current {@link android.view.Window} for the activity.
907 * This can be used to directly access parts of the Window API that
908 * are not available through Activity/Screen.
910 * @return Window The current window, or null if the activity is not
913 public Window getWindow() {
918 * Return the LoaderManager for this activity, creating it if needed.
920 public LoaderManager getLoaderManager() {
921 return mFragments.getLoaderManager();
925 * Calls {@link android.view.Window#getCurrentFocus} on the
926 * Window of this Activity to return the currently focused view.
928 * @return View The current View with focus or null.
931 * @see android.view.Window#getCurrentFocus
934 public View getCurrentFocus() {
935 return mWindow != null ? mWindow.getCurrentFocus() : null;
939 * (Create and) return the autofill manager
941 * @return The autofill manager
943 @NonNull private AutofillManager getAutofillManager() {
944 if (mAutofillManager == null) {
945 mAutofillManager = getSystemService(AutofillManager.class);
948 return mAutofillManager;
952 protected void attachBaseContext(Context newBase) {
953 super.attachBaseContext(newBase);
954 newBase.setAutofillClient(this);
959 public final AutofillClient getAutofillClient() {
964 * Called when the activity is starting. This is where most initialization
965 * should go: calling {@link #setContentView(int)} to inflate the
966 * activity's UI, using {@link #findViewById} to programmatically interact
967 * with widgets in the UI, calling
968 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
969 * cursors for data being displayed, etc.
971 * <p>You can call {@link #finish} from within this function, in
972 * which case onDestroy() will be immediately called without any of the rest
973 * of the activity lifecycle ({@link #onStart}, {@link #onResume},
974 * {@link #onPause}, etc) executing.
976 * <p><em>Derived classes must call through to the super class's
977 * implementation of this method. If they do not, an exception will be
980 * @param savedInstanceState If the activity is being re-initialized after
981 * previously being shut down then this Bundle contains the data it most
982 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
985 * @see #onSaveInstanceState
986 * @see #onRestoreInstanceState
991 protected void onCreate(@Nullable Bundle savedInstanceState) {
992 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
994 if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
995 final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
996 final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
999 if (isTranslucentOrFloating) {
1000 throw new IllegalStateException(
1001 "Only fullscreen opaque activities can request orientation");
1005 if (mLastNonConfigurationInstances != null) {
1006 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
1008 if (mActivityInfo.parentActivityName != null) {
1009 if (mActionBar == null) {
1010 mEnableDefaultActionBarUp = true;
1012 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
1015 if (savedInstanceState != null) {
1016 mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
1017 mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
1018 View.LAST_APP_AUTOFILL_ID);
1020 if (mAutoFillResetNeeded) {
1021 getAutofillManager().onCreate(savedInstanceState);
1024 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
1025 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
1026 ? mLastNonConfigurationInstances.fragments : null);
1028 mFragments.dispatchCreate();
1029 getApplication().dispatchActivityCreated(this, savedInstanceState);
1030 if (mVoiceInteractor != null) {
1031 mVoiceInteractor.attachActivity(this);
1033 mRestoredFromBundle = savedInstanceState != null;
1038 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
1039 * the attribute {@link android.R.attr#persistableMode} set to
1040 * <code>persistAcrossReboots</code>.
1042 * @param savedInstanceState if the activity is being re-initialized after
1043 * previously being shut down then this Bundle contains the data it most
1044 * recently supplied in {@link #onSaveInstanceState}.
1045 * <b><i>Note: Otherwise it is null.</i></b>
1046 * @param persistentState if the activity is being re-initialized after
1047 * previously being shut down or powered off then this Bundle contains the data it most
1048 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
1049 * <b><i>Note: Otherwise it is null.</i></b>
1051 * @see #onCreate(android.os.Bundle)
1053 * @see #onSaveInstanceState
1054 * @see #onRestoreInstanceState
1055 * @see #onPostCreate
1057 public void onCreate(@Nullable Bundle savedInstanceState,
1058 @Nullable PersistableBundle persistentState) {
1059 onCreate(savedInstanceState);
1063 * The hook for {@link ActivityThread} to restore the state of this activity.
1065 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1066 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1068 * @param savedInstanceState contains the saved state
1070 final void performRestoreInstanceState(Bundle savedInstanceState) {
1071 onRestoreInstanceState(savedInstanceState);
1072 restoreManagedDialogs(savedInstanceState);
1076 * The hook for {@link ActivityThread} to restore the state of this activity.
1078 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1079 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1081 * @param savedInstanceState contains the saved state
1082 * @param persistentState contains the persistable saved state
1084 final void performRestoreInstanceState(Bundle savedInstanceState,
1085 PersistableBundle persistentState) {
1086 onRestoreInstanceState(savedInstanceState, persistentState);
1087 if (savedInstanceState != null) {
1088 restoreManagedDialogs(savedInstanceState);
1093 * This method is called after {@link #onStart} when the activity is
1094 * being re-initialized from a previously saved state, given here in
1095 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
1096 * to restore their state, but it is sometimes convenient to do it here
1097 * after all of the initialization has been done or to allow subclasses to
1098 * decide whether to use your default implementation. The default
1099 * implementation of this method performs a restore of any view state that
1100 * had previously been frozen by {@link #onSaveInstanceState}.
1102 * <p>This method is called between {@link #onStart} and
1103 * {@link #onPostCreate}.
1105 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1108 * @see #onPostCreate
1110 * @see #onSaveInstanceState
1112 protected void onRestoreInstanceState(Bundle savedInstanceState) {
1113 if (mWindow != null) {
1114 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1115 if (windowState != null) {
1116 mWindow.restoreHierarchyState(windowState);
1122 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
1123 * created with the attribute {@link android.R.attr#persistableMode} set to
1124 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1125 * came from the restored PersistableBundle first
1126 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1128 * <p>This method is called between {@link #onStart} and
1129 * {@link #onPostCreate}.
1131 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1133 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
1134 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}.
1136 * @see #onRestoreInstanceState(Bundle)
1138 * @see #onPostCreate
1140 * @see #onSaveInstanceState
1142 public void onRestoreInstanceState(Bundle savedInstanceState,
1143 PersistableBundle persistentState) {
1144 if (savedInstanceState != null) {
1145 onRestoreInstanceState(savedInstanceState);
1150 * Restore the state of any saved managed dialogs.
1152 * @param savedInstanceState The bundle to restore from.
1154 private void restoreManagedDialogs(Bundle savedInstanceState) {
1155 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1160 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1161 final int numDialogs = ids.length;
1162 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
1163 for (int i = 0; i < numDialogs; i++) {
1164 final Integer dialogId = ids[i];
1165 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1166 if (dialogState != null) {
1167 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1168 // so tell createDialog() not to do it, otherwise we get an exception
1169 final ManagedDialog md = new ManagedDialog();
1170 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1171 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1172 if (md.mDialog != null) {
1173 mManagedDialogs.put(dialogId, md);
1174 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1175 md.mDialog.onRestoreInstanceState(dialogState);
1181 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1182 final Dialog dialog = onCreateDialog(dialogId, args);
1183 if (dialog == null) {
1186 dialog.dispatchOnCreate(state);
1190 private static String savedDialogKeyFor(int key) {
1191 return SAVED_DIALOG_KEY_PREFIX + key;
1194 private static String savedDialogArgsKeyFor(int key) {
1195 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1199 * Called when activity start-up is complete (after {@link #onStart}
1200 * and {@link #onRestoreInstanceState} have been called). Applications will
1201 * generally not implement this method; it is intended for system
1202 * classes to do final initialization after application code has run.
1204 * <p><em>Derived classes must call through to the super class's
1205 * implementation of this method. If they do not, an exception will be
1208 * @param savedInstanceState If the activity is being re-initialized after
1209 * previously being shut down then this Bundle contains the data it most
1210 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1214 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
1217 onTitleChanged(getTitle(), getTitleColor());
1224 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
1225 * created with the attribute {@link android.R.attr#persistableMode} set to
1226 * <code>persistAcrossReboots</code>.
1228 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1229 * @param persistentState The data caming from the PersistableBundle first
1230 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1234 public void onPostCreate(@Nullable Bundle savedInstanceState,
1235 @Nullable PersistableBundle persistentState) {
1236 onPostCreate(savedInstanceState);
1240 * Called after {@link #onCreate} — or after {@link #onRestart} when
1241 * the activity had been stopped, but is now again being displayed to the
1242 * user. It will be followed by {@link #onResume}.
1244 * <p><em>Derived classes must call through to the super class's
1245 * implementation of this method. If they do not, an exception will be
1253 protected void onStart() {
1254 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
1257 mFragments.doLoaderStart();
1259 getApplication().dispatchActivityStarted(this);
1261 if (mAutoFillResetNeeded) {
1262 AutofillManager afm = getAutofillManager();
1264 afm.onVisibleForAutofill();
1270 * Called after {@link #onStop} when the current activity is being
1271 * re-displayed to the user (the user has navigated back to it). It will
1272 * be followed by {@link #onStart} and then {@link #onResume}.
1274 * <p>For activities that are using raw {@link Cursor} objects (instead of
1275 * creating them through
1276 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1277 * this is usually the place
1278 * where the cursor should be requeried (because you had deactivated it in
1281 * <p><em>Derived classes must call through to the super class's
1282 * implementation of this method. If they do not, an exception will be
1290 protected void onRestart() {
1295 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1296 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1297 * to give the activity a hint that its state is no longer saved -- it will generally
1298 * be called after {@link #onSaveInstanceState} and prior to the activity being
1299 * resumed/started again.
1301 public void onStateNotSaved() {
1305 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
1306 * {@link #onPause}, for your activity to start interacting with the user.
1307 * This is a good place to begin animations, open exclusive-access devices
1308 * (such as the camera), etc.
1310 * <p>Keep in mind that onResume is not the best indicator that your activity
1311 * is visible to the user; a system window such as the keyguard may be in
1312 * front. Use {@link #onWindowFocusChanged} to know for certain that your
1313 * activity is visible to the user (for example, to resume a game).
1315 * <p><em>Derived classes must call through to the super class's
1316 * implementation of this method. If they do not, an exception will be
1319 * @see #onRestoreInstanceState
1321 * @see #onPostResume
1325 protected void onResume() {
1326 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
1327 getApplication().dispatchActivityResumed(this);
1328 mActivityTransitionState.onResume(this, isTopOfTask());
1333 * Called when activity resume is complete (after {@link #onResume} has
1334 * been called). Applications will generally not implement this method;
1335 * it is intended for system classes to do final setup after application
1336 * resume code has run.
1338 * <p><em>Derived classes must call through to the super class's
1339 * implementation of this method. If they do not, an exception will be
1345 protected void onPostResume() {
1346 final Window win = getWindow();
1347 if (win != null) win.makeActive();
1348 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
1352 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
1353 if (mVoiceInteractor != null) {
1354 for (Request activeRequest: mVoiceInteractor.getActiveRequests()) {
1355 activeRequest.cancel();
1356 activeRequest.clear();
1359 if (voiceInteractor == null) {
1360 mVoiceInteractor = null;
1362 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
1368 * Gets the next autofill ID.
1370 * <p>All IDs will be bigger than {@link View#LAST_APP_AUTOFILL_ID}. All IDs returned
1373 * @return A ID that is unique in the activity
1377 public int getNextAutofillId() {
1378 if (mLastAutofillId == Integer.MAX_VALUE - 1) {
1379 mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
1384 return mLastAutofillId;
1388 * Check whether this activity is running as part of a voice interaction with the user.
1389 * If true, it should perform its interaction with the user through the
1390 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
1392 public boolean isVoiceInteraction() {
1393 return mVoiceInteractor != null;
1397 * Like {@link #isVoiceInteraction}, but only returns true if this is also the root
1398 * of a voice interaction. That is, returns true if this activity was directly
1399 * started by the voice interaction service as the initiation of a voice interaction.
1400 * Otherwise, for example if it was started by another activity while under voice
1401 * interaction, returns false.
1403 public boolean isVoiceInteractionRoot() {
1405 return mVoiceInteractor != null
1406 && ActivityManager.getService().isRootVoiceInteraction(mToken);
1407 } catch (RemoteException e) {
1413 * Retrieve the active {@link VoiceInteractor} that the user is going through to
1414 * interact with this activity.
1416 public VoiceInteractor getVoiceInteractor() {
1417 return mVoiceInteractor;
1421 * Queries whether the currently enabled voice interaction service supports returning
1422 * a voice interactor for use by the activity. This is valid only for the duration of the
1425 * @return whether the current voice interaction service supports local voice interaction
1427 public boolean isLocalVoiceInteractionSupported() {
1429 return ActivityManager.getService().supportsLocalVoiceInteraction();
1430 } catch (RemoteException re) {
1436 * Starts a local voice interaction session. When ready,
1437 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
1438 * to the registered voice interaction service.
1439 * @param privateOptions a Bundle of private arguments to the current voice interaction service
1441 public void startLocalVoiceInteraction(Bundle privateOptions) {
1443 ActivityManager.getService().startLocalVoiceInteraction(mToken, privateOptions);
1444 } catch (RemoteException re) {
1449 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
1450 * voice interaction session being started. You can now retrieve a voice interactor using
1451 * {@link #getVoiceInteractor()}.
1453 public void onLocalVoiceInteractionStarted() {
1457 * Callback to indicate that the local voice interaction has stopped either
1458 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
1459 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
1460 * is no longer valid after this.
1462 public void onLocalVoiceInteractionStopped() {
1466 * Request to terminate the current voice interaction that was previously started
1467 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
1468 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
1470 public void stopLocalVoiceInteraction() {
1472 ActivityManager.getService().stopLocalVoiceInteraction(mToken);
1473 } catch (RemoteException re) {
1478 * This is called for activities that set launchMode to "singleTop" in
1479 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
1480 * flag when calling {@link #startActivity}. In either case, when the
1481 * activity is re-launched while at the top of the activity stack instead
1482 * of a new instance of the activity being started, onNewIntent() will be
1483 * called on the existing instance with the Intent that was used to
1486 * <p>An activity will always be paused before receiving a new intent, so
1487 * you can count on {@link #onResume} being called after this method.
1489 * <p>Note that {@link #getIntent} still returns the original Intent. You
1490 * can use {@link #setIntent} to update it to this new Intent.
1492 * @param intent The new intent that was started for the activity.
1498 protected void onNewIntent(Intent intent) {
1502 * The hook for {@link ActivityThread} to save the state of this activity.
1504 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1505 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1507 * @param outState The bundle to save the state to.
1509 final void performSaveInstanceState(Bundle outState) {
1510 onSaveInstanceState(outState);
1511 saveManagedDialogs(outState);
1512 mActivityTransitionState.saveState(outState);
1513 storeHasCurrentPermissionRequest(outState);
1514 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
1518 * The hook for {@link ActivityThread} to save the state of this activity.
1520 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
1521 * and {@link #saveManagedDialogs(android.os.Bundle)}.
1523 * @param outState The bundle to save the state to.
1524 * @param outPersistentState The bundle to save persistent state to.
1526 final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1527 onSaveInstanceState(outState, outPersistentState);
1528 saveManagedDialogs(outState);
1529 storeHasCurrentPermissionRequest(outState);
1530 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
1531 ", " + outPersistentState);
1535 * Called to retrieve per-instance state from an activity before being killed
1536 * so that the state can be restored in {@link #onCreate} or
1537 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
1538 * will be passed to both).
1540 * <p>This method is called before an activity may be killed so that when it
1541 * comes back some time in the future it can restore its state. For example,
1542 * if activity B is launched in front of activity A, and at some point activity
1543 * A is killed to reclaim resources, activity A will have a chance to save the
1544 * current state of its user interface via this method so that when the user
1545 * returns to activity A, the state of the user interface can be restored
1546 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
1548 * <p>Do not confuse this method with activity lifecycle callbacks such as
1549 * {@link #onPause}, which is always called when an activity is being placed
1550 * in the background or on its way to destruction, or {@link #onStop} which
1551 * is called before destruction. One example of when {@link #onPause} and
1552 * {@link #onStop} is called and not this method is when a user navigates back
1553 * from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
1554 * on B because that particular instance will never be restored, so the
1555 * system avoids calling it. An example when {@link #onPause} is called and
1556 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
1557 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
1558 * killed during the lifetime of B since the state of the user interface of
1559 * A will stay intact.
1561 * <p>The default implementation takes care of most of the UI per-instance
1562 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
1563 * view in the hierarchy that has an id, and by saving the id of the currently
1564 * focused view (all of which is restored by the default implementation of
1565 * {@link #onRestoreInstanceState}). If you override this method to save additional
1566 * information not captured by each individual view, you will likely want to
1567 * call through to the default implementation, otherwise be prepared to save
1568 * all of the state of each view yourself.
1570 * <p>If called, this method will occur before {@link #onStop}. There are
1571 * no guarantees about whether it will occur before or after {@link #onPause}.
1573 * @param outState Bundle in which to place your saved state.
1576 * @see #onRestoreInstanceState
1579 protected void onSaveInstanceState(Bundle outState) {
1580 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
1582 outState.putInt(LAST_AUTOFILL_ID, mLastAutofillId);
1583 Parcelable p = mFragments.saveAllState();
1585 outState.putParcelable(FRAGMENTS_TAG, p);
1587 if (mAutoFillResetNeeded) {
1588 outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
1589 getAutofillManager().onSaveInstanceState(outState);
1591 getApplication().dispatchActivitySaveInstanceState(this, outState);
1595 * This is the same as {@link #onSaveInstanceState} but is called for activities
1596 * created with the attribute {@link android.R.attr#persistableMode} set to
1597 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1598 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
1599 * the first time that this activity is restarted following the next device reboot.
1601 * @param outState Bundle in which to place your saved state.
1602 * @param outPersistentState State which will be saved across reboots.
1604 * @see #onSaveInstanceState(Bundle)
1606 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
1609 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
1610 onSaveInstanceState(outState);
1614 * Save the state of any managed dialogs.
1616 * @param outState place to store the saved state.
1618 private void saveManagedDialogs(Bundle outState) {
1619 if (mManagedDialogs == null) {
1623 final int numDialogs = mManagedDialogs.size();
1624 if (numDialogs == 0) {
1628 Bundle dialogState = new Bundle();
1630 int[] ids = new int[mManagedDialogs.size()];
1632 // save each dialog's bundle, gather the ids
1633 for (int i = 0; i < numDialogs; i++) {
1634 final int key = mManagedDialogs.keyAt(i);
1636 final ManagedDialog md = mManagedDialogs.valueAt(i);
1637 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
1638 if (md.mArgs != null) {
1639 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
1643 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
1644 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
1649 * Called as part of the activity lifecycle when an activity is going into
1650 * the background, but has not (yet) been killed. The counterpart to
1651 * {@link #onResume}.
1653 * <p>When activity B is launched in front of activity A, this callback will
1654 * be invoked on A. B will not be created until A's {@link #onPause} returns,
1655 * so be sure to not do anything lengthy here.
1657 * <p>This callback is mostly used for saving any persistent state the
1658 * activity is editing, to present a "edit in place" model to the user and
1659 * making sure nothing is lost if there are not enough resources to start
1660 * the new activity without first killing this one. This is also a good
1661 * place to do things like stop animations and other things that consume a
1662 * noticeable amount of CPU in order to make the switch to the next activity
1663 * as fast as possible, or to close resources that are exclusive access
1664 * such as the camera.
1666 * <p>In situations where the system needs more memory it may kill paused
1667 * processes to reclaim resources. Because of this, you should be sure
1668 * that all of your state is saved by the time you return from
1669 * this function. In general {@link #onSaveInstanceState} is used to save
1670 * per-instance state in the activity and this method is used to store
1671 * global persistent data (in content providers, files, etc.)
1673 * <p>After receiving this call you will usually receive a following call
1674 * to {@link #onStop} (after the next activity has been resumed and
1675 * displayed), however in some cases there will be a direct call back to
1676 * {@link #onResume} without going through the stopped state.
1678 * <p><em>Derived classes must call through to the super class's
1679 * implementation of this method. If they do not, an exception will be
1683 * @see #onSaveInstanceState
1687 protected void onPause() {
1688 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
1689 getApplication().dispatchActivityPaused(this);
1694 * Called as part of the activity lifecycle when an activity is about to go
1695 * into the background as the result of user choice. For example, when the
1696 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
1697 * when an incoming phone call causes the in-call Activity to be automatically
1698 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
1699 * the activity being interrupted. In cases when it is invoked, this method
1700 * is called right before the activity's {@link #onPause} callback.
1702 * <p>This callback and {@link #onUserInteraction} are intended to help
1703 * activities manage status bar notifications intelligently; specifically,
1704 * for helping activities determine the proper time to cancel a notfication.
1706 * @see #onUserInteraction()
1708 protected void onUserLeaveHint() {
1712 * Generate a new thumbnail for this activity. This method is called before
1713 * pausing the activity, and should draw into <var>outBitmap</var> the
1714 * imagery for the desired thumbnail in the dimensions of that bitmap. It
1715 * can use the given <var>canvas</var>, which is configured to draw into the
1716 * bitmap, for rendering if desired.
1718 * <p>The default implementation returns fails and does not draw a thumbnail;
1719 * this will result in the platform creating its own thumbnail if needed.
1721 * @param outBitmap The bitmap to contain the thumbnail.
1722 * @param canvas Can be used to render into the bitmap.
1724 * @return Return true if you have drawn into the bitmap; otherwise after
1725 * you return it will be filled with a default thumbnail.
1727 * @see #onCreateDescription
1728 * @see #onSaveInstanceState
1731 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
1736 * Generate a new description for this activity. This method is called
1737 * before pausing the activity and can, if desired, return some textual
1738 * description of its current state to be displayed to the user.
1740 * <p>The default implementation returns null, which will cause you to
1741 * inherit the description from the previous activity. If all activities
1742 * return null, generally the label of the top activity will be used as the
1745 * @return A description of what the user is doing. It should be short and
1746 * sweet (only a few words).
1748 * @see #onCreateThumbnail
1749 * @see #onSaveInstanceState
1753 public CharSequence onCreateDescription() {
1758 * This is called when the user is requesting an assist, to build a full
1759 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
1760 * application. You can override this method to place into the bundle anything
1761 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
1762 * of the assist Intent.
1764 * <p>This function will be called after any global assist callbacks that had
1765 * been registered with {@link Application#registerOnProvideAssistDataListener
1766 * Application.registerOnProvideAssistDataListener}.
1768 public void onProvideAssistData(Bundle data) {
1772 * This is called when the user is requesting an assist, to provide references
1773 * to content related to the current activity. Before being called, the
1774 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
1775 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
1776 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
1777 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
1778 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
1780 * <p>Custom implementation may adjust the content intent to better reflect the top-level
1781 * context of the activity, and fill in its ClipData with additional content of
1782 * interest that the user is currently viewing. For example, an image gallery application
1783 * that has launched in to an activity allowing the user to swipe through pictures should
1784 * modify the intent to reference the current image they are looking it; such an
1785 * application when showing a list of pictures should add a ClipData that has
1786 * references to all of the pictures currently visible on screen.</p>
1788 * @param outContent The assist content to return.
1790 public void onProvideAssistContent(AssistContent outContent) {
1794 * Request the Keyboard Shortcuts screen to show up. This will trigger
1795 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
1797 public final void requestShowKeyboardShortcuts() {
1798 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
1799 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1800 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1804 * Dismiss the Keyboard Shortcuts screen.
1806 public final void dismissKeyboardShortcutsHelper() {
1807 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
1808 intent.setPackage(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME);
1809 sendBroadcastAsUser(intent, UserHandle.SYSTEM);
1813 public void onProvideKeyboardShortcuts(
1814 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
1818 KeyboardShortcutGroup group = null;
1819 int menuSize = menu.size();
1820 for (int i = 0; i < menuSize; ++i) {
1821 final MenuItem item = menu.getItem(i);
1822 final CharSequence title = item.getTitle();
1823 final char alphaShortcut = item.getAlphabeticShortcut();
1824 final int alphaModifiers = item.getAlphabeticModifiers();
1825 if (title != null && alphaShortcut != MIN_VALUE) {
1826 if (group == null) {
1827 final int resource = mApplication.getApplicationInfo().labelRes;
1828 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
1830 group.addItem(new KeyboardShortcutInfo(
1831 title, alphaShortcut, alphaModifiers));
1834 if (group != null) {
1840 * Ask to have the current assistant shown to the user. This only works if the calling
1841 * activity is the current foreground activity. It is the same as calling
1842 * {@link android.service.voice.VoiceInteractionService#showSession
1843 * VoiceInteractionService.showSession} and requesting all of the possible context.
1844 * The receiver will always see
1845 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
1846 * @return Returns true if the assistant was successfully invoked, else false. For example
1847 * false will be returned if the caller is not the current top activity.
1849 public boolean showAssist(Bundle args) {
1851 return ActivityManager.getService().showAssistFromActivity(mToken, args);
1852 } catch (RemoteException e) {
1858 * Called when you are no longer visible to the user. You will next
1859 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
1860 * depending on later user activity.
1862 * <p><em>Derived classes must call through to the super class's
1863 * implementation of this method. If they do not, an exception will be
1868 * @see #onSaveInstanceState
1872 protected void onStop() {
1873 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
1874 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
1875 mActivityTransitionState.onStop();
1876 getApplication().dispatchActivityStopped(this);
1877 mTranslucentCallback = null;
1880 if (isFinishing()) {
1881 if (mAutoFillResetNeeded) {
1882 getAutofillManager().commit();
1883 } else if (mIntent != null
1884 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
1885 // Activity was launched when user tapped a link in the Autofill Save UI - since
1886 // user launched another activity, the Save UI should not be restored when this
1887 // activity is finished.
1888 getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_CANCEL,
1889 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
1895 * Perform any final cleanup before an activity is destroyed. This can
1896 * happen either because the activity is finishing (someone called
1897 * {@link #finish} on it, or because the system is temporarily destroying
1898 * this instance of the activity to save space. You can distinguish
1899 * between these two scenarios with the {@link #isFinishing} method.
1901 * <p><em>Note: do not count on this method being called as a place for
1902 * saving data! For example, if an activity is editing data in a content
1903 * provider, those edits should be committed in either {@link #onPause} or
1904 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
1905 * free resources like threads that are associated with an activity, so
1906 * that a destroyed activity does not leave such things around while the
1907 * rest of its application is still running. There are situations where
1908 * the system will simply kill the activity's hosting process without
1909 * calling this method (or any others) in it, so it should not be used to
1910 * do things that are intended to remain around after the process goes
1913 * <p><em>Derived classes must call through to the super class's
1914 * implementation of this method. If they do not, an exception will be
1923 protected void onDestroy() {
1924 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
1927 // dismiss any dialogs we are managing.
1928 if (mManagedDialogs != null) {
1929 final int numDialogs = mManagedDialogs.size();
1930 for (int i = 0; i < numDialogs; i++) {
1931 final ManagedDialog md = mManagedDialogs.valueAt(i);
1932 if (md.mDialog.isShowing()) {
1933 md.mDialog.dismiss();
1936 mManagedDialogs = null;
1939 // close any cursors we are managing.
1940 synchronized (mManagedCursors) {
1941 int numCursors = mManagedCursors.size();
1942 for (int i = 0; i < numCursors; i++) {
1943 ManagedCursor c = mManagedCursors.get(i);
1948 mManagedCursors.clear();
1951 // Close any open search dialog
1952 if (mSearchManager != null) {
1953 mSearchManager.stopSearch();
1956 if (mActionBar != null) {
1957 mActionBar.onDestroy();
1960 getApplication().dispatchActivityDestroyed(this);
1964 * Report to the system that your app is now fully drawn, purely for diagnostic
1965 * purposes (calling it does not impact the visible behavior of the activity).
1966 * This is only used to help instrument application launch times, so that the
1967 * app can report when it is fully in a usable state; without this, the only thing
1968 * the system itself can determine is the point at which the activity's window
1969 * is <em>first</em> drawn and displayed. To participate in app launch time
1970 * measurement, you should always call this method after first launch (when
1971 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
1972 * entirely drawn your UI and populated with all of the significant data. You
1973 * can safely call this method any time after first launch as well, in which case
1974 * it will simply be ignored.
1976 public void reportFullyDrawn() {
1977 if (mDoReportFullyDrawn) {
1978 mDoReportFullyDrawn = false;
1980 ActivityManager.getService().reportActivityFullyDrawn(mToken, mRestoredFromBundle);
1981 } catch (RemoteException e) {
1987 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
1988 * visa-versa. This method provides the same configuration that will be sent in the following
1989 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
1991 * @see android.R.attr#resizeableActivity
1993 * @param isInMultiWindowMode True if the activity is in multi-window mode.
1994 * @param newConfig The new configuration of the activity with the state
1995 * {@param isInMultiWindowMode}.
1997 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
1998 // Left deliberately empty. There should be no side effects if a direct
1999 // subclass of Activity does not call super.
2000 onMultiWindowModeChanged(isInMultiWindowMode);
2004 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
2007 * @see android.R.attr#resizeableActivity
2009 * @param isInMultiWindowMode True if the activity is in multi-window mode.
2011 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
2014 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
2015 // Left deliberately empty. There should be no side effects if a direct
2016 // subclass of Activity does not call super.
2020 * Returns true if the activity is currently in multi-window mode.
2021 * @see android.R.attr#resizeableActivity
2023 * @return True if the activity is in multi-window mode.
2025 public boolean isInMultiWindowMode() {
2027 return ActivityManager.getService().isInMultiWindowMode(mToken);
2028 } catch (RemoteException e) {
2034 * Called by the system when the activity changes to and from picture-in-picture mode. This
2035 * method provides the same configuration that will be sent in the following
2036 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2038 * @see android.R.attr#supportsPictureInPicture
2040 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2041 * @param newConfig The new configuration of the activity with the state
2042 * {@param isInPictureInPictureMode}.
2044 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2045 Configuration newConfig) {
2046 // Left deliberately empty. There should be no side effects if a direct
2047 // subclass of Activity does not call super.
2048 onPictureInPictureModeChanged(isInPictureInPictureMode);
2052 * Called by the system when the activity changes to and from picture-in-picture mode.
2054 * @see android.R.attr#supportsPictureInPicture
2056 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2058 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
2061 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
2062 // Left deliberately empty. There should be no side effects if a direct
2063 // subclass of Activity does not call super.
2067 * Returns true if the activity is currently in picture-in-picture mode.
2068 * @see android.R.attr#supportsPictureInPicture
2070 * @return True if the activity is in picture-in-picture mode.
2072 public boolean isInPictureInPictureMode() {
2074 return ActivityManager.getService().isInPictureInPictureMode(mToken);
2075 } catch (RemoteException e) {
2081 * Puts the activity in picture-in-picture mode if possible in the current system state. Any
2082 * prior calls to {@link #setPictureInPictureParams(PictureInPictureParams)} will still apply
2083 * when entering picture-in-picture through this call.
2085 * @see #enterPictureInPictureMode(PictureInPictureParams)
2086 * @see android.R.attr#supportsPictureInPicture
2089 public void enterPictureInPictureMode() {
2090 enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
2095 public boolean enterPictureInPictureMode(@NonNull PictureInPictureArgs args) {
2096 return enterPictureInPictureMode(PictureInPictureArgs.convert(args));
2100 * Puts the activity in picture-in-picture mode if possible in the current system state. The
2101 * set parameters in {@param params} will be combined with the parameters from prior calls to
2102 * {@link #setPictureInPictureParams(PictureInPictureParams)}.
2104 * The system may disallow entering picture-in-picture in various cases, including when the
2105 * activity is not visible, if the screen is locked or if the user has an activity pinned.
2107 * @see android.R.attr#supportsPictureInPicture
2108 * @see PictureInPictureParams
2110 * @param params non-null parameters to be combined with previously set parameters when entering
2111 * picture-in-picture.
2113 * @return true if the system puts this activity into picture-in-picture mode or was already
2114 * in picture-in-picture mode (@see {@link #isInPictureInPictureMode())
2116 public boolean enterPictureInPictureMode(@NonNull PictureInPictureParams params) {
2118 if (params == null) {
2119 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2121 if (!mCanEnterPictureInPicture) {
2122 throw new IllegalStateException("Activity must be resumed to enter"
2123 + " picture-in-picture");
2125 return ActivityManagerNative.getDefault().enterPictureInPictureMode(mToken, params);
2126 } catch (RemoteException e) {
2133 public void setPictureInPictureArgs(@NonNull PictureInPictureArgs args) {
2134 setPictureInPictureParams(PictureInPictureArgs.convert(args));
2138 * Updates the properties of the picture-in-picture activity, or sets it to be used later when
2139 * {@link #enterPictureInPictureMode()} is called.
2141 * @param params the new parameters for the picture-in-picture.
2143 public void setPictureInPictureParams(@NonNull PictureInPictureParams params) {
2145 if (params == null) {
2146 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2148 ActivityManagerNative.getDefault().setPictureInPictureParams(mToken, params);
2149 } catch (RemoteException e) {
2154 * Return the number of actions that will be displayed in the picture-in-picture UI when the
2155 * user interacts with the activity currently in picture-in-picture mode. This number may change
2156 * if the global configuration changes (ie. if the device is plugged into an external display),
2157 * but will always be larger than three.
2159 public int getMaxNumPictureInPictureActions() {
2161 return ActivityManagerNative.getDefault().getMaxNumPictureInPictureActions(mToken);
2162 } catch (RemoteException e) {
2167 void dispatchMovedToDisplay(int displayId, Configuration config) {
2168 updateDisplay(displayId);
2169 onMovedToDisplay(displayId, config);
2173 * Called by the system when the activity is moved from one display to another without
2174 * recreation. This means that this activity is declared to handle all changes to configuration
2175 * that happened when it was switched to another display, so it wasn't destroyed and created
2178 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
2179 * applied configuration actually changed. It is up to app developer to choose whether to handle
2180 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
2183 * <p>Use this callback to track changes to the displays if some activity functionality relies
2184 * on an association with some display properties.
2186 * @param displayId The id of the display to which activity was moved.
2187 * @param config Configuration of the activity resources on new display after move.
2189 * @see #onConfigurationChanged(Configuration)
2190 * @see View#onMovedToDisplay(int, Configuration)
2193 public void onMovedToDisplay(int displayId, Configuration config) {
2197 * Called by the system when the device configuration changes while your
2198 * activity is running. Note that this will <em>only</em> be called if
2199 * you have selected configurations you would like to handle with the
2200 * {@link android.R.attr#configChanges} attribute in your manifest. If
2201 * any configuration change occurs that is not selected to be reported
2202 * by that attribute, then instead of reporting it the system will stop
2203 * and restart the activity (to have it launched with the new
2206 * <p>At the time that this function has been called, your Resources
2207 * object will have been updated to return resource values matching the
2208 * new configuration.
2210 * @param newConfig The new device configuration.
2212 public void onConfigurationChanged(Configuration newConfig) {
2213 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
2216 mFragments.dispatchConfigurationChanged(newConfig);
2218 if (mWindow != null) {
2219 // Pass the configuration changed event to the window
2220 mWindow.onConfigurationChanged(newConfig);
2223 if (mActionBar != null) {
2224 // Do this last; the action bar will need to access
2225 // view changes from above.
2226 mActionBar.onConfigurationChanged(newConfig);
2231 * If this activity is being destroyed because it can not handle a
2232 * configuration parameter being changed (and thus its
2233 * {@link #onConfigurationChanged(Configuration)} method is
2234 * <em>not</em> being called), then you can use this method to discover
2235 * the set of changes that have occurred while in the process of being
2236 * destroyed. Note that there is no guarantee that these will be
2237 * accurate (other changes could have happened at any time), so you should
2238 * only use this as an optimization hint.
2240 * @return Returns a bit field of the configuration parameters that are
2241 * changing, as defined by the {@link android.content.res.Configuration}
2244 public int getChangingConfigurations() {
2245 return mConfigChangeFlags;
2249 * Retrieve the non-configuration instance data that was previously
2250 * returned by {@link #onRetainNonConfigurationInstance()}. This will
2251 * be available from the initial {@link #onCreate} and
2252 * {@link #onStart} calls to the new instance, allowing you to extract
2253 * any useful dynamic state from the previous instance.
2255 * <p>Note that the data you retrieve here should <em>only</em> be used
2256 * as an optimization for handling configuration changes. You should always
2257 * be able to handle getting a null pointer back, and an activity must
2258 * still be able to restore itself to its previous state (through the
2259 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2260 * function returns null.
2262 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2263 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2264 * available on older platforms through the Android support libraries.
2266 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
2269 public Object getLastNonConfigurationInstance() {
2270 return mLastNonConfigurationInstances != null
2271 ? mLastNonConfigurationInstances.activity : null;
2275 * Called by the system, as part of destroying an
2276 * activity due to a configuration change, when it is known that a new
2277 * instance will immediately be created for the new configuration. You
2278 * can return any object you like here, including the activity instance
2279 * itself, which can later be retrieved by calling
2280 * {@link #getLastNonConfigurationInstance()} in the new activity
2283 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2284 * or later, consider instead using a {@link Fragment} with
2285 * {@link Fragment#setRetainInstance(boolean)
2286 * Fragment.setRetainInstance(boolean}.</em>
2288 * <p>This function is called purely as an optimization, and you must
2289 * not rely on it being called. When it is called, a number of guarantees
2290 * will be made to help optimize configuration switching:
2292 * <li> The function will be called between {@link #onStop} and
2293 * {@link #onDestroy}.
2294 * <li> A new instance of the activity will <em>always</em> be immediately
2295 * created after this one's {@link #onDestroy()} is called. In particular,
2296 * <em>no</em> messages will be dispatched during this time (when the returned
2297 * object does not have an activity to be associated with).
2298 * <li> The object you return here will <em>always</em> be available from
2299 * the {@link #getLastNonConfigurationInstance()} method of the following
2300 * activity instance as described there.
2303 * <p>These guarantees are designed so that an activity can use this API
2304 * to propagate extensive state from the old to new activity instance, from
2305 * loaded bitmaps, to network connections, to evenly actively running
2306 * threads. Note that you should <em>not</em> propagate any data that
2307 * may change based on the configuration, including any data loaded from
2308 * resources such as strings, layouts, or drawables.
2310 * <p>The guarantee of no message handling during the switch to the next
2311 * activity simplifies use with active objects. For example if your retained
2312 * state is an {@link android.os.AsyncTask} you are guaranteed that its
2313 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
2314 * not be called from the call here until you execute the next instance's
2315 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
2316 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
2317 * running in a separate thread.)
2319 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
2320 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
2321 * available on older platforms through the Android support libraries.
2323 * @return any Object holding the desired state to propagate to the
2324 * next activity instance
2326 public Object onRetainNonConfigurationInstance() {
2331 * Retrieve the non-configuration instance data that was previously
2332 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
2333 * be available from the initial {@link #onCreate} and
2334 * {@link #onStart} calls to the new instance, allowing you to extract
2335 * any useful dynamic state from the previous instance.
2337 * <p>Note that the data you retrieve here should <em>only</em> be used
2338 * as an optimization for handling configuration changes. You should always
2339 * be able to handle getting a null pointer back, and an activity must
2340 * still be able to restore itself to its previous state (through the
2341 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
2342 * function returns null.
2344 * @return Returns the object previously returned by
2345 * {@link #onRetainNonConfigurationChildInstances()}
2348 HashMap<String, Object> getLastNonConfigurationChildInstances() {
2349 return mLastNonConfigurationInstances != null
2350 ? mLastNonConfigurationInstances.children : null;
2354 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
2355 * it should return either a mapping from child activity id strings to arbitrary objects,
2356 * or null. This method is intended to be used by Activity framework subclasses that control a
2357 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
2358 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
2361 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
2365 NonConfigurationInstances retainNonConfigurationInstances() {
2366 Object activity = onRetainNonConfigurationInstance();
2367 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
2368 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
2370 // We're already stopped but we've been asked to retain.
2371 // Our fragments are taken care of but we need to mark the loaders for retention.
2372 // In order to do this correctly we need to restart the loaders first before
2373 // handing them off to the next activity.
2374 mFragments.doLoaderStart();
2375 mFragments.doLoaderStop(true);
2376 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
2378 if (activity == null && children == null && fragments == null && loaders == null
2379 && mVoiceInteractor == null) {
2383 NonConfigurationInstances nci = new NonConfigurationInstances();
2384 nci.activity = activity;
2385 nci.children = children;
2386 nci.fragments = fragments;
2387 nci.loaders = loaders;
2388 if (mVoiceInteractor != null) {
2389 mVoiceInteractor.retainInstance();
2390 nci.voiceInteractor = mVoiceInteractor;
2395 public void onLowMemory() {
2396 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
2398 mFragments.dispatchLowMemory();
2401 public void onTrimMemory(int level) {
2402 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
2404 mFragments.dispatchTrimMemory(level);
2408 * Return the FragmentManager for interacting with fragments associated
2409 * with this activity.
2411 public FragmentManager getFragmentManager() {
2412 return mFragments.getFragmentManager();
2416 * Called when a Fragment is being attached to this activity, immediately
2417 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
2418 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
2420 public void onAttachFragment(Fragment fragment) {
2425 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2426 * that gives the resulting {@link Cursor} to call
2427 * {@link #startManagingCursor} so that the activity will manage its
2428 * lifecycle for you.
2430 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2431 * or later, consider instead using {@link LoaderManager} instead, available
2432 * via {@link #getLoaderManager()}.</em>
2434 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2435 * this method, because the activity will do that for you at the appropriate time. However, if
2436 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2437 * not</em> automatically close the cursor and, in that case, you must call
2438 * {@link Cursor#close()}.</p>
2440 * @param uri The URI of the content provider to query.
2441 * @param projection List of columns to return.
2442 * @param selection SQL WHERE clause.
2443 * @param sortOrder SQL ORDER BY clause.
2445 * @return The Cursor that was returned by query().
2447 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2448 * @see #startManagingCursor
2451 * @deprecated Use {@link CursorLoader} instead.
2454 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2456 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
2458 startManagingCursor(c);
2465 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
2466 * that gives the resulting {@link Cursor} to call
2467 * {@link #startManagingCursor} so that the activity will manage its
2468 * lifecycle for you.
2470 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2471 * or later, consider instead using {@link LoaderManager} instead, available
2472 * via {@link #getLoaderManager()}.</em>
2474 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
2475 * this method, because the activity will do that for you at the appropriate time. However, if
2476 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
2477 * not</em> automatically close the cursor and, in that case, you must call
2478 * {@link Cursor#close()}.</p>
2480 * @param uri The URI of the content provider to query.
2481 * @param projection List of columns to return.
2482 * @param selection SQL WHERE clause.
2483 * @param selectionArgs The arguments to selection, if any ?s are pesent
2484 * @param sortOrder SQL ORDER BY clause.
2486 * @return The Cursor that was returned by query().
2488 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
2489 * @see #startManagingCursor
2491 * @deprecated Use {@link CursorLoader} instead.
2494 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
2495 String[] selectionArgs, String sortOrder) {
2496 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
2498 startManagingCursor(c);
2504 * This method allows the activity to take care of managing the given
2505 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
2506 * That is, when the activity is stopped it will automatically call
2507 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
2508 * it will call {@link Cursor#requery} for you. When the activity is
2509 * destroyed, all managed Cursors will be closed automatically.
2511 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
2512 * or later, consider instead using {@link LoaderManager} instead, available
2513 * via {@link #getLoaderManager()}.</em>
2515 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
2516 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
2517 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
2518 * <em>will not</em> automatically close the cursor and, in that case, you must call
2519 * {@link Cursor#close()}.</p>
2521 * @param c The Cursor to be managed.
2523 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
2524 * @see #stopManagingCursor
2526 * @deprecated Use the new {@link android.content.CursorLoader} class with
2527 * {@link LoaderManager} instead; this is also
2528 * available on older platforms through the Android compatibility package.
2531 public void startManagingCursor(Cursor c) {
2532 synchronized (mManagedCursors) {
2533 mManagedCursors.add(new ManagedCursor(c));
2538 * Given a Cursor that was previously given to
2539 * {@link #startManagingCursor}, stop the activity's management of that
2542 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
2543 * the system <em>will not</em> automatically close the cursor and you must call
2544 * {@link Cursor#close()}.</p>
2546 * @param c The Cursor that was being managed.
2548 * @see #startManagingCursor
2550 * @deprecated Use the new {@link android.content.CursorLoader} class with
2551 * {@link LoaderManager} instead; this is also
2552 * available on older platforms through the Android compatibility package.
2555 public void stopManagingCursor(Cursor c) {
2556 synchronized (mManagedCursors) {
2557 final int N = mManagedCursors.size();
2558 for (int i=0; i<N; i++) {
2559 ManagedCursor mc = mManagedCursors.get(i);
2560 if (mc.mCursor == c) {
2561 mManagedCursors.remove(i);
2569 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
2574 public void setPersistent(boolean isPersistent) {
2578 * Finds a view that was identified by the {@code android:id} XML attribute
2579 * that was processed in {@link #onCreate}.
2581 * <strong>Note:</strong> In most cases -- depending on compiler support --
2582 * the resulting view is automatically cast to the target class type. If
2583 * the target class type is unconstrained, an explicit cast may be
2586 * @param id the ID to search for
2587 * @return a view with given ID if found, or {@code null} otherwise
2588 * @see View#findViewById(int)
2591 public <T extends View> T findViewById(@IdRes int id) {
2592 return getWindow().findViewById(id);
2596 * Retrieve a reference to this activity's ActionBar.
2598 * @return The Activity's ActionBar, or null if it does not have one.
2601 public ActionBar getActionBar() {
2602 initWindowDecorActionBar();
2607 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
2610 * <p>When set to a non-null value the {@link #getActionBar()} method will return
2611 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
2612 * a traditional window decor action bar. The toolbar's menu will be populated with the
2613 * Activity's options menu and the navigation button will be wired through the standard
2614 * {@link android.R.id#home home} menu select action.</p>
2616 * <p>In order to use a Toolbar within the Activity's window content the application
2617 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
2619 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
2621 public void setActionBar(@Nullable Toolbar toolbar) {
2622 final ActionBar ab = getActionBar();
2623 if (ab instanceof WindowDecorActionBar) {
2624 throw new IllegalStateException("This Activity already has an action bar supplied " +
2625 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
2626 "android:windowActionBar to false in your theme to use a Toolbar instead.");
2629 // If we reach here then we're setting a new action bar
2630 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
2631 mMenuInflater = null;
2633 // If we have an action bar currently, destroy it
2638 if (toolbar != null) {
2639 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
2641 mWindow.setCallback(tbab.getWrappedWindowCallback());
2644 // Re-set the original window callback since we may have already set a Toolbar wrapper
2645 mWindow.setCallback(this);
2648 invalidateOptionsMenu();
2652 * Creates a new ActionBar, locates the inflated ActionBarView,
2653 * initializes the ActionBar with the view, and sets mActionBar.
2655 private void initWindowDecorActionBar() {
2656 Window window = getWindow();
2658 // Initializing the window decor can change window feature flags.
2659 // Make sure that we have the correct set before performing the test below.
2660 window.getDecorView();
2662 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
2666 mActionBar = new WindowDecorActionBar(this);
2667 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
2669 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
2670 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
2674 * Set the activity content from a layout resource. The resource will be
2675 * inflated, adding all top-level views to the activity.
2677 * @param layoutResID Resource ID to be inflated.
2679 * @see #setContentView(android.view.View)
2680 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2682 public void setContentView(@LayoutRes int layoutResID) {
2683 getWindow().setContentView(layoutResID);
2684 initWindowDecorActionBar();
2688 * Set the activity content to an explicit view. This view is placed
2689 * directly into the activity's view hierarchy. It can itself be a complex
2690 * view hierarchy. When calling this method, the layout parameters of the
2691 * specified view are ignored. Both the width and the height of the view are
2692 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
2693 * your own layout parameters, invoke
2694 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
2697 * @param view The desired content to display.
2699 * @see #setContentView(int)
2700 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
2702 public void setContentView(View view) {
2703 getWindow().setContentView(view);
2704 initWindowDecorActionBar();
2708 * Set the activity content to an explicit view. This view is placed
2709 * directly into the activity's view hierarchy. It can itself be a complex
2712 * @param view The desired content to display.
2713 * @param params Layout parameters for the view.
2715 * @see #setContentView(android.view.View)
2716 * @see #setContentView(int)
2718 public void setContentView(View view, ViewGroup.LayoutParams params) {
2719 getWindow().setContentView(view, params);
2720 initWindowDecorActionBar();
2724 * Add an additional content view to the activity. Added after any existing
2725 * ones in the activity -- existing views are NOT removed.
2727 * @param view The desired content to display.
2728 * @param params Layout parameters for the view.
2730 public void addContentView(View view, ViewGroup.LayoutParams params) {
2731 getWindow().addContentView(view, params);
2732 initWindowDecorActionBar();
2736 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
2737 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2739 * <p>This method will return non-null after content has been initialized (e.g. by using
2740 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
2742 * @return This window's content TransitionManager or null if none is set.
2744 public TransitionManager getContentTransitionManager() {
2745 return getWindow().getTransitionManager();
2749 * Set the {@link TransitionManager} to use for default transitions in this window.
2750 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2752 * @param tm The TransitionManager to use for scene changes.
2754 public void setContentTransitionManager(TransitionManager tm) {
2755 getWindow().setTransitionManager(tm);
2759 * Retrieve the {@link Scene} representing this window's current content.
2760 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
2762 * <p>This method will return null if the current content is not represented by a Scene.</p>
2764 * @return Current Scene being shown or null
2766 public Scene getContentScene() {
2767 return getWindow().getContentScene();
2771 * Sets whether this activity is finished when touched outside its window's
2774 public void setFinishOnTouchOutside(boolean finish) {
2775 mWindow.setCloseOnTouchOutside(finish);
2779 @IntDef(prefix = { "DEFAULT_KEYS_" }, value = {
2780 DEFAULT_KEYS_DISABLE,
2781 DEFAULT_KEYS_DIALER,
2782 DEFAULT_KEYS_SHORTCUT,
2783 DEFAULT_KEYS_SEARCH_LOCAL,
2784 DEFAULT_KEYS_SEARCH_GLOBAL
2786 @Retention(RetentionPolicy.SOURCE)
2787 @interface DefaultKeyMode {}
2790 * Use with {@link #setDefaultKeyMode} to turn off default handling of
2793 * @see #setDefaultKeyMode
2795 static public final int DEFAULT_KEYS_DISABLE = 0;
2797 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
2800 * @see #setDefaultKeyMode
2802 static public final int DEFAULT_KEYS_DIALER = 1;
2804 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
2805 * default key handling.
2807 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
2809 * @see #setDefaultKeyMode
2811 static public final int DEFAULT_KEYS_SHORTCUT = 2;
2813 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2814 * will start an application-defined search. (If the application or activity does not
2815 * actually define a search, the the keys will be ignored.)
2817 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2819 * @see #setDefaultKeyMode
2821 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
2824 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
2825 * will start a global search (typically web search, but some platforms may define alternate
2826 * methods for global search)
2828 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
2830 * @see #setDefaultKeyMode
2832 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
2835 * Select the default key handling for this activity. This controls what
2836 * will happen to key events that are not otherwise handled. The default
2837 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
2838 * floor. Other modes allow you to launch the dialer
2839 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
2840 * menu without requiring the menu key be held down
2841 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
2842 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
2844 * <p>Note that the mode selected here does not impact the default
2845 * handling of system keys, such as the "back" and "menu" keys, and your
2846 * activity and its views always get a first chance to receive and handle
2847 * all application keys.
2849 * @param mode The desired default key mode constant.
2853 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
2854 mDefaultKeyMode = mode;
2856 // Some modes use a SpannableStringBuilder to track & dispatch input events
2857 // This list must remain in sync with the switch in onKeyDown()
2859 case DEFAULT_KEYS_DISABLE:
2860 case DEFAULT_KEYS_SHORTCUT:
2861 mDefaultKeySsb = null; // not used in these modes
2863 case DEFAULT_KEYS_DIALER:
2864 case DEFAULT_KEYS_SEARCH_LOCAL:
2865 case DEFAULT_KEYS_SEARCH_GLOBAL:
2866 mDefaultKeySsb = new SpannableStringBuilder();
2867 Selection.setSelection(mDefaultKeySsb,0);
2870 throw new IllegalArgumentException();
2875 * Called when a key was pressed down and not handled by any of the views
2876 * inside of the activity. So, for example, key presses while the cursor
2877 * is inside a TextView will not trigger the event (unless it is a navigation
2878 * to another object) because TextView handles its own key presses.
2880 * <p>If the focused view didn't want this event, this method is called.
2882 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
2883 * by calling {@link #onBackPressed()}, though the behavior varies based
2884 * on the application compatibility mode: for
2885 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
2886 * it will set up the dispatch to call {@link #onKeyUp} where the action
2887 * will be performed; for earlier applications, it will perform the
2888 * action immediately in on-down, as those versions of the platform
2891 * <p>Other additional default key handling may be performed
2892 * if configured with {@link #setDefaultKeyMode}.
2894 * @return Return <code>true</code> to prevent this event from being propagated
2895 * further, or <code>false</code> to indicate that you have not handled
2896 * this event and it should continue to be propagated.
2898 * @see android.view.KeyEvent
2900 public boolean onKeyDown(int keyCode, KeyEvent event) {
2901 if (keyCode == KeyEvent.KEYCODE_BACK) {
2902 if (getApplicationInfo().targetSdkVersion
2903 >= Build.VERSION_CODES.ECLAIR) {
2904 event.startTracking();
2911 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
2913 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
2914 Window w = getWindow();
2915 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
2916 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
2917 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
2921 } else if (keyCode == KeyEvent.KEYCODE_TAB) {
2922 // Don't consume TAB here since it's used for navigation. Arrow keys
2923 // aren't considered "typing keys" so they already won't get consumed.
2926 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
2927 boolean clearSpannable = false;
2929 if ((event.getRepeatCount() != 0) || event.isSystem()) {
2930 clearSpannable = true;
2933 handled = TextKeyListener.getInstance().onKeyDown(
2934 null, mDefaultKeySsb, keyCode, event);
2935 if (handled && mDefaultKeySsb.length() > 0) {
2936 // something useable has been typed - dispatch it now.
2938 final String str = mDefaultKeySsb.toString();
2939 clearSpannable = true;
2941 switch (mDefaultKeyMode) {
2942 case DEFAULT_KEYS_DIALER:
2943 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
2944 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2945 startActivity(intent);
2947 case DEFAULT_KEYS_SEARCH_LOCAL:
2948 startSearch(str, false, null, false);
2950 case DEFAULT_KEYS_SEARCH_GLOBAL:
2951 startSearch(str, false, null, true);
2956 if (clearSpannable) {
2957 mDefaultKeySsb.clear();
2958 mDefaultKeySsb.clearSpans();
2959 Selection.setSelection(mDefaultKeySsb,0);
2966 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
2967 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
2970 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
2975 * Called when a key was released and not handled by any of the views
2976 * inside of the activity. So, for example, key presses while the cursor
2977 * is inside a TextView will not trigger the event (unless it is a navigation
2978 * to another object) because TextView handles its own key presses.
2980 * <p>The default implementation handles KEYCODE_BACK to stop the activity
2983 * @return Return <code>true</code> to prevent this event from being propagated
2984 * further, or <code>false</code> to indicate that you have not handled
2985 * this event and it should continue to be propagated.
2989 public boolean onKeyUp(int keyCode, KeyEvent event) {
2990 if (getApplicationInfo().targetSdkVersion
2991 >= Build.VERSION_CODES.ECLAIR) {
2992 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
2993 && !event.isCanceled()) {
3002 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3003 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
3006 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3011 * Called when the activity has detected the user's press of the back
3012 * key. The default implementation simply finishes the current activity,
3013 * but you can override this to do whatever you want.
3015 public void onBackPressed() {
3016 if (mActionBar != null && mActionBar.collapseActionView()) {
3020 FragmentManager fragmentManager = mFragments.getFragmentManager();
3022 if (fragmentManager.isStateSaved() || !fragmentManager.popBackStackImmediate()) {
3023 finishAfterTransition();
3028 * Called when a key shortcut event is not handled by any of the views in the Activity.
3029 * Override this method to implement global key shortcuts for the Activity.
3030 * Key shortcuts can also be implemented by setting the
3031 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
3033 * @param keyCode The value in event.getKeyCode().
3034 * @param event Description of the key event.
3035 * @return True if the key shortcut was handled.
3037 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
3038 // Let the Action Bar have a chance at handling the shortcut.
3039 ActionBar actionBar = getActionBar();
3040 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
3044 * Called when a touch screen event was not handled by any of the views
3045 * under it. This is most useful to process touch events that happen
3046 * outside of your window bounds, where there is no view to receive it.
3048 * @param event The touch screen event being processed.
3050 * @return Return true if you have consumed the event, false if you haven't.
3051 * The default implementation always returns false.
3053 public boolean onTouchEvent(MotionEvent event) {
3054 if (mWindow.shouldCloseOnTouch(this, event)) {
3063 * Called when the trackball was moved and not handled by any of the
3064 * views inside of the activity. So, for example, if the trackball moves
3065 * while focus is on a button, you will receive a call here because
3066 * buttons do not normally do anything with trackball events. The call
3067 * here happens <em>before</em> trackball movements are converted to
3068 * DPAD key events, which then get sent back to the view hierarchy, and
3069 * will be processed at the point for things like focus navigation.
3071 * @param event The trackball event being processed.
3073 * @return Return true if you have consumed the event, false if you haven't.
3074 * The default implementation always returns false.
3076 public boolean onTrackballEvent(MotionEvent event) {
3081 * Called when a generic motion event was not handled by any of the
3082 * views inside of the activity.
3084 * Generic motion events describe joystick movements, mouse hovers, track pad
3085 * touches, scroll wheel movements and other input events. The
3086 * {@link MotionEvent#getSource() source} of the motion event specifies
3087 * the class of input that was received. Implementations of this method
3088 * must examine the bits in the source before processing the event.
3089 * The following code example shows how this is done.
3091 * Generic motion events with source class
3092 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
3093 * are delivered to the view under the pointer. All other generic motion events are
3094 * delivered to the focused view.
3096 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
3097 * handle this event.
3100 * @param event The generic motion event being processed.
3102 * @return Return true if you have consumed the event, false if you haven't.
3103 * The default implementation always returns false.
3105 public boolean onGenericMotionEvent(MotionEvent event) {
3110 * Called whenever a key, touch, or trackball event is dispatched to the
3111 * activity. Implement this method if you wish to know that the user has
3112 * interacted with the device in some way while your activity is running.
3113 * This callback and {@link #onUserLeaveHint} are intended to help
3114 * activities manage status bar notifications intelligently; specifically,
3115 * for helping activities determine the proper time to cancel a notfication.
3117 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
3118 * be accompanied by calls to {@link #onUserInteraction}. This
3119 * ensures that your activity will be told of relevant user activity such
3120 * as pulling down the notification pane and touching an item there.
3122 * <p>Note that this callback will be invoked for the touch down action
3123 * that begins a touch gesture, but may not be invoked for the touch-moved
3124 * and touch-up actions that follow.
3126 * @see #onUserLeaveHint()
3128 public void onUserInteraction() {
3131 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
3132 // Update window manager if: we have a view, that view is
3133 // attached to its parent (which will be a RootView), and
3134 // this activity is not embedded.
3135 if (mParent == null) {
3136 View decor = mDecor;
3137 if (decor != null && decor.getParent() != null) {
3138 getWindowManager().updateViewLayout(decor, params);
3143 public void onContentChanged() {
3147 * Called when the current {@link Window} of the activity gains or loses
3148 * focus. This is the best indicator of whether this activity is visible
3149 * to the user. The default implementation clears the key tracking
3150 * state, so should always be called.
3152 * <p>Note that this provides information about global focus state, which
3153 * is managed independently of activity lifecycles. As such, while focus
3154 * changes will generally have some relation to lifecycle changes (an
3155 * activity that is stopped will not generally get window focus), you
3156 * should not rely on any particular order between the callbacks here and
3157 * those in the other lifecycle methods such as {@link #onResume}.
3159 * <p>As a general rule, however, a resumed activity will have window
3160 * focus... unless it has displayed other dialogs or popups that take
3161 * input focus, in which case the activity itself will not have focus
3162 * when the other windows have it. Likewise, the system may display
3163 * system-level windows (such as the status bar notification panel or
3164 * a system alert) which will temporarily take window input focus without
3165 * pausing the foreground activity.
3167 * @param hasFocus Whether the window of this activity has focus.
3169 * @see #hasWindowFocus()
3171 * @see View#onWindowFocusChanged(boolean)
3173 public void onWindowFocusChanged(boolean hasFocus) {
3177 * Called when the main window associated with the activity has been
3178 * attached to the window manager.
3179 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
3180 * for more information.
3181 * @see View#onAttachedToWindow
3183 public void onAttachedToWindow() {
3187 * Called when the main window associated with the activity has been
3188 * detached from the window manager.
3189 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
3190 * for more information.
3191 * @see View#onDetachedFromWindow
3193 public void onDetachedFromWindow() {
3197 * Returns true if this activity's <em>main</em> window currently has window focus.
3198 * Note that this is not the same as the view itself having focus.
3200 * @return True if this activity's main window currently has window focus.
3202 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
3204 public boolean hasWindowFocus() {
3205 Window w = getWindow();
3207 View d = w.getDecorView();
3209 return d.hasWindowFocus();
3216 * Called when the main window associated with the activity has been dismissed.
3220 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
3221 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
3222 if (suppressWindowTransition) {
3223 overridePendingTransition(0, 0);
3229 * Moves the activity from
3230 * {@link android.app.ActivityManager.StackId#FREEFORM_WORKSPACE_STACK_ID} to
3231 * {@link android.app.ActivityManager.StackId#FULLSCREEN_WORKSPACE_STACK_ID} stack.
3236 public void exitFreeformMode() throws RemoteException {
3237 ActivityManager.getService().exitFreeformMode(mToken);
3240 /** Returns the current stack Id for the window.
3244 public int getWindowStackId() throws RemoteException {
3245 return ActivityManager.getService().getActivityStackId(mToken);
3249 * Puts the activity in picture-in-picture mode if the activity supports.
3250 * @see android.R.attr#supportsPictureInPicture
3254 public void enterPictureInPictureModeIfPossible() {
3255 if (mActivityInfo.supportsPictureInPicture()) {
3256 enterPictureInPictureMode();
3261 * Called to process key events. You can override this to intercept all
3262 * key events before they are dispatched to the window. Be sure to call
3263 * this implementation for key events that should be handled normally.
3265 * @param event The key event.
3267 * @return boolean Return true if this event was consumed.
3269 public boolean dispatchKeyEvent(KeyEvent event) {
3270 onUserInteraction();
3272 // Let action bars open menus in response to the menu key prioritized over
3273 // the window handling it
3274 final int keyCode = event.getKeyCode();
3275 if (keyCode == KeyEvent.KEYCODE_MENU &&
3276 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
3280 Window win = getWindow();
3281 if (win.superDispatchKeyEvent(event)) {
3284 View decor = mDecor;
3285 if (decor == null) decor = win.getDecorView();
3286 return event.dispatch(this, decor != null
3287 ? decor.getKeyDispatcherState() : null, this);
3291 * Called to process a key shortcut event.
3292 * You can override this to intercept all key shortcut events before they are
3293 * dispatched to the window. Be sure to call this implementation for key shortcut
3294 * events that should be handled normally.
3296 * @param event The key shortcut event.
3297 * @return True if this event was consumed.
3299 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3300 onUserInteraction();
3301 if (getWindow().superDispatchKeyShortcutEvent(event)) {
3304 return onKeyShortcut(event.getKeyCode(), event);
3308 * Called to process touch screen events. You can override this to
3309 * intercept all touch screen events before they are dispatched to the
3310 * window. Be sure to call this implementation for touch screen events
3311 * that should be handled normally.
3313 * @param ev The touch screen event.
3315 * @return boolean Return true if this event was consumed.
3317 public boolean dispatchTouchEvent(MotionEvent ev) {
3318 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
3319 onUserInteraction();
3321 if (getWindow().superDispatchTouchEvent(ev)) {
3324 return onTouchEvent(ev);
3328 * Called to process trackball events. You can override this to
3329 * intercept all trackball events before they are dispatched to the
3330 * window. Be sure to call this implementation for trackball events
3331 * that should be handled normally.
3333 * @param ev The trackball event.
3335 * @return boolean Return true if this event was consumed.
3337 public boolean dispatchTrackballEvent(MotionEvent ev) {
3338 onUserInteraction();
3339 if (getWindow().superDispatchTrackballEvent(ev)) {
3342 return onTrackballEvent(ev);
3346 * Called to process generic motion events. You can override this to
3347 * intercept all generic motion events before they are dispatched to the
3348 * window. Be sure to call this implementation for generic motion events
3349 * that should be handled normally.
3351 * @param ev The generic motion event.
3353 * @return boolean Return true if this event was consumed.
3355 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3356 onUserInteraction();
3357 if (getWindow().superDispatchGenericMotionEvent(ev)) {
3360 return onGenericMotionEvent(ev);
3363 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3364 event.setClassName(getClass().getName());
3365 event.setPackageName(getPackageName());
3367 LayoutParams params = getWindow().getAttributes();
3368 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
3369 (params.height == LayoutParams.MATCH_PARENT);
3370 event.setFullScreen(isFullScreen);
3372 CharSequence title = getTitle();
3373 if (!TextUtils.isEmpty(title)) {
3374 event.getText().add(title);
3381 * Default implementation of
3382 * {@link android.view.Window.Callback#onCreatePanelView}
3383 * for activities. This
3384 * simply returns null so that all panel sub-windows will have the default
3388 public View onCreatePanelView(int featureId) {
3393 * Default implementation of
3394 * {@link android.view.Window.Callback#onCreatePanelMenu}
3395 * for activities. This calls through to the new
3396 * {@link #onCreateOptionsMenu} method for the
3397 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3398 * so that subclasses of Activity don't need to deal with feature codes.
3400 public boolean onCreatePanelMenu(int featureId, Menu menu) {
3401 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
3402 boolean show = onCreateOptionsMenu(menu);
3403 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
3410 * Default implementation of
3411 * {@link android.view.Window.Callback#onPreparePanel}
3412 * for activities. This
3413 * calls through to the new {@link #onPrepareOptionsMenu} method for the
3414 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3415 * panel, so that subclasses of
3416 * Activity don't need to deal with feature codes.
3418 public boolean onPreparePanel(int featureId, View view, Menu menu) {
3419 if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
3420 boolean goforit = onPrepareOptionsMenu(menu);
3421 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
3430 * @return The default implementation returns true.
3432 public boolean onMenuOpened(int featureId, Menu menu) {
3433 if (featureId == Window.FEATURE_ACTION_BAR) {
3434 initWindowDecorActionBar();
3435 if (mActionBar != null) {
3436 mActionBar.dispatchMenuVisibilityChanged(true);
3438 Log.e(TAG, "Tried to open action bar menu with no action bar");
3445 * Default implementation of
3446 * {@link android.view.Window.Callback#onMenuItemSelected}
3447 * for activities. This calls through to the new
3448 * {@link #onOptionsItemSelected} method for the
3449 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
3450 * panel, so that subclasses of
3451 * Activity don't need to deal with feature codes.
3453 public boolean onMenuItemSelected(int featureId, MenuItem item) {
3454 CharSequence titleCondensed = item.getTitleCondensed();
3456 switch (featureId) {
3457 case Window.FEATURE_OPTIONS_PANEL:
3458 // Put event logging here so it gets called even if subclass
3459 // doesn't call through to superclass's implmeentation of each
3460 // of these methods below
3461 if(titleCondensed != null) {
3462 EventLog.writeEvent(50000, 0, titleCondensed.toString());
3464 if (onOptionsItemSelected(item)) {
3467 if (mFragments.dispatchOptionsItemSelected(item)) {
3470 if (item.getItemId() == android.R.id.home && mActionBar != null &&
3471 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
3472 if (mParent == null) {
3473 return onNavigateUp();
3475 return mParent.onNavigateUpFromChild(this);
3480 case Window.FEATURE_CONTEXT_MENU:
3481 if(titleCondensed != null) {
3482 EventLog.writeEvent(50000, 1, titleCondensed.toString());
3484 if (onContextItemSelected(item)) {
3487 return mFragments.dispatchContextItemSelected(item);
3495 * Default implementation of
3496 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
3497 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
3498 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
3499 * so that subclasses of Activity don't need to deal with feature codes.
3500 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
3501 * {@link #onContextMenuClosed(Menu)} will be called.
3503 public void onPanelClosed(int featureId, Menu menu) {
3504 switch (featureId) {
3505 case Window.FEATURE_OPTIONS_PANEL:
3506 mFragments.dispatchOptionsMenuClosed(menu);
3507 onOptionsMenuClosed(menu);
3510 case Window.FEATURE_CONTEXT_MENU:
3511 onContextMenuClosed(menu);
3514 case Window.FEATURE_ACTION_BAR:
3515 initWindowDecorActionBar();
3516 mActionBar.dispatchMenuVisibilityChanged(false);
3522 * Declare that the options menu has changed, so should be recreated.
3523 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
3524 * time it needs to be displayed.
3526 public void invalidateOptionsMenu() {
3527 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3528 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
3529 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
3534 * Initialize the contents of the Activity's standard options menu. You
3535 * should place your menu items in to <var>menu</var>.
3537 * <p>This is only called once, the first time the options menu is
3538 * displayed. To update the menu every time it is displayed, see
3539 * {@link #onPrepareOptionsMenu}.
3541 * <p>The default implementation populates the menu with standard system
3542 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
3543 * they will be correctly ordered with application-defined menu items.
3544 * Deriving classes should always call through to the base implementation.
3546 * <p>You can safely hold on to <var>menu</var> (and any items created
3547 * from it), making modifications to it as desired, until the next
3548 * time onCreateOptionsMenu() is called.
3550 * <p>When you add items to the menu, you can implement the Activity's
3551 * {@link #onOptionsItemSelected} method to handle them there.
3553 * @param menu The options menu in which you place your items.
3555 * @return You must return true for the menu to be displayed;
3556 * if you return false it will not be shown.
3558 * @see #onPrepareOptionsMenu
3559 * @see #onOptionsItemSelected
3561 public boolean onCreateOptionsMenu(Menu menu) {
3562 if (mParent != null) {
3563 return mParent.onCreateOptionsMenu(menu);
3569 * Prepare the Screen's standard options menu to be displayed. This is
3570 * called right before the menu is shown, every time it is shown. You can
3571 * use this method to efficiently enable/disable items or otherwise
3572 * dynamically modify the contents.
3574 * <p>The default implementation updates the system menu items based on the
3575 * activity's state. Deriving classes should always call through to the
3576 * base class implementation.
3578 * @param menu The options menu as last shown or first initialized by
3579 * onCreateOptionsMenu().
3581 * @return You must return true for the menu to be displayed;
3582 * if you return false it will not be shown.
3584 * @see #onCreateOptionsMenu
3586 public boolean onPrepareOptionsMenu(Menu menu) {
3587 if (mParent != null) {
3588 return mParent.onPrepareOptionsMenu(menu);
3594 * This hook is called whenever an item in your options menu is selected.
3595 * The default implementation simply returns false to have the normal
3596 * processing happen (calling the item's Runnable or sending a message to
3597 * its Handler as appropriate). You can use this method for any items
3598 * for which you would like to do processing without those other
3601 * <p>Derived classes should call through to the base class for it to
3602 * perform the default menu handling.</p>
3604 * @param item The menu item that was selected.
3606 * @return boolean Return false to allow normal menu processing to
3607 * proceed, true to consume it here.
3609 * @see #onCreateOptionsMenu
3611 public boolean onOptionsItemSelected(MenuItem item) {
3612 if (mParent != null) {
3613 return mParent.onOptionsItemSelected(item);
3619 * This method is called whenever the user chooses to navigate Up within your application's
3620 * activity hierarchy from the action bar.
3622 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
3623 * was specified in the manifest for this activity or an activity-alias to it,
3624 * default Up navigation will be handled automatically. If any activity
3625 * along the parent chain requires extra Intent arguments, the Activity subclass
3626 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
3627 * to supply those arguments.</p>
3629 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
3630 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
3631 * from the design guide for more information about navigating within your app.</p>
3633 * <p>See the {@link TaskStackBuilder} class and the Activity methods
3634 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
3635 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
3636 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
3638 * @return true if Up navigation completed successfully and this Activity was finished,
3641 public boolean onNavigateUp() {
3642 // Automatically handle hierarchical Up navigation if the proper
3643 // metadata is available.
3644 Intent upIntent = getParentActivityIntent();
3645 if (upIntent != null) {
3646 if (mActivityInfo.taskAffinity == null) {
3647 // Activities with a null affinity are special; they really shouldn't
3648 // specify a parent activity intent in the first place. Just finish
3649 // the current activity and call it a day.
3651 } else if (shouldUpRecreateTask(upIntent)) {
3652 TaskStackBuilder b = TaskStackBuilder.create(this);
3653 onCreateNavigateUpTaskStack(b);
3654 onPrepareNavigateUpTaskStack(b);
3655 b.startActivities();
3657 // We can't finishAffinity if we have a result.
3658 // Fall back and simply finish the current activity instead.
3659 if (mResultCode != RESULT_CANCELED || mResultData != null) {
3660 // Tell the developer what's going on to avoid hair-pulling.
3661 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
3667 navigateUpTo(upIntent);
3675 * This is called when a child activity of this one attempts to navigate up.
3676 * The default implementation simply calls onNavigateUp() on this activity (the parent).
3678 * @param child The activity making the call.
3680 public boolean onNavigateUpFromChild(Activity child) {
3681 return onNavigateUp();
3685 * Define the synthetic task stack that will be generated during Up navigation from
3688 * <p>The default implementation of this method adds the parent chain of this activity
3689 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
3690 * may choose to override this method to construct the desired task stack in a different
3693 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
3694 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
3695 * returned by {@link #getParentActivityIntent()}.</p>
3697 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
3698 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
3700 * @param builder An empty TaskStackBuilder - the application should add intents representing
3701 * the desired task stack
3703 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
3704 builder.addParentStack(this);
3708 * Prepare the synthetic task stack that will be generated during Up navigation
3709 * from a different task.
3711 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
3712 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
3713 * If any extra data should be added to these intents before launching the new task,
3714 * the application should override this method and add that data here.</p>
3716 * @param builder A TaskStackBuilder that has been populated with Intents by
3717 * onCreateNavigateUpTaskStack.
3719 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
3723 * This hook is called whenever the options menu is being closed (either by the user canceling
3724 * the menu with the back/menu button, or when an item is selected).
3726 * @param menu The options menu as last shown or first initialized by
3727 * onCreateOptionsMenu().
3729 public void onOptionsMenuClosed(Menu menu) {
3730 if (mParent != null) {
3731 mParent.onOptionsMenuClosed(menu);
3736 * Programmatically opens the options menu. If the options menu is already
3737 * open, this method does nothing.
3739 public void openOptionsMenu() {
3740 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3741 (mActionBar == null || !mActionBar.openOptionsMenu())) {
3742 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
3747 * Progammatically closes the options menu. If the options menu is already
3748 * closed, this method does nothing.
3750 public void closeOptionsMenu() {
3751 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3752 (mActionBar == null || !mActionBar.closeOptionsMenu())) {
3753 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
3758 * Called when a context menu for the {@code view} is about to be shown.
3759 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
3760 * time the context menu is about to be shown and should be populated for
3761 * the view (or item inside the view for {@link AdapterView} subclasses,
3762 * this can be found in the {@code menuInfo})).
3764 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
3765 * item has been selected.
3767 * It is not safe to hold onto the context menu after this method returns.
3770 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3774 * Registers a context menu to be shown for the given view (multiple views
3775 * can show the context menu). This method will set the
3776 * {@link OnCreateContextMenuListener} on the view to this activity, so
3777 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
3778 * called when it is time to show the context menu.
3780 * @see #unregisterForContextMenu(View)
3781 * @param view The view that should show a context menu.
3783 public void registerForContextMenu(View view) {
3784 view.setOnCreateContextMenuListener(this);
3788 * Prevents a context menu to be shown for the given view. This method will remove the
3789 * {@link OnCreateContextMenuListener} on the view.
3791 * @see #registerForContextMenu(View)
3792 * @param view The view that should stop showing a context menu.
3794 public void unregisterForContextMenu(View view) {
3795 view.setOnCreateContextMenuListener(null);
3799 * Programmatically opens the context menu for a particular {@code view}.
3800 * The {@code view} should have been added via
3801 * {@link #registerForContextMenu(View)}.
3803 * @param view The view to show the context menu for.
3805 public void openContextMenu(View view) {
3806 view.showContextMenu();
3810 * Programmatically closes the most recently opened context menu, if showing.
3812 public void closeContextMenu() {
3813 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
3814 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
3819 * This hook is called whenever an item in a context menu is selected. The
3820 * default implementation simply returns false to have the normal processing
3821 * happen (calling the item's Runnable or sending a message to its Handler
3822 * as appropriate). You can use this method for any items for which you
3823 * would like to do processing without those other facilities.
3825 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
3826 * View that added this menu item.
3828 * Derived classes should call through to the base class for it to perform
3829 * the default menu handling.
3831 * @param item The context menu item that was selected.
3832 * @return boolean Return false to allow normal context menu processing to
3833 * proceed, true to consume it here.
3835 public boolean onContextItemSelected(MenuItem item) {
3836 if (mParent != null) {
3837 return mParent.onContextItemSelected(item);
3843 * This hook is called whenever the context menu is being closed (either by
3844 * the user canceling the menu with the back/menu button, or when an item is
3847 * @param menu The context menu that is being closed.
3849 public void onContextMenuClosed(Menu menu) {
3850 if (mParent != null) {
3851 mParent.onContextMenuClosed(menu);
3856 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
3859 protected Dialog onCreateDialog(int id) {
3864 * Callback for creating dialogs that are managed (saved and restored) for you
3865 * by the activity. The default implementation calls through to
3866 * {@link #onCreateDialog(int)} for compatibility.
3868 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3869 * or later, consider instead using a {@link DialogFragment} instead.</em>
3871 * <p>If you use {@link #showDialog(int)}, the activity will call through to
3872 * this method the first time, and hang onto it thereafter. Any dialog
3873 * that is created by this method will automatically be saved and restored
3874 * for you, including whether it is showing.
3876 * <p>If you would like the activity to manage saving and restoring dialogs
3877 * for you, you should override this method and handle any ids that are
3878 * passed to {@link #showDialog}.
3880 * <p>If you would like an opportunity to prepare your dialog before it is shown,
3881 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
3883 * @param id The id of the dialog.
3884 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3885 * @return The dialog. If you return null, the dialog will not be created.
3887 * @see #onPrepareDialog(int, Dialog, Bundle)
3888 * @see #showDialog(int, Bundle)
3889 * @see #dismissDialog(int)
3890 * @see #removeDialog(int)
3892 * @deprecated Use the new {@link DialogFragment} class with
3893 * {@link FragmentManager} instead; this is also
3894 * available on older platforms through the Android compatibility package.
3898 protected Dialog onCreateDialog(int id, Bundle args) {
3899 return onCreateDialog(id);
3903 * @deprecated Old no-arguments version of
3904 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
3907 protected void onPrepareDialog(int id, Dialog dialog) {
3908 dialog.setOwnerActivity(this);
3912 * Provides an opportunity to prepare a managed dialog before it is being
3913 * shown. The default implementation calls through to
3914 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
3917 * Override this if you need to update a managed dialog based on the state
3918 * of the application each time it is shown. For example, a time picker
3919 * dialog might want to be updated with the current time. You should call
3920 * through to the superclass's implementation. The default implementation
3921 * will set this Activity as the owner activity on the Dialog.
3923 * @param id The id of the managed dialog.
3924 * @param dialog The dialog.
3925 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
3926 * @see #onCreateDialog(int, Bundle)
3927 * @see #showDialog(int)
3928 * @see #dismissDialog(int)
3929 * @see #removeDialog(int)
3931 * @deprecated Use the new {@link DialogFragment} class with
3932 * {@link FragmentManager} instead; this is also
3933 * available on older platforms through the Android compatibility package.
3936 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
3937 onPrepareDialog(id, dialog);
3941 * Simple version of {@link #showDialog(int, Bundle)} that does not
3942 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
3943 * with null arguments.
3945 * @deprecated Use the new {@link DialogFragment} class with
3946 * {@link FragmentManager} instead; this is also
3947 * available on older platforms through the Android compatibility package.
3950 public final void showDialog(int id) {
3951 showDialog(id, null);
3955 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
3956 * will be made with the same id the first time this is called for a given
3957 * id. From thereafter, the dialog will be automatically saved and restored.
3959 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3960 * or later, consider instead using a {@link DialogFragment} instead.</em>
3962 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
3963 * be made to provide an opportunity to do any timely preparation.
3965 * @param id The id of the managed dialog.
3966 * @param args Arguments to pass through to the dialog. These will be saved
3967 * and restored for you. Note that if the dialog is already created,
3968 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
3969 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
3970 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
3971 * @return Returns true if the Dialog was created; false is returned if
3972 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
3975 * @see #onCreateDialog(int, Bundle)
3976 * @see #onPrepareDialog(int, Dialog, Bundle)
3977 * @see #dismissDialog(int)
3978 * @see #removeDialog(int)
3980 * @deprecated Use the new {@link DialogFragment} class with
3981 * {@link FragmentManager} instead; this is also
3982 * available on older platforms through the Android compatibility package.
3985 public final boolean showDialog(int id, Bundle args) {
3986 if (mManagedDialogs == null) {
3987 mManagedDialogs = new SparseArray<ManagedDialog>();
3989 ManagedDialog md = mManagedDialogs.get(id);
3991 md = new ManagedDialog();
3992 md.mDialog = createDialog(id, null, args);
3993 if (md.mDialog == null) {
3996 mManagedDialogs.put(id, md);
4000 onPrepareDialog(id, md.mDialog, args);
4006 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
4008 * @param id The id of the managed dialog.
4010 * @throws IllegalArgumentException if the id was not previously shown via
4011 * {@link #showDialog(int)}.
4013 * @see #onCreateDialog(int, Bundle)
4014 * @see #onPrepareDialog(int, Dialog, Bundle)
4015 * @see #showDialog(int)
4016 * @see #removeDialog(int)
4018 * @deprecated Use the new {@link DialogFragment} class with
4019 * {@link FragmentManager} instead; this is also
4020 * available on older platforms through the Android compatibility package.
4023 public final void dismissDialog(int id) {
4024 if (mManagedDialogs == null) {
4025 throw missingDialog(id);
4028 final ManagedDialog md = mManagedDialogs.get(id);
4030 throw missingDialog(id);
4032 md.mDialog.dismiss();
4036 * Creates an exception to throw if a user passed in a dialog id that is
4039 private IllegalArgumentException missingDialog(int id) {
4040 return new IllegalArgumentException("no dialog with id " + id + " was ever "
4041 + "shown via Activity#showDialog");
4045 * Removes any internal references to a dialog managed by this Activity.
4046 * If the dialog is showing, it will dismiss it as part of the clean up.
4048 * <p>This can be useful if you know that you will never show a dialog again and
4049 * want to avoid the overhead of saving and restoring it in the future.
4051 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
4052 * will not throw an exception if you try to remove an ID that does not
4053 * currently have an associated dialog.</p>
4055 * @param id The id of the managed dialog.
4057 * @see #onCreateDialog(int, Bundle)
4058 * @see #onPrepareDialog(int, Dialog, Bundle)
4059 * @see #showDialog(int)
4060 * @see #dismissDialog(int)
4062 * @deprecated Use the new {@link DialogFragment} class with
4063 * {@link FragmentManager} instead; this is also
4064 * available on older platforms through the Android compatibility package.
4067 public final void removeDialog(int id) {
4068 if (mManagedDialogs != null) {
4069 final ManagedDialog md = mManagedDialogs.get(id);
4071 md.mDialog.dismiss();
4072 mManagedDialogs.remove(id);
4078 * This hook is called when the user signals the desire to start a search.
4080 * <p>You can use this function as a simple way to launch the search UI, in response to a
4081 * menu item, search button, or other widgets within your activity. Unless overidden,
4082 * calling this function is the same as calling
4083 * {@link #startSearch startSearch(null, false, null, false)}, which launches
4084 * search for the current activity as specified in its manifest, see {@link SearchManager}.
4086 * <p>You can override this function to force global search, e.g. in response to a dedicated
4087 * search key, or to block search entirely (by simply returning false).
4089 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION}, the default
4090 * implementation changes to simply return false and you must supply your own custom
4091 * implementation if you want to support search.</p>
4093 * @param searchEvent The {@link SearchEvent} that signaled this search.
4094 * @return Returns {@code true} if search launched, and {@code false} if the activity does
4095 * not respond to search. The default implementation always returns {@code true}, except
4096 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
4098 * @see android.app.SearchManager
4100 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
4101 mSearchEvent = searchEvent;
4102 boolean result = onSearchRequested();
4103 mSearchEvent = null;
4108 * @see #onSearchRequested(SearchEvent)
4110 public boolean onSearchRequested() {
4111 if ((getResources().getConfiguration().uiMode&Configuration.UI_MODE_TYPE_MASK)
4112 != Configuration.UI_MODE_TYPE_TELEVISION) {
4113 startSearch(null, false, null, false);
4121 * During the onSearchRequested() callbacks, this function will return the
4122 * {@link SearchEvent} that triggered the callback, if it exists.
4124 * @return SearchEvent The SearchEvent that triggered the {@link
4125 * #onSearchRequested} callback.
4127 public final SearchEvent getSearchEvent() {
4128 return mSearchEvent;
4132 * This hook is called to launch the search UI.
4134 * <p>It is typically called from onSearchRequested(), either directly from
4135 * Activity.onSearchRequested() or from an overridden version in any given
4136 * Activity. If your goal is simply to activate search, it is preferred to call
4137 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
4138 * is to inject specific data such as context data, it is preferred to <i>override</i>
4139 * onSearchRequested(), so that any callers to it will benefit from the override.
4141 * @param initialQuery Any non-null non-empty string will be inserted as
4142 * pre-entered text in the search query box.
4143 * @param selectInitialQuery If true, the initial query will be preselected, which means that
4144 * any further typing will replace it. This is useful for cases where an entire pre-formed
4145 * query is being inserted. If false, the selection point will be placed at the end of the
4146 * inserted query. This is useful when the inserted query is text that the user entered,
4147 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
4148 * if initialQuery is a non-empty string.</i>
4149 * @param appSearchData An application can insert application-specific
4150 * context here, in order to improve quality or specificity of its own
4151 * searches. This data will be returned with SEARCH intent(s). Null if
4152 * no extra data is required.
4153 * @param globalSearch If false, this will only launch the search that has been specifically
4154 * defined by the application (which is usually defined as a local search). If no default
4155 * search is defined in the current application or activity, global search will be launched.
4156 * If true, this will always launch a platform-global (e.g. web-based) search instead.
4158 * @see android.app.SearchManager
4159 * @see #onSearchRequested
4161 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
4162 @Nullable Bundle appSearchData, boolean globalSearch) {
4163 ensureSearchManager();
4164 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
4165 appSearchData, globalSearch);
4169 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
4170 * the search dialog. Made available for testing purposes.
4172 * @param query The query to trigger. If empty, the request will be ignored.
4173 * @param appSearchData An application can insert application-specific
4174 * context here, in order to improve quality or specificity of its own
4175 * searches. This data will be returned with SEARCH intent(s). Null if
4176 * no extra data is required.
4178 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
4179 ensureSearchManager();
4180 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
4184 * Request that key events come to this activity. Use this if your
4185 * activity has no views with focus, but the activity still wants
4186 * a chance to process key events.
4188 * @see android.view.Window#takeKeyEvents
4190 public void takeKeyEvents(boolean get) {
4191 getWindow().takeKeyEvents(get);
4195 * Enable extended window features. This is a convenience for calling
4196 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
4198 * @param featureId The desired feature as defined in
4199 * {@link android.view.Window}.
4200 * @return Returns true if the requested feature is supported and now
4203 * @see android.view.Window#requestFeature
4205 public final boolean requestWindowFeature(int featureId) {
4206 return getWindow().requestFeature(featureId);
4210 * Convenience for calling
4211 * {@link android.view.Window#setFeatureDrawableResource}.
4213 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
4214 getWindow().setFeatureDrawableResource(featureId, resId);
4218 * Convenience for calling
4219 * {@link android.view.Window#setFeatureDrawableUri}.
4221 public final void setFeatureDrawableUri(int featureId, Uri uri) {
4222 getWindow().setFeatureDrawableUri(featureId, uri);
4226 * Convenience for calling
4227 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
4229 public final void setFeatureDrawable(int featureId, Drawable drawable) {
4230 getWindow().setFeatureDrawable(featureId, drawable);
4234 * Convenience for calling
4235 * {@link android.view.Window#setFeatureDrawableAlpha}.
4237 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
4238 getWindow().setFeatureDrawableAlpha(featureId, alpha);
4242 * Convenience for calling
4243 * {@link android.view.Window#getLayoutInflater}.
4246 public LayoutInflater getLayoutInflater() {
4247 return getWindow().getLayoutInflater();
4251 * Returns a {@link MenuInflater} with this context.
4254 public MenuInflater getMenuInflater() {
4255 // Make sure that action views can get an appropriate theme.
4256 if (mMenuInflater == null) {
4257 initWindowDecorActionBar();
4258 if (mActionBar != null) {
4259 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
4261 mMenuInflater = new MenuInflater(this);
4264 return mMenuInflater;
4268 public void setTheme(int resid) {
4269 super.setTheme(resid);
4270 mWindow.setTheme(resid);
4274 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
4276 if (mParent == null) {
4277 super.onApplyThemeResource(theme, resid, first);
4280 theme.setTo(mParent.getTheme());
4281 } catch (Exception e) {
4284 theme.applyStyle(resid, false);
4287 // Get the primary color and update the TaskDescription for this activity
4288 TypedArray a = theme.obtainStyledAttributes(
4289 com.android.internal.R.styleable.ActivityTaskDescription);
4290 if (mTaskDescription.getPrimaryColor() == 0) {
4291 int colorPrimary = a.getColor(
4292 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
4293 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
4294 mTaskDescription.setPrimaryColor(colorPrimary);
4298 int colorBackground = a.getColor(
4299 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
4300 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
4301 mTaskDescription.setBackgroundColor(colorBackground);
4304 final int statusBarColor = a.getColor(
4305 com.android.internal.R.styleable.ActivityTaskDescription_statusBarColor, 0);
4306 if (statusBarColor != 0) {
4307 mTaskDescription.setStatusBarColor(statusBarColor);
4310 final int navigationBarColor = a.getColor(
4311 com.android.internal.R.styleable.ActivityTaskDescription_navigationBarColor, 0);
4312 if (navigationBarColor != 0) {
4313 mTaskDescription.setNavigationBarColor(navigationBarColor);
4317 setTaskDescription(mTaskDescription);
4321 * Requests permissions to be granted to this application. These permissions
4322 * must be requested in your manifest, they should not be granted to your app,
4323 * and they should have protection level {@link android.content.pm.PermissionInfo
4324 * #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by
4325 * the platform or a third-party app.
4327 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
4328 * are granted at install time if requested in the manifest. Signature permissions
4329 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
4330 * install time if requested in the manifest and the signature of your app matches
4331 * the signature of the app declaring the permissions.
4334 * If your app does not have the requested permissions the user will be presented
4335 * with UI for accepting them. After the user has accepted or rejected the
4336 * requested permissions you will receive a callback on {@link
4337 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
4338 * permissions were granted or not.
4341 * Note that requesting a permission does not guarantee it will be granted and
4342 * your app should be able to run without having this permission.
4345 * This method may start an activity allowing the user to choose which permissions
4346 * to grant and which to reject. Hence, you should be prepared that your activity
4347 * may be paused and resumed. Further, granting some permissions may require
4348 * a restart of you application. In such a case, the system will recreate the
4349 * activity stack before delivering the result to {@link
4350 * #onRequestPermissionsResult(int, String[], int[])}.
4353 * When checking whether you have a permission you should use {@link
4354 * #checkSelfPermission(String)}.
4357 * Calling this API for permissions already granted to your app would show UI
4358 * to the user to decide whether the app can still hold these permissions. This
4359 * can be useful if the way your app uses data guarded by the permissions
4360 * changes significantly.
4363 * You cannot request a permission if your activity sets {@link
4364 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
4365 * <code>true</code> because in this case the activity would not receive
4366 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
4369 * The <a href="http://developer.android.com/samples/RuntimePermissions/index.html">
4370 * RuntimePermissions</a> sample app demonstrates how to use this method to
4371 * request permissions at run time.
4374 * @param permissions The requested permissions. Must me non-null and not empty.
4375 * @param requestCode Application specific request code to match with a result
4376 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
4379 * @throws IllegalArgumentException if requestCode is negative.
4381 * @see #onRequestPermissionsResult(int, String[], int[])
4382 * @see #checkSelfPermission(String)
4383 * @see #shouldShowRequestPermissionRationale(String)
4385 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
4386 if (requestCode < 0) {
4387 throw new IllegalArgumentException("requestCode should be >= 0");
4389 if (mHasCurrentPermissionsRequest) {
4390 Log.w(TAG, "Can reqeust only one set of permissions at a time");
4391 // Dispatch the callback with empty arrays which means a cancellation.
4392 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
4395 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
4396 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
4397 mHasCurrentPermissionsRequest = true;
4401 * Callback for the result from requesting permissions. This method
4402 * is invoked for every call on {@link #requestPermissions(String[], int)}.
4404 * <strong>Note:</strong> It is possible that the permissions request interaction
4405 * with the user is interrupted. In this case you will receive empty permissions
4406 * and results arrays which should be treated as a cancellation.
4409 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
4410 * @param permissions The requested permissions. Never null.
4411 * @param grantResults The grant results for the corresponding permissions
4412 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
4413 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
4415 * @see #requestPermissions(String[], int)
4417 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
4418 @NonNull int[] grantResults) {
4419 /* callback - no nothing */
4423 * Gets whether you should show UI with rationale for requesting a permission.
4424 * You should do this only if you do not have the permission and the context in
4425 * which the permission is requested does not clearly communicate to the user
4426 * what would be the benefit from granting this permission.
4428 * For example, if you write a camera app, requesting the camera permission
4429 * would be expected by the user and no rationale for why it is requested is
4430 * needed. If however, the app needs location for tagging photos then a non-tech
4431 * savvy user may wonder how location is related to taking photos. In this case
4432 * you may choose to show UI with rationale of requesting this permission.
4435 * @param permission A permission your app wants to request.
4436 * @return Whether you can show permission rationale UI.
4438 * @see #checkSelfPermission(String)
4439 * @see #requestPermissions(String[], int)
4440 * @see #onRequestPermissionsResult(int, String[], int[])
4442 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
4443 return getPackageManager().shouldShowRequestPermissionRationale(permission);
4447 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
4450 * @param intent The intent to start.
4451 * @param requestCode If >= 0, this code will be returned in
4452 * onActivityResult() when the activity exits.
4454 * @throws android.content.ActivityNotFoundException
4456 * @see #startActivity
4458 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
4459 startActivityForResult(intent, requestCode, null);
4463 * Launch an activity for which you would like a result when it finished.
4464 * When this activity exits, your
4465 * onActivityResult() method will be called with the given requestCode.
4466 * Using a negative requestCode is the same as calling
4467 * {@link #startActivity} (the activity is not launched as a sub-activity).
4469 * <p>Note that this method should only be used with Intent protocols
4470 * that are defined to return a result. In other protocols (such as
4471 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
4472 * not get the result when you expect. For example, if the activity you
4473 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
4474 * run in your task and thus you will immediately receive a cancel result.
4476 * <p>As a special case, if you call startActivityForResult() with a requestCode
4477 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
4478 * activity, then your window will not be displayed until a result is
4479 * returned back from the started activity. This is to avoid visible
4480 * flickering when redirecting to another activity.
4482 * <p>This method throws {@link android.content.ActivityNotFoundException}
4483 * if there was no Activity found to run the given Intent.
4485 * @param intent The intent to start.
4486 * @param requestCode If >= 0, this code will be returned in
4487 * onActivityResult() when the activity exits.
4488 * @param options Additional options for how the Activity should be started.
4489 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4490 * Context.startActivity(Intent, Bundle)} for more details.
4492 * @throws android.content.ActivityNotFoundException
4494 * @see #startActivity
4496 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
4497 @Nullable Bundle options) {
4498 if (mParent == null) {
4499 options = transferSpringboardActivityOptions(options);
4500 Instrumentation.ActivityResult ar =
4501 mInstrumentation.execStartActivity(
4502 this, mMainThread.getApplicationThread(), mToken, this,
4503 intent, requestCode, options);
4505 mMainThread.sendActivityResult(
4506 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4507 ar.getResultData());
4509 if (requestCode >= 0) {
4510 // If this start is requesting a result, we can avoid making
4511 // the activity visible until the result is received. Setting
4512 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4513 // activity hidden during this time, to avoid flickering.
4514 // This can only be done when a result is requested because
4515 // that guarantees we will get information back when the
4516 // activity is finished, no matter what happens to it.
4517 mStartedActivity = true;
4520 cancelInputsAndStartExitTransition(options);
4521 // TODO Consider clearing/flushing other event sources and events for child windows.
4523 if (options != null) {
4524 mParent.startActivityFromChild(this, intent, requestCode, options);
4526 // Note we want to go through this method for compatibility with
4527 // existing applications that may have overridden it.
4528 mParent.startActivityFromChild(this, intent, requestCode);
4534 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
4536 * @param options The ActivityOptions bundle used to start an Activity.
4538 private void cancelInputsAndStartExitTransition(Bundle options) {
4539 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
4540 if (decor != null) {
4541 decor.cancelPendingInputEvents();
4543 if (options != null && !isTopOfTask()) {
4544 mActivityTransitionState.startExitOutTransition(this, options);
4549 * Returns whether there are any activity transitions currently running on this
4550 * activity. A return value of {@code true} can mean that either an enter or
4551 * exit transition is running, including whether the background of the activity
4552 * is animating as a part of that transition.
4554 * @return true if a transition is currently running on this activity, false otherwise.
4556 public boolean isActivityTransitionRunning() {
4557 return mActivityTransitionState.isTransitionRunning();
4560 private Bundle transferSpringboardActivityOptions(Bundle options) {
4561 if (options == null && (mWindow != null && !mWindow.isActive())) {
4562 final ActivityOptions activityOptions = getActivityOptions();
4563 if (activityOptions != null &&
4564 activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
4565 return activityOptions.toBundle();
4572 * @hide Implement to provide correct calling token.
4574 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
4575 startActivityForResultAsUser(intent, requestCode, null, user);
4579 * @hide Implement to provide correct calling token.
4581 public void startActivityForResultAsUser(Intent intent, int requestCode,
4582 @Nullable Bundle options, UserHandle user) {
4583 startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
4587 * @hide Implement to provide correct calling token.
4589 public void startActivityForResultAsUser(Intent intent, String resultWho, int requestCode,
4590 @Nullable Bundle options, UserHandle user) {
4591 if (mParent != null) {
4592 throw new RuntimeException("Can't be called from a child");
4594 options = transferSpringboardActivityOptions(options);
4595 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
4596 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
4599 mMainThread.sendActivityResult(
4600 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
4602 if (requestCode >= 0) {
4603 // If this start is requesting a result, we can avoid making
4604 // the activity visible until the result is received. Setting
4605 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4606 // activity hidden during this time, to avoid flickering.
4607 // This can only be done when a result is requested because
4608 // that guarantees we will get information back when the
4609 // activity is finished, no matter what happens to it.
4610 mStartedActivity = true;
4613 cancelInputsAndStartExitTransition(options);
4617 * @hide Implement to provide correct calling token.
4619 public void startActivityAsUser(Intent intent, UserHandle user) {
4620 startActivityAsUser(intent, null, user);
4624 * @hide Implement to provide correct calling token.
4626 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
4627 if (mParent != null) {
4628 throw new RuntimeException("Can't be called from a child");
4630 options = transferSpringboardActivityOptions(options);
4631 Instrumentation.ActivityResult ar =
4632 mInstrumentation.execStartActivity(
4633 this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
4634 intent, -1, options, user);
4636 mMainThread.sendActivityResult(
4637 mToken, mEmbeddedID, -1, ar.getResultCode(),
4638 ar.getResultData());
4640 cancelInputsAndStartExitTransition(options);
4644 * Start a new activity as if it was started by the activity that started our
4645 * current activity. This is for the resolver and chooser activities, which operate
4646 * as intermediaries that dispatch their intent to the target the user selects -- to
4647 * do this, they must perform all security checks including permission grants as if
4648 * their launch had come from the original activity.
4649 * @param intent The Intent to start.
4650 * @param options ActivityOptions or null.
4651 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
4652 * caller it is doing the start is, is actually allowed to start the target activity.
4653 * If you set this to true, you must set an explicit component in the Intent and do any
4654 * appropriate security checks yourself.
4655 * @param userId The user the new activity should run as.
4658 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
4659 boolean ignoreTargetSecurity, int userId) {
4660 if (mParent != null) {
4661 throw new RuntimeException("Can't be called from a child");
4663 options = transferSpringboardActivityOptions(options);
4664 Instrumentation.ActivityResult ar =
4665 mInstrumentation.execStartActivityAsCaller(
4666 this, mMainThread.getApplicationThread(), mToken, this,
4667 intent, -1, options, ignoreTargetSecurity, userId);
4669 mMainThread.sendActivityResult(
4670 mToken, mEmbeddedID, -1, ar.getResultCode(),
4671 ar.getResultData());
4673 cancelInputsAndStartExitTransition(options);
4677 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
4678 * Intent, int, int, int, Bundle)} with no options.
4680 * @param intent The IntentSender to launch.
4681 * @param requestCode If >= 0, this code will be returned in
4682 * onActivityResult() when the activity exits.
4683 * @param fillInIntent If non-null, this will be provided as the
4684 * intent parameter to {@link IntentSender#sendIntent}.
4685 * @param flagsMask Intent flags in the original IntentSender that you
4686 * would like to change.
4687 * @param flagsValues Desired values for any bits set in
4688 * <var>flagsMask</var>
4689 * @param extraFlags Always set to 0.
4691 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4692 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4693 throws IntentSender.SendIntentException {
4694 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
4695 flagsValues, extraFlags, null);
4699 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
4700 * to use a IntentSender to describe the activity to be started. If
4701 * the IntentSender is for an activity, that activity will be started
4702 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
4703 * here; otherwise, its associated action will be executed (such as
4704 * sending a broadcast) as if you had called
4705 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
4707 * @param intent The IntentSender to launch.
4708 * @param requestCode If >= 0, this code will be returned in
4709 * onActivityResult() when the activity exits.
4710 * @param fillInIntent If non-null, this will be provided as the
4711 * intent parameter to {@link IntentSender#sendIntent}.
4712 * @param flagsMask Intent flags in the original IntentSender that you
4713 * would like to change.
4714 * @param flagsValues Desired values for any bits set in
4715 * <var>flagsMask</var>
4716 * @param extraFlags Always set to 0.
4717 * @param options Additional options for how the Activity should be started.
4718 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4719 * Context.startActivity(Intent, Bundle)} for more details. If options
4720 * have also been supplied by the IntentSender, options given here will
4721 * override any that conflict with those given by the IntentSender.
4723 public void startIntentSenderForResult(IntentSender intent, int requestCode,
4724 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4725 Bundle options) throws IntentSender.SendIntentException {
4726 if (mParent == null) {
4727 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
4728 flagsMask, flagsValues, options);
4729 } else if (options != null) {
4730 mParent.startIntentSenderFromChild(this, intent, requestCode,
4731 fillInIntent, flagsMask, flagsValues, extraFlags, options);
4733 // Note we want to go through this call for compatibility with
4734 // existing applications that may have overridden the method.
4735 mParent.startIntentSenderFromChild(this, intent, requestCode,
4736 fillInIntent, flagsMask, flagsValues, extraFlags);
4740 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
4741 Intent fillInIntent, int flagsMask, int flagsValues,
4743 throws IntentSender.SendIntentException {
4745 String resolvedType = null;
4746 if (fillInIntent != null) {
4747 fillInIntent.migrateExtraStreamToClipData();
4748 fillInIntent.prepareToLeaveProcess(this);
4749 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
4751 int result = ActivityManager.getService()
4752 .startActivityIntentSender(mMainThread.getApplicationThread(),
4753 intent != null ? intent.getTarget() : null,
4754 intent != null ? intent.getWhitelistToken() : null,
4755 fillInIntent, resolvedType, mToken, who,
4756 requestCode, flagsMask, flagsValues, options);
4757 if (result == ActivityManager.START_CANCELED) {
4758 throw new IntentSender.SendIntentException();
4760 Instrumentation.checkStartActivityResult(result, null);
4761 } catch (RemoteException e) {
4763 if (requestCode >= 0) {
4764 // If this start is requesting a result, we can avoid making
4765 // the activity visible until the result is received. Setting
4766 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4767 // activity hidden during this time, to avoid flickering.
4768 // This can only be done when a result is requested because
4769 // that guarantees we will get information back when the
4770 // activity is finished, no matter what happens to it.
4771 mStartedActivity = true;
4776 * Same as {@link #startActivity(Intent, Bundle)} with no options
4779 * @param intent The intent to start.
4781 * @throws android.content.ActivityNotFoundException
4783 * @see #startActivity(Intent, Bundle)
4784 * @see #startActivityForResult
4787 public void startActivity(Intent intent) {
4788 this.startActivity(intent, null);
4792 * Launch a new activity. You will not receive any information about when
4793 * the activity exits. This implementation overrides the base version,
4794 * providing information about
4795 * the activity performing the launch. Because of this additional
4796 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4797 * required; if not specified, the new activity will be added to the
4798 * task of the caller.
4800 * <p>This method throws {@link android.content.ActivityNotFoundException}
4801 * if there was no Activity found to run the given Intent.
4803 * @param intent The intent to start.
4804 * @param options Additional options for how the Activity should be started.
4805 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4806 * Context.startActivity(Intent, Bundle)} for more details.
4808 * @throws android.content.ActivityNotFoundException
4810 * @see #startActivity(Intent)
4811 * @see #startActivityForResult
4814 public void startActivity(Intent intent, @Nullable Bundle options) {
4815 if (options != null) {
4816 startActivityForResult(intent, -1, options);
4818 // Note we want to go through this call for compatibility with
4819 // applications that may have overridden the method.
4820 startActivityForResult(intent, -1);
4825 * Same as {@link #startActivities(Intent[], Bundle)} with no options
4828 * @param intents The intents to start.
4830 * @throws android.content.ActivityNotFoundException
4832 * @see #startActivities(Intent[], Bundle)
4833 * @see #startActivityForResult
4836 public void startActivities(Intent[] intents) {
4837 startActivities(intents, null);
4841 * Launch a new activity. You will not receive any information about when
4842 * the activity exits. This implementation overrides the base version,
4843 * providing information about
4844 * the activity performing the launch. Because of this additional
4845 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
4846 * required; if not specified, the new activity will be added to the
4847 * task of the caller.
4849 * <p>This method throws {@link android.content.ActivityNotFoundException}
4850 * if there was no Activity found to run the given Intent.
4852 * @param intents The intents to start.
4853 * @param options Additional options for how the Activity should be started.
4854 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4855 * Context.startActivity(Intent, Bundle)} for more details.
4857 * @throws android.content.ActivityNotFoundException
4859 * @see #startActivities(Intent[])
4860 * @see #startActivityForResult
4863 public void startActivities(Intent[] intents, @Nullable Bundle options) {
4864 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
4865 mToken, this, intents, options);
4869 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
4872 * @param intent The IntentSender to launch.
4873 * @param fillInIntent If non-null, this will be provided as the
4874 * intent parameter to {@link IntentSender#sendIntent}.
4875 * @param flagsMask Intent flags in the original IntentSender that you
4876 * would like to change.
4877 * @param flagsValues Desired values for any bits set in
4878 * <var>flagsMask</var>
4879 * @param extraFlags Always set to 0.
4881 public void startIntentSender(IntentSender intent,
4882 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
4883 throws IntentSender.SendIntentException {
4884 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
4889 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
4891 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
4892 * for more information.
4894 * @param intent The IntentSender to launch.
4895 * @param fillInIntent If non-null, this will be provided as the
4896 * intent parameter to {@link IntentSender#sendIntent}.
4897 * @param flagsMask Intent flags in the original IntentSender that you
4898 * would like to change.
4899 * @param flagsValues Desired values for any bits set in
4900 * <var>flagsMask</var>
4901 * @param extraFlags Always set to 0.
4902 * @param options Additional options for how the Activity should be started.
4903 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4904 * Context.startActivity(Intent, Bundle)} for more details. If options
4905 * have also been supplied by the IntentSender, options given here will
4906 * override any that conflict with those given by the IntentSender.
4908 public void startIntentSender(IntentSender intent,
4909 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
4910 Bundle options) throws IntentSender.SendIntentException {
4911 if (options != null) {
4912 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4913 flagsValues, extraFlags, options);
4915 // Note we want to go through this call for compatibility with
4916 // applications that may have overridden the method.
4917 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
4918 flagsValues, extraFlags);
4923 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
4926 * @param intent The intent to start.
4927 * @param requestCode If >= 0, this code will be returned in
4928 * onActivityResult() when the activity exits, as described in
4929 * {@link #startActivityForResult}.
4931 * @return If a new activity was launched then true is returned; otherwise
4932 * false is returned and you must handle the Intent yourself.
4934 * @see #startActivity
4935 * @see #startActivityForResult
4937 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4939 return startActivityIfNeeded(intent, requestCode, null);
4943 * A special variation to launch an activity only if a new activity
4944 * instance is needed to handle the given Intent. In other words, this is
4945 * just like {@link #startActivityForResult(Intent, int)} except: if you are
4946 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
4947 * singleTask or singleTop
4948 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
4950 * that handles <var>intent</var> is the same as your currently running
4951 * activity, then a new instance is not needed. In this case, instead of
4952 * the normal behavior of calling {@link #onNewIntent} this function will
4953 * return and you can handle the Intent yourself.
4955 * <p>This function can only be called from a top-level activity; if it is
4956 * called from a child activity, a runtime exception will be thrown.
4958 * @param intent The intent to start.
4959 * @param requestCode If >= 0, this code will be returned in
4960 * onActivityResult() when the activity exits, as described in
4961 * {@link #startActivityForResult}.
4962 * @param options Additional options for how the Activity should be started.
4963 * See {@link android.content.Context#startActivity(Intent, Bundle)}
4964 * Context.startActivity(Intent, Bundle)} for more details.
4966 * @return If a new activity was launched then true is returned; otherwise
4967 * false is returned and you must handle the Intent yourself.
4969 * @see #startActivity
4970 * @see #startActivityForResult
4972 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
4973 int requestCode, @Nullable Bundle options) {
4974 if (mParent == null) {
4975 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
4977 Uri referrer = onProvideReferrer();
4978 if (referrer != null) {
4979 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
4981 intent.migrateExtraStreamToClipData();
4982 intent.prepareToLeaveProcess(this);
4983 result = ActivityManager.getService()
4984 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
4985 intent, intent.resolveTypeIfNeeded(getContentResolver()), mToken,
4986 mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4988 } catch (RemoteException e) {
4992 Instrumentation.checkStartActivityResult(result, intent);
4994 if (requestCode >= 0) {
4995 // If this start is requesting a result, we can avoid making
4996 // the activity visible until the result is received. Setting
4997 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4998 // activity hidden during this time, to avoid flickering.
4999 // This can only be done when a result is requested because
5000 // that guarantees we will get information back when the
5001 // activity is finished, no matter what happens to it.
5002 mStartedActivity = true;
5004 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
5007 throw new UnsupportedOperationException(
5008 "startActivityIfNeeded can only be called from a top-level activity");
5012 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
5015 * @param intent The intent to dispatch to the next activity. For
5016 * correct behavior, this must be the same as the Intent that started
5017 * your own activity; the only changes you can make are to the extras
5020 * @return Returns a boolean indicating whether there was another Activity
5021 * to start: true if there was a next activity to start, false if there
5022 * wasn't. In general, if true is returned you will then want to call
5023 * finish() on yourself.
5025 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
5026 return startNextMatchingActivity(intent, null);
5030 * Special version of starting an activity, for use when you are replacing
5031 * other activity components. You can use this to hand the Intent off
5032 * to the next Activity that can handle it. You typically call this in
5033 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
5035 * @param intent The intent to dispatch to the next activity. For
5036 * correct behavior, this must be the same as the Intent that started
5037 * your own activity; the only changes you can make are to the extras
5039 * @param options Additional options for how the Activity should be started.
5040 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5041 * Context.startActivity(Intent, Bundle)} for more details.
5043 * @return Returns a boolean indicating whether there was another Activity
5044 * to start: true if there was a next activity to start, false if there
5045 * wasn't. In general, if true is returned you will then want to call
5046 * finish() on yourself.
5048 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
5049 @Nullable Bundle options) {
5050 if (mParent == null) {
5052 intent.migrateExtraStreamToClipData();
5053 intent.prepareToLeaveProcess(this);
5054 return ActivityManager.getService()
5055 .startNextMatchingActivity(mToken, intent, options);
5056 } catch (RemoteException e) {
5062 throw new UnsupportedOperationException(
5063 "startNextMatchingActivity can only be called from a top-level activity");
5067 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
5070 * @param child The activity making the call.
5071 * @param intent The intent to start.
5072 * @param requestCode Reply request code. < 0 if reply is not requested.
5074 * @throws android.content.ActivityNotFoundException
5076 * @see #startActivity
5077 * @see #startActivityForResult
5079 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5081 startActivityFromChild(child, intent, requestCode, null);
5085 * This is called when a child activity of this one calls its
5086 * {@link #startActivity} or {@link #startActivityForResult} method.
5088 * <p>This method throws {@link android.content.ActivityNotFoundException}
5089 * if there was no Activity found to run the given Intent.
5091 * @param child The activity making the call.
5092 * @param intent The intent to start.
5093 * @param requestCode Reply request code. < 0 if reply is not requested.
5094 * @param options Additional options for how the Activity should be started.
5095 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5096 * Context.startActivity(Intent, Bundle)} for more details.
5098 * @throws android.content.ActivityNotFoundException
5100 * @see #startActivity
5101 * @see #startActivityForResult
5103 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
5104 int requestCode, @Nullable Bundle options) {
5105 options = transferSpringboardActivityOptions(options);
5106 Instrumentation.ActivityResult ar =
5107 mInstrumentation.execStartActivity(
5108 this, mMainThread.getApplicationThread(), mToken, child,
5109 intent, requestCode, options);
5111 mMainThread.sendActivityResult(
5112 mToken, child.mEmbeddedID, requestCode,
5113 ar.getResultCode(), ar.getResultData());
5115 cancelInputsAndStartExitTransition(options);
5119 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
5122 * @param fragment The fragment making the call.
5123 * @param intent The intent to start.
5124 * @param requestCode Reply request code. < 0 if reply is not requested.
5126 * @throws android.content.ActivityNotFoundException
5128 * @see Fragment#startActivity
5129 * @see Fragment#startActivityForResult
5131 public void startActivityFromFragment(@NonNull Fragment fragment,
5132 @RequiresPermission Intent intent, int requestCode) {
5133 startActivityFromFragment(fragment, intent, requestCode, null);
5137 * This is called when a Fragment in this activity calls its
5138 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
5141 * <p>This method throws {@link android.content.ActivityNotFoundException}
5142 * if there was no Activity found to run the given Intent.
5144 * @param fragment The fragment making the call.
5145 * @param intent The intent to start.
5146 * @param requestCode Reply request code. < 0 if reply is not requested.
5147 * @param options Additional options for how the Activity should be started.
5148 * See {@link android.content.Context#startActivity(Intent, Bundle)}
5149 * Context.startActivity(Intent, Bundle)} for more details.
5151 * @throws android.content.ActivityNotFoundException
5153 * @see Fragment#startActivity
5154 * @see Fragment#startActivityForResult
5156 public void startActivityFromFragment(@NonNull Fragment fragment,
5157 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
5158 startActivityForResult(fragment.mWho, intent, requestCode, options);
5164 public void startActivityAsUserFromFragment(@NonNull Fragment fragment,
5165 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
5167 startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
5174 public void startActivityForResult(
5175 String who, Intent intent, int requestCode, @Nullable Bundle options) {
5176 Uri referrer = onProvideReferrer();
5177 if (referrer != null) {
5178 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5180 options = transferSpringboardActivityOptions(options);
5181 Instrumentation.ActivityResult ar =
5182 mInstrumentation.execStartActivity(
5183 this, mMainThread.getApplicationThread(), mToken, who,
5184 intent, requestCode, options);
5186 mMainThread.sendActivityResult(
5187 mToken, who, requestCode,
5188 ar.getResultCode(), ar.getResultData());
5190 cancelInputsAndStartExitTransition(options);
5197 public boolean canStartActivityForResult() {
5202 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
5203 * int, Intent, int, int, int, Bundle)} with no options.
5205 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5206 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5208 throws IntentSender.SendIntentException {
5209 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
5210 flagsMask, flagsValues, extraFlags, null);
5214 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
5215 * taking a IntentSender; see
5216 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5217 * for more information.
5219 public void startIntentSenderFromChild(Activity child, IntentSender intent,
5220 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5221 int extraFlags, @Nullable Bundle options)
5222 throws IntentSender.SendIntentException {
5223 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
5224 flagsMask, flagsValues, options);
5228 * Like {@link #startIntentSenderFromChild}, but taking a Fragment; see
5229 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
5230 * for more information.
5234 public void startIntentSenderFromChildFragment(Fragment child, IntentSender intent,
5235 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
5236 int extraFlags, @Nullable Bundle options)
5237 throws IntentSender.SendIntentException {
5238 startIntentSenderForResultInner(intent, child.mWho, requestCode, fillInIntent,
5239 flagsMask, flagsValues, options);
5243 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
5244 * or {@link #finish} to specify an explicit transition animation to
5247 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
5248 * to using this with starting activities is to supply the desired animation
5249 * information through a {@link ActivityOptions} bundle to
5250 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
5251 * you to specify a custom animation even when starting an activity from
5252 * outside the context of the current top activity.
5254 * @param enterAnim A resource ID of the animation resource to use for
5255 * the incoming activity. Use 0 for no animation.
5256 * @param exitAnim A resource ID of the animation resource to use for
5257 * the outgoing activity. Use 0 for no animation.
5259 public void overridePendingTransition(int enterAnim, int exitAnim) {
5261 ActivityManager.getService().overridePendingTransition(
5262 mToken, getPackageName(), enterAnim, exitAnim);
5263 } catch (RemoteException e) {
5268 * Call this to set the result that your activity will return to its
5271 * @param resultCode The result code to propagate back to the originating
5272 * activity, often RESULT_CANCELED or RESULT_OK
5274 * @see #RESULT_CANCELED
5276 * @see #RESULT_FIRST_USER
5277 * @see #setResult(int, Intent)
5279 public final void setResult(int resultCode) {
5280 synchronized (this) {
5281 mResultCode = resultCode;
5287 * Call this to set the result that your activity will return to its
5290 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
5291 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
5292 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
5293 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
5294 * Activity receiving the result access to the specific URIs in the Intent.
5295 * Access will remain until the Activity has finished (it will remain across the hosting
5296 * process being killed and other temporary destruction) and will be added
5297 * to any existing set of URI permissions it already holds.
5299 * @param resultCode The result code to propagate back to the originating
5300 * activity, often RESULT_CANCELED or RESULT_OK
5301 * @param data The data to propagate back to the originating activity.
5303 * @see #RESULT_CANCELED
5305 * @see #RESULT_FIRST_USER
5306 * @see #setResult(int)
5308 public final void setResult(int resultCode, Intent data) {
5309 synchronized (this) {
5310 mResultCode = resultCode;
5316 * Return information about who launched this activity. If the launching Intent
5317 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
5318 * that will be returned as-is; otherwise, if known, an
5319 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
5320 * package name that started the Intent will be returned. This may return null if no
5321 * referrer can be identified -- it is neither explicitly specified, nor is it known which
5322 * application package was involved.
5324 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
5325 * return the referrer that submitted that new intent to the activity. Otherwise, it
5326 * always returns the referrer of the original Intent.</p>
5328 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
5329 * referrer information, applications can spoof it.</p>
5332 public Uri getReferrer() {
5333 Intent intent = getIntent();
5335 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
5336 if (referrer != null) {
5339 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
5340 if (referrerName != null) {
5341 return Uri.parse(referrerName);
5343 } catch (BadParcelableException e) {
5344 Log.w(TAG, "Cannot read referrer from intent;"
5345 + " intent extras contain unknown custom Parcelable objects");
5347 if (mReferrer != null) {
5348 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
5354 * Override to generate the desired referrer for the content currently being shown
5355 * by the app. The default implementation returns null, meaning the referrer will simply
5356 * be the android-app: of the package name of this activity. Return a non-null Uri to
5357 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
5359 public Uri onProvideReferrer() {
5364 * Return the name of the package that invoked this activity. This is who
5365 * the data in {@link #setResult setResult()} will be sent to. You can
5366 * use this information to validate that the recipient is allowed to
5369 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5370 * did not use the {@link #startActivityForResult}
5371 * form that includes a request code), then the calling package will be
5374 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
5375 * the result from this method was unstable. If the process hosting the calling
5376 * package was no longer running, it would return null instead of the proper package
5377 * name. You can use {@link #getCallingActivity()} and retrieve the package name
5378 * from that instead.</p>
5380 * @return The package of the activity that will receive your
5381 * reply, or null if none.
5384 public String getCallingPackage() {
5386 return ActivityManager.getService().getCallingPackage(mToken);
5387 } catch (RemoteException e) {
5393 * Return the name of the activity that invoked this activity. This is
5394 * who the data in {@link #setResult setResult()} will be sent to. You
5395 * can use this information to validate that the recipient is allowed to
5398 * <p class="note">Note: if the calling activity is not expecting a result (that is it
5399 * did not use the {@link #startActivityForResult}
5400 * form that includes a request code), then the calling package will be
5403 * @return The ComponentName of the activity that will receive your
5404 * reply, or null if none.
5407 public ComponentName getCallingActivity() {
5409 return ActivityManager.getService().getCallingActivity(mToken);
5410 } catch (RemoteException e) {
5416 * Control whether this activity's main window is visible. This is intended
5417 * only for the special case of an activity that is not going to show a
5418 * UI itself, but can't just finish prior to onResume() because it needs
5419 * to wait for a service binding or such. Setting this to false allows
5420 * you to prevent your UI from being shown during that time.
5422 * <p>The default value for this is taken from the
5423 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
5425 public void setVisible(boolean visible) {
5426 if (mVisibleFromClient != visible) {
5427 mVisibleFromClient = visible;
5428 if (mVisibleFromServer) {
5429 if (visible) makeVisible();
5430 else mDecor.setVisibility(View.INVISIBLE);
5435 void makeVisible() {
5436 if (!mWindowAdded) {
5437 ViewManager wm = getWindowManager();
5438 wm.addView(mDecor, getWindow().getAttributes());
5439 mWindowAdded = true;
5441 mDecor.setVisibility(View.VISIBLE);
5445 * Check to see whether this activity is in the process of finishing,
5446 * either because you called {@link #finish} on it or someone else
5447 * has requested that it finished. This is often used in
5448 * {@link #onPause} to determine whether the activity is simply pausing or
5449 * completely finishing.
5451 * @return If the activity is finishing, returns true; else returns false.
5455 public boolean isFinishing() {
5460 * Returns true if the final {@link #onDestroy()} call has been made
5461 * on the Activity, so this instance is now dead.
5463 public boolean isDestroyed() {
5468 * Check to see whether this activity is in the process of being destroyed in order to be
5469 * recreated with a new configuration. This is often used in
5470 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
5471 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
5473 * @return If the activity is being torn down in order to be recreated with a new configuration,
5474 * returns true; else returns false.
5476 public boolean isChangingConfigurations() {
5477 return mChangingConfigurations;
5481 * Cause this Activity to be recreated with a new instance. This results
5482 * in essentially the same flow as when the Activity is created due to
5483 * a configuration change -- the current instance will go through its
5484 * lifecycle to {@link #onDestroy} and a new instance then created after it.
5486 public void recreate() {
5487 if (mParent != null) {
5488 throw new IllegalStateException("Can only be called on top-level activity");
5490 if (Looper.myLooper() != mMainThread.getLooper()) {
5491 throw new IllegalStateException("Must be called from main thread");
5494 ActivityManager.getService().requestActivityRelaunch(mToken);
5495 } catch (RemoteException e) {
5500 * Finishes the current activity and specifies whether to remove the task associated with this
5503 private void finish(int finishTask) {
5504 if (mParent == null) {
5507 synchronized (this) {
5508 resultCode = mResultCode;
5509 resultData = mResultData;
5511 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
5513 if (resultData != null) {
5514 resultData.prepareToLeaveProcess(this);
5516 if (ActivityManager.getService()
5517 .finishActivity(mToken, resultCode, resultData, finishTask)) {
5520 } catch (RemoteException e) {
5524 mParent.finishFromChild(this);
5527 // Activity was launched when user tapped a link in the Autofill Save UI - Save UI must
5529 if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
5530 getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_RESTORE,
5531 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN));
5536 * Call this when your activity is done and should be closed. The
5537 * ActivityResult is propagated back to whoever launched you via
5538 * onActivityResult().
5540 public void finish() {
5541 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
5545 * Finish this activity as well as all activities immediately below it
5546 * in the current task that have the same affinity. This is typically
5547 * used when an application can be launched on to another task (such as
5548 * from an ACTION_VIEW of a content type it understands) and the user
5549 * has used the up navigation to switch out of the current task and in
5550 * to its own task. In this case, if the user has navigated down into
5551 * any other activities of the second application, all of those should
5552 * be removed from the original task as part of the task switch.
5554 * <p>Note that this finish does <em>not</em> allow you to deliver results
5555 * to the previous activity, and an exception will be thrown if you are trying
5558 public void finishAffinity() {
5559 if (mParent != null) {
5560 throw new IllegalStateException("Can not be called from an embedded activity");
5562 if (mResultCode != RESULT_CANCELED || mResultData != null) {
5563 throw new IllegalStateException("Can not be called to deliver a result");
5566 if (ActivityManager.getService().finishActivityAffinity(mToken)) {
5569 } catch (RemoteException e) {
5575 * This is called when a child activity of this one calls its
5576 * {@link #finish} method. The default implementation simply calls
5577 * finish() on this activity (the parent), finishing the entire group.
5579 * @param child The activity making the call.
5583 public void finishFromChild(Activity child) {
5588 * Reverses the Activity Scene entry Transition and triggers the calling Activity
5589 * to reverse its exit Transition. When the exit Transition completes,
5590 * {@link #finish()} is called. If no entry Transition was used, finish() is called
5591 * immediately and the Activity exit Transition is run.
5592 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
5594 public void finishAfterTransition() {
5595 if (!mActivityTransitionState.startExitBackTransition(this)) {
5601 * Force finish another activity that you had previously started with
5602 * {@link #startActivityForResult}.
5604 * @param requestCode The request code of the activity that you had
5605 * given to startActivityForResult(). If there are multiple
5606 * activities started with this request code, they
5607 * will all be finished.
5609 public void finishActivity(int requestCode) {
5610 if (mParent == null) {
5612 ActivityManager.getService()
5613 .finishSubActivity(mToken, mEmbeddedID, requestCode);
5614 } catch (RemoteException e) {
5618 mParent.finishActivityFromChild(this, requestCode);
5623 * This is called when a child activity of this one calls its
5626 * @param child The activity making the call.
5627 * @param requestCode Request code that had been used to start the
5630 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
5632 ActivityManager.getService()
5633 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
5634 } catch (RemoteException e) {
5640 * Call this when your activity is done and should be closed and the task should be completely
5641 * removed as a part of finishing the root activity of the task.
5643 public void finishAndRemoveTask() {
5644 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
5648 * Ask that the local app instance of this activity be released to free up its memory.
5649 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
5650 * a new instance of the activity will later be re-created if needed due to the user
5651 * navigating back to it.
5653 * @return Returns true if the activity was in a state that it has started the process
5654 * of destroying its current instance; returns false if for any reason this could not
5655 * be done: it is currently visible to the user, it is already being destroyed, it is
5656 * being finished, it hasn't yet saved its state, etc.
5658 public boolean releaseInstance() {
5660 return ActivityManager.getService().releaseActivityInstance(mToken);
5661 } catch (RemoteException e) {
5668 * Called when an activity you launched exits, giving you the requestCode
5669 * you started it with, the resultCode it returned, and any additional
5670 * data from it. The <var>resultCode</var> will be
5671 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
5672 * didn't return any result, or crashed during its operation.
5674 * <p>You will receive this call immediately before onResume() when your
5675 * activity is re-starting.
5677 * <p>This method is never invoked if your activity sets
5678 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5679 * <code>true</code>.
5681 * @param requestCode The integer request code originally supplied to
5682 * startActivityForResult(), allowing you to identify who this
5684 * @param resultCode The integer result code returned by the child activity
5685 * through its setResult().
5686 * @param data An Intent, which can return result data to the caller
5687 * (various data can be attached to Intent "extras").
5689 * @see #startActivityForResult
5690 * @see #createPendingResult
5691 * @see #setResult(int)
5693 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
5697 * Called when an activity you launched with an activity transition exposes this
5698 * Activity through a returning activity transition, giving you the resultCode
5699 * and any additional data from it. This method will only be called if the activity
5700 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
5701 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
5703 * <p>The purpose of this function is to let the called Activity send a hint about
5704 * its state so that this underlying Activity can prepare to be exposed. A call to
5705 * this method does not guarantee that the called Activity has or will be exiting soon.
5706 * It only indicates that it will expose this Activity's Window and it has
5707 * some data to pass to prepare it.</p>
5709 * @param resultCode The integer result code returned by the child activity
5710 * through its setResult().
5711 * @param data An Intent, which can return result data to the caller
5712 * (various data can be attached to Intent "extras").
5714 public void onActivityReenter(int resultCode, Intent data) {
5718 * Create a new PendingIntent object which you can hand to others
5719 * for them to use to send result data back to your
5720 * {@link #onActivityResult} callback. The created object will be either
5721 * one-shot (becoming invalid after a result is sent back) or multiple
5722 * (allowing any number of results to be sent through it).
5724 * @param requestCode Private request code for the sender that will be
5725 * associated with the result data when it is returned. The sender can not
5726 * modify this value, allowing you to identify incoming results.
5727 * @param data Default data to supply in the result, which may be modified
5729 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
5730 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
5731 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
5732 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
5733 * or any of the flags as supported by
5734 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
5735 * of the intent that can be supplied when the actual send happens.
5737 * @return Returns an existing or new PendingIntent matching the given
5738 * parameters. May return null only if
5739 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
5742 * @see PendingIntent
5744 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
5745 @PendingIntent.Flags int flags) {
5746 String packageName = getPackageName();
5748 data.prepareToLeaveProcess(this);
5749 IIntentSender target =
5750 ActivityManager.getService().getIntentSender(
5751 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName,
5752 mParent == null ? mToken : mParent.mToken,
5753 mEmbeddedID, requestCode, new Intent[] { data }, null, flags, null,
5754 UserHandle.myUserId());
5755 return target != null ? new PendingIntent(target) : null;
5756 } catch (RemoteException e) {
5763 * Change the desired orientation of this activity. If the activity
5764 * is currently in the foreground or otherwise impacting the screen
5765 * orientation, the screen will immediately be changed (possibly causing
5766 * the activity to be restarted). Otherwise, this will be used the next
5767 * time the activity is visible.
5769 * @param requestedOrientation An orientation constant as used in
5770 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5772 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
5773 if (mParent == null) {
5775 ActivityManager.getService().setRequestedOrientation(
5776 mToken, requestedOrientation);
5777 } catch (RemoteException e) {
5781 mParent.setRequestedOrientation(requestedOrientation);
5786 * Return the current requested orientation of the activity. This will
5787 * either be the orientation requested in its component's manifest, or
5788 * the last requested orientation given to
5789 * {@link #setRequestedOrientation(int)}.
5791 * @return Returns an orientation constant as used in
5792 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
5794 @ActivityInfo.ScreenOrientation
5795 public int getRequestedOrientation() {
5796 if (mParent == null) {
5798 return ActivityManager.getService()
5799 .getRequestedOrientation(mToken);
5800 } catch (RemoteException e) {
5804 return mParent.getRequestedOrientation();
5806 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
5810 * Return the identifier of the task this activity is in. This identifier
5811 * will remain the same for the lifetime of the activity.
5813 * @return Task identifier, an opaque integer.
5815 public int getTaskId() {
5817 return ActivityManager.getService()
5818 .getTaskForActivity(mToken, false);
5819 } catch (RemoteException e) {
5825 * Return whether this activity is the root of a task. The root is the
5826 * first activity in a task.
5828 * @return True if this is the root activity, else false.
5831 public boolean isTaskRoot() {
5833 return ActivityManager.getService().getTaskForActivity(mToken, true) >= 0;
5834 } catch (RemoteException e) {
5840 * Move the task containing this activity to the back of the activity
5841 * stack. The activity's order within the task is unchanged.
5843 * @param nonRoot If false then this only works if the activity is the root
5844 * of a task; if true it will work for any activity in
5847 * @return If the task was moved (or it was already at the
5848 * back) true is returned, else false.
5850 public boolean moveTaskToBack(boolean nonRoot) {
5852 return ActivityManager.getService().moveActivityTaskToBack(
5854 } catch (RemoteException e) {
5861 * Returns class name for this activity with the package prefix removed.
5862 * This is the default name used to read and write settings.
5864 * @return The local class name.
5867 public String getLocalClassName() {
5868 final String pkg = getPackageName();
5869 final String cls = mComponent.getClassName();
5870 int packageLen = pkg.length();
5871 if (!cls.startsWith(pkg) || cls.length() <= packageLen
5872 || cls.charAt(packageLen) != '.') {
5875 return cls.substring(packageLen+1);
5879 * Returns complete component name of this activity.
5881 * @return Returns the complete component name for this activity
5883 public ComponentName getComponentName()
5889 * Retrieve a {@link SharedPreferences} object for accessing preferences
5890 * that are private to this activity. This simply calls the underlying
5891 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
5892 * class name as the preferences name.
5894 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
5897 * @return Returns the single SharedPreferences instance that can be used
5898 * to retrieve and modify the preference values.
5900 public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
5901 return getSharedPreferences(getLocalClassName(), mode);
5904 private void ensureSearchManager() {
5905 if (mSearchManager != null) {
5910 mSearchManager = new SearchManager(this, null);
5911 } catch (ServiceNotFoundException e) {
5912 throw new IllegalStateException(e);
5917 public Object getSystemService(@ServiceName @NonNull String name) {
5918 if (getBaseContext() == null) {
5919 throw new IllegalStateException(
5920 "System services not available to Activities before onCreate()");
5923 if (WINDOW_SERVICE.equals(name)) {
5924 return mWindowManager;
5925 } else if (SEARCH_SERVICE.equals(name)) {
5926 ensureSearchManager();
5927 return mSearchManager;
5929 return super.getSystemService(name);
5933 * Change the title associated with this activity. If this is a
5934 * top-level activity, the title for its window will change. If it
5935 * is an embedded activity, the parent can do whatever it wants
5938 public void setTitle(CharSequence title) {
5940 onTitleChanged(title, mTitleColor);
5942 if (mParent != null) {
5943 mParent.onChildTitleChanged(this, title);
5948 * Change the title associated with this activity. If this is a
5949 * top-level activity, the title for its window will change. If it
5950 * is an embedded activity, the parent can do whatever it wants
5953 public void setTitle(int titleId) {
5954 setTitle(getText(titleId));
5958 * Change the color of the title associated with this activity.
5960 * This method is deprecated starting in API Level 11 and replaced by action
5961 * bar styles. For information on styling the Action Bar, read the <a
5962 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
5965 * @deprecated Use action bar styles instead.
5968 public void setTitleColor(int textColor) {
5969 mTitleColor = textColor;
5970 onTitleChanged(mTitle, textColor);
5973 public final CharSequence getTitle() {
5977 public final int getTitleColor() {
5981 protected void onTitleChanged(CharSequence title, int color) {
5983 final Window win = getWindow();
5985 win.setTitle(title);
5987 win.setTitleColor(color);
5990 if (mActionBar != null) {
5991 mActionBar.setWindowTitle(title);
5996 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
6000 * Sets information describing the task with this activity for presentation inside the Recents
6001 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
6002 * are traversed in order from the topmost activity to the bottommost. The traversal continues
6003 * for each property until a suitable value is found. For each task the taskDescription will be
6004 * returned in {@link android.app.ActivityManager.TaskDescription}.
6006 * @see ActivityManager#getRecentTasks
6007 * @see android.app.ActivityManager.TaskDescription
6009 * @param taskDescription The TaskDescription properties that describe the task with this activity
6011 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
6012 if (mTaskDescription != taskDescription) {
6013 mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
6014 // Scale the icon down to something reasonable if it is provided
6015 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
6016 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
6017 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
6019 mTaskDescription.setIcon(icon);
6023 ActivityManager.getService().setTaskDescription(mToken, mTaskDescription);
6024 } catch (RemoteException e) {
6029 * Sets the visibility of the progress bar in the title.
6031 * In order for the progress bar to be shown, the feature must be requested
6032 * via {@link #requestWindowFeature(int)}.
6034 * @param visible Whether to show the progress bars in the title.
6035 * @deprecated No longer supported starting in API 21.
6038 public final void setProgressBarVisibility(boolean visible) {
6039 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
6040 Window.PROGRESS_VISIBILITY_OFF);
6044 * Sets the visibility of the indeterminate progress bar in the title.
6046 * In order for the progress bar to be shown, the feature must be requested
6047 * via {@link #requestWindowFeature(int)}.
6049 * @param visible Whether to show the progress bars in the title.
6050 * @deprecated No longer supported starting in API 21.
6053 public final void setProgressBarIndeterminateVisibility(boolean visible) {
6054 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
6055 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
6059 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
6060 * is always indeterminate).
6062 * In order for the progress bar to be shown, the feature must be requested
6063 * via {@link #requestWindowFeature(int)}.
6065 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
6066 * @deprecated No longer supported starting in API 21.
6069 public final void setProgressBarIndeterminate(boolean indeterminate) {
6070 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6071 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
6072 : Window.PROGRESS_INDETERMINATE_OFF);
6076 * Sets the progress for the progress bars in the title.
6078 * In order for the progress bar to be shown, the feature must be requested
6079 * via {@link #requestWindowFeature(int)}.
6081 * @param progress The progress for the progress bar. Valid ranges are from
6082 * 0 to 10000 (both inclusive). If 10000 is given, the progress
6083 * bar will be completely filled and will fade out.
6084 * @deprecated No longer supported starting in API 21.
6087 public final void setProgress(int progress) {
6088 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
6092 * Sets the secondary progress for the progress bar in the title. This
6093 * progress is drawn between the primary progress (set via
6094 * {@link #setProgress(int)} and the background. It can be ideal for media
6095 * scenarios such as showing the buffering progress while the default
6096 * progress shows the play progress.
6098 * In order for the progress bar to be shown, the feature must be requested
6099 * via {@link #requestWindowFeature(int)}.
6101 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
6102 * 0 to 10000 (both inclusive).
6103 * @deprecated No longer supported starting in API 21.
6106 public final void setSecondaryProgress(int secondaryProgress) {
6107 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6108 secondaryProgress + Window.PROGRESS_SECONDARY_START);
6112 * Suggests an audio stream whose volume should be changed by the hardware
6115 * The suggested audio stream will be tied to the window of this Activity.
6116 * Volume requests which are received while the Activity is in the
6117 * foreground will affect this stream.
6119 * It is not guaranteed that the hardware volume controls will always change
6120 * this stream's volume (for example, if a call is in progress, its stream's
6121 * volume may be changed instead). To reset back to the default, use
6122 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
6124 * @param streamType The type of the audio stream whose volume should be
6125 * changed by the hardware volume controls.
6127 public final void setVolumeControlStream(int streamType) {
6128 getWindow().setVolumeControlStream(streamType);
6132 * Gets the suggested audio stream whose volume should be changed by the
6133 * hardware volume controls.
6135 * @return The suggested audio stream type whose volume should be changed by
6136 * the hardware volume controls.
6137 * @see #setVolumeControlStream(int)
6139 public final int getVolumeControlStream() {
6140 return getWindow().getVolumeControlStream();
6144 * Sets a {@link MediaController} to send media keys and volume changes to.
6146 * The controller will be tied to the window of this Activity. Media key and
6147 * volume events which are received while the Activity is in the foreground
6148 * will be forwarded to the controller and used to invoke transport controls
6149 * or adjust the volume. This may be used instead of or in addition to
6150 * {@link #setVolumeControlStream} to affect a specific session instead of a
6153 * It is not guaranteed that the hardware volume controls will always change
6154 * this session's volume (for example, if a call is in progress, its
6155 * stream's volume may be changed instead). To reset back to the default use
6156 * null as the controller.
6158 * @param controller The controller for the session which should receive
6159 * media keys and volume changes.
6161 public final void setMediaController(MediaController controller) {
6162 getWindow().setMediaController(controller);
6166 * Gets the controller which should be receiving media key and volume events
6167 * while this activity is in the foreground.
6169 * @return The controller which should receive events.
6170 * @see #setMediaController(android.media.session.MediaController)
6172 public final MediaController getMediaController() {
6173 return getWindow().getMediaController();
6177 * Runs the specified action on the UI thread. If the current thread is the UI
6178 * thread, then the action is executed immediately. If the current thread is
6179 * not the UI thread, the action is posted to the event queue of the UI thread.
6181 * @param action the action to run on the UI thread
6184 public final void runOnUiThread(Runnable action) {
6185 if (Thread.currentThread() != mUiThread) {
6186 mHandler.post(action);
6193 * Standard implementation of
6194 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
6195 * inflating with the LayoutInflater returned by {@link #getSystemService}.
6196 * This implementation does nothing and is for
6197 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
6198 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
6200 * @see android.view.LayoutInflater#createView
6201 * @see android.view.Window#getLayoutInflater
6204 public View onCreateView(String name, Context context, AttributeSet attrs) {
6209 * Standard implementation of
6210 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
6211 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
6212 * This implementation handles <fragment> tags to embed fragments inside
6215 * @see android.view.LayoutInflater#createView
6216 * @see android.view.Window#getLayoutInflater
6218 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
6219 if (!"fragment".equals(name)) {
6220 return onCreateView(name, context, attrs);
6223 return mFragments.onCreateView(parent, name, context, attrs);
6227 * Print the Activity's state into the given stream. This gets invoked if
6228 * you run "adb shell dumpsys activity <activity_component_name>".
6230 * @param prefix Desired prefix to prepend at each line of output.
6231 * @param fd The raw file descriptor that the dump is being sent to.
6232 * @param writer The PrintWriter to which you should dump your state. This will be
6233 * closed for you after you return.
6234 * @param args additional arguments to the dump request.
6236 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6237 dumpInner(prefix, fd, writer, args);
6240 void dumpInner(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
6241 writer.print(prefix); writer.print("Local Activity ");
6242 writer.print(Integer.toHexString(System.identityHashCode(this)));
6243 writer.println(" State:");
6244 String innerPrefix = prefix + " ";
6245 writer.print(innerPrefix); writer.print("mResumed=");
6246 writer.print(mResumed); writer.print(" mStopped=");
6247 writer.print(mStopped); writer.print(" mFinished=");
6248 writer.println(mFinished);
6249 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
6250 writer.println(mChangingConfigurations);
6251 writer.print(innerPrefix); writer.print("mCurrentConfig=");
6252 writer.println(mCurrentConfig);
6254 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
6255 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
6256 if (mVoiceInteractor != null) {
6257 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
6260 if (getWindow() != null &&
6261 getWindow().peekDecorView() != null &&
6262 getWindow().peekDecorView().getViewRootImpl() != null) {
6263 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
6266 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
6268 final AutofillManager afm = getAutofillManager();
6270 afm.dump(prefix, writer);
6275 * Bit indicating that this activity is "immersive" and should not be
6276 * interrupted by notifications if possible.
6278 * This value is initially set by the manifest property
6279 * <code>android:immersive</code> but may be changed at runtime by
6280 * {@link #setImmersive}.
6282 * @see #setImmersive(boolean)
6283 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6285 public boolean isImmersive() {
6287 return ActivityManager.getService().isImmersive(mToken);
6288 } catch (RemoteException e) {
6294 * Indication of whether this is the highest level activity in this task. Can be used to
6295 * determine whether an activity launched by this activity was placed in the same task or
6298 * @return true if this is the topmost, non-finishing activity in its task.
6300 private boolean isTopOfTask() {
6301 if (mToken == null || mWindow == null) {
6305 return ActivityManager.getService().isTopOfTask(getActivityToken());
6306 } catch (RemoteException e) {
6312 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} to a
6313 * fullscreen opaque Activity.
6315 * Call this whenever the background of a translucent Activity has changed to become opaque.
6316 * Doing so will allow the {@link android.view.Surface} of the Activity behind to be released.
6318 * This call has no effect on non-translucent activities or on activities with the
6319 * {@link android.R.attr#windowIsFloating} attribute.
6321 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
6323 * @see TranslucentConversionListener
6328 public void convertFromTranslucent() {
6330 mTranslucentCallback = null;
6331 if (ActivityManager.getService().convertFromTranslucent(mToken)) {
6332 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
6334 } catch (RemoteException e) {
6340 * Convert a translucent themed Activity {@link android.R.attr#windowIsTranslucent} back from
6341 * opaque to translucent following a call to {@link #convertFromTranslucent()}.
6343 * Calling this allows the Activity behind this one to be seen again. Once all such Activities
6344 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
6345 * be called indicating that it is safe to make this activity translucent again. Until
6346 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
6347 * behind the frontmost Activity will be indeterminate.
6349 * This call has no effect on non-translucent activities or on activities with the
6350 * {@link android.R.attr#windowIsFloating} attribute.
6352 * @param callback the method to call when all visible Activities behind this one have been
6353 * drawn and it is safe to make this Activity translucent again.
6354 * @param options activity options delivered to the activity below this one. The options
6355 * are retrieved using {@link #getActivityOptions}.
6356 * @return <code>true</code> if Window was opaque and will become translucent or
6357 * <code>false</code> if window was translucent and no change needed to be made.
6359 * @see #convertFromTranslucent()
6360 * @see TranslucentConversionListener
6365 public boolean convertToTranslucent(TranslucentConversionListener callback,
6366 ActivityOptions options) {
6367 boolean drawComplete;
6369 mTranslucentCallback = callback;
6370 mChangeCanvasToTranslucent = ActivityManager.getService().convertToTranslucent(
6371 mToken, options == null ? null : options.toBundle());
6372 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6373 drawComplete = true;
6374 } catch (RemoteException e) {
6375 // Make callback return as though it timed out.
6376 mChangeCanvasToTranslucent = false;
6377 drawComplete = false;
6379 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
6380 // Window is already translucent.
6381 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6383 return mChangeCanvasToTranslucent;
6387 void onTranslucentConversionComplete(boolean drawComplete) {
6388 if (mTranslucentCallback != null) {
6389 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
6390 mTranslucentCallback = null;
6392 if (mChangeCanvasToTranslucent) {
6393 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
6398 public void onNewActivityOptions(ActivityOptions options) {
6399 mActivityTransitionState.setEnterActivityOptions(this, options);
6401 mActivityTransitionState.enterReady(this);
6406 * Retrieve the ActivityOptions passed in from the launching activity or passed back
6407 * from an activity launched by this activity in its call to {@link
6408 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
6410 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
6413 ActivityOptions getActivityOptions() {
6415 return ActivityOptions.fromBundle(
6416 ActivityManager.getService().getActivityOptions(mToken));
6417 } catch (RemoteException e) {
6423 * Activities that want to remain visible behind a translucent activity above them must call
6424 * this method anytime between the start of {@link #onResume()} and the return from
6425 * {@link #onPause()}. If this call is successful then the activity will remain visible after
6426 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
6428 * <p>The actions of this call are reset each time that this activity is brought to the
6429 * front. That is, every time {@link #onResume()} is called the activity will be assumed
6430 * to not have requested visible behind. Therefore, if you want this activity to continue to
6431 * be visible in the background you must call this method again.
6433 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
6434 * for dialog and translucent activities.
6436 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
6437 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
6439 * <p>False will be returned any time this method is called between the return of onPause and
6440 * the next call to onResume.
6442 * @deprecated This method's functionality is no longer supported as of
6443 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6445 * @param visible true to notify the system that the activity wishes to be visible behind other
6446 * translucent activities, false to indicate otherwise. Resources must be
6447 * released when passing false to this method.
6449 * @return the resulting visibiity state. If true the activity will remain visible beyond
6450 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
6451 * then the activity may not count on being visible behind other translucent activities,
6452 * and must stop any media playback and release resources.
6453 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
6454 * the return value must be checked.
6456 * @see #onVisibleBehindCanceled()
6459 public boolean requestVisibleBehind(boolean visible) {
6464 * Called when a translucent activity over this activity is becoming opaque or another
6465 * activity is being launched. Activities that override this method must call
6466 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
6468 * <p>When this method is called the activity has 500 msec to release any resources it may be
6469 * using while visible in the background.
6470 * If the activity has not returned from this method in 500 msec the system will destroy
6471 * the activity and kill the process in order to recover the resources for another
6472 * process. Otherwise {@link #onStop()} will be called following return.
6474 * @see #requestVisibleBehind(boolean)
6476 * @deprecated This method's functionality is no longer supported as of
6477 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6481 public void onVisibleBehindCanceled() {
6486 * Translucent activities may call this to determine if there is an activity below them that
6487 * is currently set to be visible in the background.
6489 * @deprecated This method's functionality is no longer supported as of
6490 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6492 * @return true if an activity below is set to visible according to the most recent call to
6493 * {@link #requestVisibleBehind(boolean)}, false otherwise.
6495 * @see #requestVisibleBehind(boolean)
6496 * @see #onVisibleBehindCanceled()
6497 * @see #onBackgroundVisibleBehindChanged(boolean)
6502 public boolean isBackgroundVisibleBehind() {
6507 * The topmost foreground activity will receive this call when the background visibility state
6508 * of the activity below it changes.
6510 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
6511 * due to a background activity finishing itself.
6513 * @deprecated This method's functionality is no longer supported as of
6514 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
6516 * @param visible true if a background activity is visible, false otherwise.
6518 * @see #requestVisibleBehind(boolean)
6519 * @see #onVisibleBehindCanceled()
6524 public void onBackgroundVisibleBehindChanged(boolean visible) {
6528 * Activities cannot draw during the period that their windows are animating in. In order
6529 * to know when it is safe to begin drawing they can override this method which will be
6530 * called when the entering animation has completed.
6532 public void onEnterAnimationComplete() {
6538 public void dispatchEnterAnimationComplete() {
6539 onEnterAnimationComplete();
6540 if (getWindow() != null && getWindow().getDecorView() != null) {
6541 getWindow().getDecorView().getViewTreeObserver().dispatchOnEnterAnimationComplete();
6546 * Adjust the current immersive mode setting.
6548 * Note that changing this value will have no effect on the activity's
6549 * {@link android.content.pm.ActivityInfo} structure; that is, if
6550 * <code>android:immersive</code> is set to <code>true</code>
6551 * in the application's manifest entry for this activity, the {@link
6552 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
6553 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6554 * FLAG_IMMERSIVE} bit set.
6556 * @see #isImmersive()
6557 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
6559 public void setImmersive(boolean i) {
6561 ActivityManager.getService().setImmersive(mToken, i);
6562 } catch (RemoteException e) {
6568 * Enable or disable virtual reality (VR) mode for this Activity.
6570 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
6571 * while this Activity has user focus.</p>
6573 * <p>It is recommended that applications additionally declare
6574 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
6575 * transitions when switching between VR activities.</p>
6577 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
6578 * VR mode will not be started. Developers can handle this case as follows:</p>
6581 * String servicePackage = "com.whatever.app";
6582 * String serviceClass = "com.whatever.app.MyVrListenerService";
6584 * // Name of the component of the VrListenerService to start.
6585 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
6588 * setVrModeEnabled(true, myComponentName);
6589 * } catch (PackageManager.NameNotFoundException e) {
6590 * List<ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
6591 * boolean isInstalled = false;
6592 * for (ApplicationInfo app : installed) {
6593 * if (app.packageName.equals(servicePackage)) {
6594 * isInstalled = true;
6598 * if (isInstalled) {
6599 * // Package is installed, but not enabled in Settings. Let user enable it.
6600 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
6602 * // Package is not installed. Send an intent to download this.
6603 * sentIntentToLaunchAppStore(servicePackage);
6608 * @param enabled {@code true} to enable this mode.
6609 * @param requestedComponent the name of the component to use as a
6610 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
6612 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
6613 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
6614 * not been enabled in user settings.
6616 * @see android.content.pm.PackageManager#FEATURE_VR_MODE
6617 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
6618 * @see android.service.vr.VrListenerService
6619 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
6620 * @see android.R.attr#enableVrMode
6622 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
6623 throws PackageManager.NameNotFoundException {
6625 if (ActivityManager.getService().setVrMode(mToken, enabled, requestedComponent)
6627 throw new PackageManager.NameNotFoundException(
6628 requestedComponent.flattenToString());
6630 } catch (RemoteException e) {
6636 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
6638 * @param callback Callback that will manage lifecycle events for this action mode
6639 * @return The ActionMode that was started, or null if it was canceled
6644 public ActionMode startActionMode(ActionMode.Callback callback) {
6645 return mWindow.getDecorView().startActionMode(callback);
6649 * Start an action mode of the given type.
6651 * @param callback Callback that will manage lifecycle events for this action mode
6652 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6653 * @return The ActionMode that was started, or null if it was canceled
6658 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6659 return mWindow.getDecorView().startActionMode(callback, type);
6663 * Give the Activity a chance to control the UI for an action mode requested
6666 * <p>Note: If you are looking for a notification callback that an action mode
6667 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
6669 * @param callback The callback that should control the new action mode
6670 * @return The new action mode, or <code>null</code> if the activity does not want to
6671 * provide special handling for this action mode. (It will be handled by the system.)
6675 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
6676 // Only Primary ActionModes are represented in the ActionBar.
6677 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
6678 initWindowDecorActionBar();
6679 if (mActionBar != null) {
6680 return mActionBar.startActionMode(callback);
6691 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
6693 mActionModeTypeStarting = type;
6694 return onWindowStartingActionMode(callback);
6696 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
6701 * Notifies the Activity that an action mode has been started.
6702 * Activity subclasses overriding this method should call the superclass implementation.
6704 * @param mode The new action mode.
6708 public void onActionModeStarted(ActionMode mode) {
6712 * Notifies the activity that an action mode has finished.
6713 * Activity subclasses overriding this method should call the superclass implementation.
6715 * @param mode The action mode that just finished.
6719 public void onActionModeFinished(ActionMode mode) {
6723 * Returns true if the app should recreate the task when navigating 'up' from this activity
6724 * by using targetIntent.
6726 * <p>If this method returns false the app can trivially call
6727 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
6728 * up navigation. If this method returns false, the app should synthesize a new task stack
6729 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
6731 * @param targetIntent An intent representing the target destination for up navigation
6732 * @return true if navigating up should recreate a new task stack, false if the same task
6733 * should be used for the destination
6735 public boolean shouldUpRecreateTask(Intent targetIntent) {
6737 PackageManager pm = getPackageManager();
6738 ComponentName cn = targetIntent.getComponent();
6740 cn = targetIntent.resolveActivity(pm);
6742 ActivityInfo info = pm.getActivityInfo(cn, 0);
6743 if (info.taskAffinity == null) {
6746 return ActivityManager.getService()
6747 .shouldUpRecreateTask(mToken, info.taskAffinity);
6748 } catch (RemoteException e) {
6750 } catch (NameNotFoundException e) {
6756 * Navigate from this activity to the activity specified by upIntent, finishing this activity
6757 * in the process. If the activity indicated by upIntent already exists in the task's history,
6758 * this activity and all others before the indicated activity in the history stack will be
6761 * <p>If the indicated activity does not appear in the history stack, this will finish
6762 * each activity in this task until the root activity of the task is reached, resulting in
6763 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
6764 * when an activity may be reached by a path not passing through a canonical parent
6767 * <p>This method should be used when performing up navigation from within the same task
6768 * as the destination. If up navigation should cross tasks in some cases, see
6769 * {@link #shouldUpRecreateTask(Intent)}.</p>
6771 * @param upIntent An intent representing the target destination for up navigation
6773 * @return true if up navigation successfully reached the activity indicated by upIntent and
6774 * upIntent was delivered to it. false if an instance of the indicated activity could
6775 * not be found and this activity was simply finished normally.
6777 public boolean navigateUpTo(Intent upIntent) {
6778 if (mParent == null) {
6779 ComponentName destInfo = upIntent.getComponent();
6780 if (destInfo == null) {
6781 destInfo = upIntent.resolveActivity(getPackageManager());
6782 if (destInfo == null) {
6785 upIntent = new Intent(upIntent);
6786 upIntent.setComponent(destInfo);
6790 synchronized (this) {
6791 resultCode = mResultCode;
6792 resultData = mResultData;
6794 if (resultData != null) {
6795 resultData.prepareToLeaveProcess(this);
6798 upIntent.prepareToLeaveProcess(this);
6799 return ActivityManager.getService().navigateUpTo(mToken, upIntent,
6800 resultCode, resultData);
6801 } catch (RemoteException e) {
6805 return mParent.navigateUpToFromChild(this, upIntent);
6810 * This is called when a child activity of this one calls its
6811 * {@link #navigateUpTo} method. The default implementation simply calls
6812 * navigateUpTo(upIntent) on this activity (the parent).
6814 * @param child The activity making the call.
6815 * @param upIntent An intent representing the target destination for up navigation
6817 * @return true if up navigation successfully reached the activity indicated by upIntent and
6818 * upIntent was delivered to it. false if an instance of the indicated activity could
6819 * not be found and this activity was simply finished normally.
6821 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
6822 return navigateUpTo(upIntent);
6826 * Obtain an {@link Intent} that will launch an explicit target activity specified by
6827 * this activity's logical parent. The logical parent is named in the application's manifest
6828 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
6829 * Activity subclasses may override this method to modify the Intent returned by
6830 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
6831 * the parent intent entirely.
6833 * @return a new Intent targeting the defined parent of this activity or null if
6834 * there is no valid parent.
6837 public Intent getParentActivityIntent() {
6838 final String parentName = mActivityInfo.parentActivityName;
6839 if (TextUtils.isEmpty(parentName)) {
6843 // If the parent itself has no parent, generate a main activity intent.
6844 final ComponentName target = new ComponentName(this, parentName);
6846 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
6847 final String parentActivity = parentInfo.parentActivityName;
6848 final Intent parentIntent = parentActivity == null
6849 ? Intent.makeMainActivity(target)
6850 : new Intent().setComponent(target);
6851 return parentIntent;
6852 } catch (NameNotFoundException e) {
6853 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
6860 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6861 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6862 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
6863 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6865 * @param callback Used to manipulate shared element transitions on the launched Activity.
6867 public void setEnterSharedElementCallback(SharedElementCallback callback) {
6868 if (callback == null) {
6869 callback = SharedElementCallback.NULL_CALLBACK;
6871 mEnterTransitionListener = callback;
6875 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6876 * android.view.View, String)} was used to start an Activity, <var>callback</var>
6877 * will be called to handle shared elements on the <i>launching</i> Activity. Most
6878 * calls will only come when returning from the started Activity.
6879 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
6881 * @param callback Used to manipulate shared element transitions on the launching Activity.
6883 public void setExitSharedElementCallback(SharedElementCallback callback) {
6884 if (callback == null) {
6885 callback = SharedElementCallback.NULL_CALLBACK;
6887 mExitTransitionListener = callback;
6891 * Postpone the entering activity transition when Activity was started with
6892 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6893 * android.util.Pair[])}.
6894 * <p>This method gives the Activity the ability to delay starting the entering and
6895 * shared element transitions until all data is loaded. Until then, the Activity won't
6896 * draw into its window, leaving the window transparent. This may also cause the
6897 * returning animation to be delayed until data is ready. This method should be
6898 * called in {@link #onCreate(android.os.Bundle)} or in
6899 * {@link #onActivityReenter(int, android.content.Intent)}.
6900 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
6901 * start the transitions. If the Activity did not use
6902 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
6903 * android.util.Pair[])}, then this method does nothing.</p>
6905 public void postponeEnterTransition() {
6906 mActivityTransitionState.postponeEnterTransition();
6910 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
6911 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
6912 * to have your Activity start drawing.
6914 public void startPostponedEnterTransition() {
6915 mActivityTransitionState.startPostponedEnterTransition();
6919 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
6920 * access permissions for content URIs associated with the {@link DragEvent}.
6921 * @param event Drag event
6922 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
6923 * Null if no content URIs are associated with the event or if permissions could not be granted.
6925 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
6926 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
6927 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
6928 return dragAndDropPermissions;
6933 // ------------------ Internal API ------------------
6935 final void setParent(Activity parent) {
6939 final void attach(Context context, ActivityThread aThread,
6940 Instrumentation instr, IBinder token, int ident,
6941 Application application, Intent intent, ActivityInfo info,
6942 CharSequence title, Activity parent, String id,
6943 NonConfigurationInstances lastNonConfigurationInstances,
6944 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6945 Window window, ActivityConfigCallback activityConfigCallback) {
6946 attachBaseContext(context);
6948 mFragments.attachHost(null /*parent*/);
6950 mWindow = new PhoneWindow(this, window, activityConfigCallback);
6951 mWindow.setWindowControllerCallback(this);
6952 mWindow.setCallback(this);
6953 mWindow.setOnWindowDismissedCallback(this);
6954 mWindow.getLayoutInflater().setPrivateFactory(this);
6955 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6956 mWindow.setSoftInputMode(info.softInputMode);
6958 if (info.uiOptions != 0) {
6959 mWindow.setUiOptions(info.uiOptions);
6961 mUiThread = Thread.currentThread();
6963 mMainThread = aThread;
6964 mInstrumentation = instr;
6967 mApplication = application;
6969 mReferrer = referrer;
6970 mComponent = intent.getComponent();
6971 mActivityInfo = info;
6975 mLastNonConfigurationInstances = lastNonConfigurationInstances;
6976 if (voiceInteractor != null) {
6977 if (lastNonConfigurationInstances != null) {
6978 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6980 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6985 mWindow.setWindowManager(
6986 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6987 mToken, mComponent.flattenToString(),
6988 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6989 if (mParent != null) {
6990 mWindow.setContainer(mParent.getWindow());
6992 mWindowManager = mWindow.getWindowManager();
6993 mCurrentConfig = config;
6995 mWindow.setColorMode(info.colorMode);
6999 public final IBinder getActivityToken() {
7000 return mParent != null ? mParent.getActivityToken() : mToken;
7003 final void performCreate(Bundle icicle) {
7004 performCreate(icicle, null);
7007 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7008 mCanEnterPictureInPicture = true;
7009 restoreHasCurrentPermissionRequest(icicle);
7010 if (persistentState != null) {
7011 onCreate(icicle, persistentState);
7015 mActivityTransitionState.readState(icicle);
7017 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
7018 com.android.internal.R.styleable.Window_windowNoDisplay, false);
7019 mFragments.dispatchActivityCreated();
7020 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7023 final void performNewIntent(Intent intent) {
7024 mCanEnterPictureInPicture = true;
7025 onNewIntent(intent);
7028 final void performStart() {
7029 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7030 mFragments.noteStateNotSaved();
7032 mFragments.execPendingActions();
7033 mInstrumentation.callActivityOnStart(this);
7035 throw new SuperNotCalledException(
7036 "Activity " + mComponent.toShortString() +
7037 " did not call through to super.onStart()");
7039 mFragments.dispatchStart();
7040 mFragments.reportLoaderStart();
7042 // This property is set for all builds except final release
7043 boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
7044 boolean isAppDebuggable =
7045 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7047 if (isAppDebuggable || isDlwarningEnabled) {
7048 String dlwarning = getDlWarning();
7049 if (dlwarning != null) {
7050 String appName = getApplicationInfo().loadLabel(getPackageManager())
7052 String warning = "Detected problems with app native libraries\n" +
7053 "(please consult log for detail):\n" + dlwarning;
7054 if (isAppDebuggable) {
7055 new AlertDialog.Builder(this).
7057 setMessage(warning).
7058 setPositiveButton(android.R.string.ok, null).
7059 setCancelable(false).
7062 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
7067 mActivityTransitionState.enterReady(this);
7070 final void performRestart() {
7071 mCanEnterPictureInPicture = true;
7072 mFragments.noteStateNotSaved();
7074 if (mToken != null && mParent == null) {
7075 // No need to check mStopped, the roots will check if they were actually stopped.
7076 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
7082 synchronized (mManagedCursors) {
7083 final int N = mManagedCursors.size();
7084 for (int i=0; i<N; i++) {
7085 ManagedCursor mc = mManagedCursors.get(i);
7086 if (mc.mReleased || mc.mUpdated) {
7087 if (!mc.mCursor.requery()) {
7088 if (getApplicationInfo().targetSdkVersion
7089 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
7090 throw new IllegalStateException(
7091 "trying to requery an already closed cursor "
7095 mc.mReleased = false;
7096 mc.mUpdated = false;
7102 mInstrumentation.callActivityOnRestart(this);
7104 throw new SuperNotCalledException(
7105 "Activity " + mComponent.toShortString() +
7106 " did not call through to super.onRestart()");
7112 final void performResume() {
7115 mFragments.execPendingActions();
7117 mLastNonConfigurationInstances = null;
7120 // mResumed is set by the instrumentation
7121 mInstrumentation.callActivityOnResume(this);
7123 throw new SuperNotCalledException(
7124 "Activity " + mComponent.toShortString() +
7125 " did not call through to super.onResume()");
7128 // invisible activities must be finished before onResume() completes
7129 if (!mVisibleFromClient && !mFinished) {
7130 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
7131 if (getApplicationInfo().targetSdkVersion
7132 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
7133 throw new IllegalStateException(
7134 "Activity " + mComponent.toShortString() +
7135 " did not call finish() prior to onResume() completing");
7139 // Now really resume, and install the current status bar and menu.
7142 mFragments.dispatchResume();
7143 mFragments.execPendingActions();
7147 throw new SuperNotCalledException(
7148 "Activity " + mComponent.toShortString() +
7149 " did not call through to super.onPostResume()");
7153 final void performPause() {
7154 mDoReportFullyDrawn = false;
7155 mFragments.dispatchPause();
7159 if (!mCalled && getApplicationInfo().targetSdkVersion
7160 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
7161 throw new SuperNotCalledException(
7162 "Activity " + mComponent.toShortString() +
7163 " did not call through to super.onPause()");
7168 final void performUserLeaving() {
7169 onUserInteraction();
7173 final void performStop(boolean preserveWindow) {
7174 mDoReportFullyDrawn = false;
7175 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
7177 // Disallow entering picture-in-picture after the activity has been stopped
7178 mCanEnterPictureInPicture = false;
7181 if (mWindow != null) {
7182 mWindow.closeAllPanels();
7185 // If we're preserving the window, don't setStoppedState to true, since we
7186 // need the window started immediately again. Stopping the window will
7187 // destroys hardware resources and causes flicker.
7188 if (!preserveWindow && mToken != null && mParent == null) {
7189 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
7192 mFragments.dispatchStop();
7195 mInstrumentation.callActivityOnStop(this);
7197 throw new SuperNotCalledException(
7198 "Activity " + mComponent.toShortString() +
7199 " did not call through to super.onStop()");
7202 synchronized (mManagedCursors) {
7203 final int N = mManagedCursors.size();
7204 for (int i=0; i<N; i++) {
7205 ManagedCursor mc = mManagedCursors.get(i);
7206 if (!mc.mReleased) {
7207 mc.mCursor.deactivate();
7208 mc.mReleased = true;
7218 final void performDestroy() {
7221 mFragments.dispatchDestroy();
7223 mFragments.doLoaderDestroy();
7224 if (mVoiceInteractor != null) {
7225 mVoiceInteractor.detachActivity();
7229 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
7230 Configuration newConfig) {
7231 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7232 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
7234 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7235 if (mWindow != null) {
7236 mWindow.onMultiWindowModeChanged();
7238 onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
7241 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
7242 Configuration newConfig) {
7243 if (DEBUG_LIFECYCLE) Slog.v(TAG,
7244 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
7246 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7247 if (mWindow != null) {
7248 mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
7250 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
7256 public final boolean isResumed() {
7260 private void storeHasCurrentPermissionRequest(Bundle bundle) {
7261 if (bundle != null && mHasCurrentPermissionsRequest) {
7262 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
7266 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
7267 if (bundle != null) {
7268 mHasCurrentPermissionsRequest = bundle.getBoolean(
7269 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
7273 void dispatchActivityResult(String who, int requestCode,
7274 int resultCode, Intent data) {
7276 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
7277 + ", resCode=" + resultCode + ", data=" + data);
7278 mFragments.noteStateNotSaved();
7280 onActivityResult(requestCode, resultCode, data);
7281 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
7282 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
7283 if (TextUtils.isEmpty(who)) {
7284 dispatchRequestPermissionsResult(requestCode, data);
7286 Fragment frag = mFragments.findFragmentByWho(who);
7288 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
7291 } else if (who.startsWith("@android:view:")) {
7292 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
7293 getActivityToken());
7294 for (ViewRootImpl viewRoot : views) {
7295 if (viewRoot.getView() != null
7296 && viewRoot.getView().dispatchActivityResult(
7297 who, requestCode, resultCode, data)) {
7301 } else if (who.startsWith(AUTO_FILL_AUTH_WHO_PREFIX)) {
7302 Intent resultData = (resultCode == Activity.RESULT_OK) ? data : null;
7303 getAutofillManager().onAuthenticationResult(requestCode, resultData);
7305 Fragment frag = mFragments.findFragmentByWho(who);
7307 frag.onActivityResult(requestCode, resultCode, data);
7313 * Request to put this Activity in a mode where the user is locked to the
7316 * This will prevent the user from launching other apps, going to settings, or reaching the
7317 * home screen. This does not include those apps whose {@link android.R.attr#lockTaskMode}
7318 * values permit launching while locked.
7320 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns true or
7321 * lockTaskMode=lockTaskModeAlways for this component then the app will go directly into
7322 * Lock Task mode. The user will not be able to exit this mode until
7323 * {@link Activity#stopLockTask()} is called.
7325 * If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns false
7326 * then the system will prompt the user with a dialog requesting permission to enter
7327 * this mode. When entered through this method the user can exit at any time through
7328 * an action described by the request dialog. Calling stopLockTask will also exit the
7331 * @see android.R.attr#lockTaskMode
7333 public void startLockTask() {
7335 ActivityManager.getService().startLockTaskModeByToken(mToken);
7336 } catch (RemoteException e) {
7341 * Allow the user to switch away from the current task.
7343 * Called to end the mode started by {@link Activity#startLockTask}. This
7344 * can only be called by activities that have successfully called
7345 * startLockTask previously.
7347 * This will allow the user to exit this app and move onto other activities.
7348 * <p>Note: This method should only be called when the activity is user-facing. That is,
7349 * between onResume() and onPause().
7350 * <p>Note: If there are other tasks below this one that are also locked then calling this
7351 * method will immediately finish this task and resume the previous locked one, remaining in
7354 * @see android.R.attr#lockTaskMode
7355 * @see ActivityManager#getLockTaskModeState()
7357 public void stopLockTask() {
7359 ActivityManager.getService().stopLockTaskMode();
7360 } catch (RemoteException e) {
7365 * Shows the user the system defined message for telling the user how to exit
7366 * lock task mode. The task containing this activity must be in lock task mode at the time
7367 * of this call for the message to be displayed.
7369 public void showLockTaskEscapeMessage() {
7371 ActivityManager.getService().showLockTaskEscapeMessage(mToken);
7372 } catch (RemoteException e) {
7377 * Check whether the caption on freeform windows is displayed directly on the content.
7379 * @return True if caption is displayed on content, false if it pushes the content down.
7381 * @see #setOverlayWithDecorCaptionEnabled(boolean)
7384 public boolean isOverlayWithDecorCaptionEnabled() {
7385 return mWindow.isOverlayWithDecorCaptionEnabled();
7389 * Set whether the caption should displayed directly on the content rather than push it down.
7391 * This affects only freeform windows since they display the caption and only the main
7392 * window of the activity. The caption is used to drag the window around and also shows
7393 * maximize and close action buttons.
7396 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
7397 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
7401 * Interface for informing a translucent {@link Activity} once all visible activities below it
7402 * have completed drawing. This is necessary only after an {@link Activity} has been made
7403 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
7404 * translucent again following a call to {@link
7405 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7411 public interface TranslucentConversionListener {
7413 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
7414 * below the top one have been redrawn. Following this callback it is safe to make the top
7415 * Activity translucent because the underlying Activity has been drawn.
7417 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
7418 * occurred waiting for the Activity to complete drawing.
7420 * @see Activity#convertFromTranslucent()
7421 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
7423 public void onTranslucentConversionComplete(boolean drawComplete);
7426 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
7427 mHasCurrentPermissionsRequest = false;
7428 // If the package installer crashed we may have not data - best effort.
7429 String[] permissions = (data != null) ? data.getStringArrayExtra(
7430 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7431 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7432 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7433 onRequestPermissionsResult(requestCode, permissions, grantResults);
7436 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
7437 Fragment fragment) {
7438 // If the package installer crashed we may have not data - best effort.
7439 String[] permissions = (data != null) ? data.getStringArrayExtra(
7440 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
7441 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
7442 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
7443 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
7448 final public void autofillCallbackAuthenticate(int authenticationId, IntentSender intent,
7449 Intent fillInIntent) {
7451 startIntentSenderForResultInner(intent, AUTO_FILL_AUTH_WHO_PREFIX,
7452 authenticationId, fillInIntent, 0, 0, null);
7453 } catch (IntentSender.SendIntentException e) {
7454 Log.e(TAG, "authenticate() failed for intent:" + intent, e);
7460 final public void autofillCallbackResetableStateAvailable() {
7461 mAutoFillResetNeeded = true;
7466 final public boolean autofillCallbackRequestShowFillUi(@NonNull View anchor, int width,
7467 int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter) {
7468 final boolean wasShowing;
7470 if (mAutofillPopupWindow == null) {
7472 mAutofillPopupWindow = new AutofillPopupWindow(presenter);
7474 wasShowing = mAutofillPopupWindow.isShowing();
7476 mAutofillPopupWindow.update(anchor, 0, 0, width, height, anchorBounds);
7478 return !wasShowing && mAutofillPopupWindow.isShowing();
7483 final public boolean autofillCallbackRequestHideFillUi() {
7484 if (mAutofillPopupWindow == null) {
7487 mAutofillPopupWindow.dismiss();
7488 mAutofillPopupWindow = null;
7494 @NonNull public View[] findViewsByAutofillIdTraversal(@NonNull int[] viewIds) {
7495 final View[] views = new View[viewIds.length];
7496 final ArrayList<ViewRootImpl> roots =
7497 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7499 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7500 final View rootView = roots.get(rootNum).getView();
7502 if (rootView != null) {
7503 for (int viewNum = 0; viewNum < viewIds.length; viewNum++) {
7504 if (views[viewNum] == null) {
7505 views[viewNum] = rootView.findViewByAutofillIdTraversal(
7517 @Nullable public View findViewByAutofillIdTraversal(int viewId) {
7518 final ArrayList<ViewRootImpl> roots =
7519 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
7520 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
7521 final View rootView = roots.get(rootNum).getView();
7523 if (rootView != null) {
7524 final View view = rootView.findViewByAutofillIdTraversal(viewId);
7536 @NonNull public boolean[] getViewVisibility(@NonNull int[] viewIds) {
7537 final boolean[] isVisible = new boolean[viewIds.length];
7538 final View views[] = findViewsByAutofillIdTraversal(viewIds);
7540 for (int i = 0; i < viewIds.length; i++) {
7541 View view = views[i];
7543 isVisible[i] = false;
7547 isVisible[i] = true;
7549 // Check if the view is visible by checking all parents
7551 if (view instanceof DecorView && view.getViewRootImpl() == view.getParent()) {
7555 if (view.getVisibility() != View.VISIBLE) {
7556 isVisible[i] = false;
7560 if (view.getParent() instanceof View) {
7561 view = (View) view.getParent();
7573 public boolean isVisibleForAutofill() {
7578 * If set to true, this indicates to the system that it should never take a
7579 * screenshot of the activity to be used as a representation while it is not in a started state.
7581 * Note that the system may use the window background of the theme instead to represent
7582 * the window when it is not running.
7584 * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
7585 * this only affects the behavior when the activity's screenshot would be used as a
7586 * representation when the activity is not in a started state, i.e. in Overview. The system may
7587 * still take screenshots of the activity in other contexts; for example, when the user takes a
7588 * screenshot of the entire screen, or when the active
7589 * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
7590 * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
7592 * @param disable {@code true} to disable preview screenshots; {@code false} otherwise.
7596 public void setDisablePreviewScreenshots(boolean disable) {
7598 ActivityManager.getService().setDisablePreviewScreenshots(mToken, disable);
7599 } catch (RemoteException e) {
7600 Log.e(TAG, "Failed to call setDisablePreviewScreenshots", e);
7605 * Specifies whether an {@link Activity} should be shown on top of the the lock screen whenever
7606 * the lockscreen is up and the activity is resumed. Normally an activity will be transitioned
7607 * to the stopped state if it is started while the lockscreen is up, but with this flag set the
7608 * activity will remain in the resumed state visible on-top of the lock screen. This value can
7609 * be set as a manifest attribute using {@link android.R.attr#showWhenLocked}.
7611 * @param showWhenLocked {@code true} to show the {@link Activity} on top of the lock screen;
7612 * {@code false} otherwise.
7613 * @see #setTurnScreenOn(boolean)
7614 * @see android.R.attr#turnScreenOn
7615 * @see android.R.attr#showWhenLocked
7617 public void setShowWhenLocked(boolean showWhenLocked) {
7619 ActivityManager.getService().setShowWhenLocked(mToken, showWhenLocked);
7620 } catch (RemoteException e) {
7621 Log.e(TAG, "Failed to call setShowWhenLocked", e);
7626 * Specifies whether the screen should be turned on when the {@link Activity} is resumed.
7627 * Normally an activity will be transitioned to the stopped state if it is started while the
7628 * screen if off, but with this flag set the activity will cause the screen to turn on if the
7629 * activity will be visible and resumed due to the screen coming on. The screen will not be
7630 * turned on if the activity won't be visible after the screen is turned on. This flag is
7631 * normally used in conjunction with the {@link android.R.attr#showWhenLocked} flag to make sure
7632 * the activity is visible after the screen is turned on when the lockscreen is up. In addition,
7633 * if this flag is set and the activity calls {@link
7634 * KeyguardManager#requestDismissKeyguard(Activity, KeyguardManager.KeyguardDismissCallback)}
7635 * the screen will turn on.
7637 * @param turnScreenOn {@code true} to turn on the screen; {@code false} otherwise.
7639 * @see #setShowWhenLocked(boolean)
7640 * @see android.R.attr#turnScreenOn
7641 * @see android.R.attr#showWhenLocked
7643 public void setTurnScreenOn(boolean turnScreenOn) {
7645 ActivityManager.getService().setTurnScreenOn(mToken, turnScreenOn);
7646 } catch (RemoteException e) {
7647 Log.e(TAG, "Failed to call setTurnScreenOn", e);
7651 class HostCallbacks extends FragmentHostCallback<Activity> {
7652 public HostCallbacks() {
7653 super(Activity.this /*activity*/);
7657 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
7658 Activity.this.dump(prefix, fd, writer, args);
7662 public boolean onShouldSaveFragmentState(Fragment fragment) {
7663 return !isFinishing();
7667 public LayoutInflater onGetLayoutInflater() {
7668 final LayoutInflater result = Activity.this.getLayoutInflater();
7669 if (onUseFragmentManagerInflaterFactory()) {
7670 return result.cloneInContext(Activity.this);
7676 public boolean onUseFragmentManagerInflaterFactory() {
7677 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
7678 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
7682 public Activity onGetHost() {
7683 return Activity.this;
7687 public void onInvalidateOptionsMenu() {
7688 Activity.this.invalidateOptionsMenu();
7692 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
7694 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
7698 public void onStartActivityAsUserFromFragment(
7699 Fragment fragment, Intent intent, int requestCode, Bundle options,
7701 Activity.this.startActivityAsUserFromFragment(
7702 fragment, intent, requestCode, options, user);
7706 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
7707 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
7708 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
7709 if (mParent == null) {
7710 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
7711 flagsMask, flagsValues, options);
7712 } else if (options != null) {
7713 mParent.startIntentSenderFromChildFragment(fragment, intent, requestCode,
7714 fillInIntent, flagsMask, flagsValues, extraFlags, options);
7719 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
7721 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
7722 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
7723 startActivityForResult(who, intent, requestCode, null);
7727 public boolean onHasWindowAnimations() {
7728 return getWindow() != null;
7732 public int onGetWindowAnimations() {
7733 final Window w = getWindow();
7734 return (w == null) ? 0 : w.getAttributes().windowAnimations;
7738 public void onAttachFragment(Fragment fragment) {
7739 Activity.this.onAttachFragment(fragment);
7744 public <T extends View> T onFindViewById(int id) {
7745 return Activity.this.findViewById(id);
7749 public boolean onHasView() {
7750 final Window w = getWindow();
7751 return (w != null && w.peekDecorView() != null);