blob: 3772755beca18e8cb4e9f360ae2ab08bd69172b8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Jorim Jaggif84e2f62018-01-16 14:17:59 +010019import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Hongwei Wangf7e5a232020-05-06 15:49:44 -070020import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
21import static android.app.WindowConfiguration.inMultiWindowMode;
Felipe Leme0c6b23d2019-01-15 17:02:49 -080022import static android.os.Process.myUid;
Felipe Leme5b32ebe2018-02-15 12:52:19 -080023
Philip P. Moltmanne78c7712017-06-19 12:57:13 -070024import static java.lang.Character.MIN_VALUE;
Winson Chung1af8eda2016-02-05 17:55:56 +000025
Tor Norbyec615c6f2015-03-02 10:11:44 -080026import android.annotation.CallSuper;
Tor Norbye7b9c9122013-05-30 16:48:33 -070027import android.annotation.DrawableRes;
28import android.annotation.IdRes;
29import android.annotation.IntDef;
30import android.annotation.LayoutRes;
Tor Norbye83c68962015-03-10 20:55:31 -070031import android.annotation.MainThread;
Tor Norbyed9273d62013-05-30 15:59:53 -070032import android.annotation.NonNull;
Tor Norbye7b9c9122013-05-30 16:48:33 -070033import android.annotation.Nullable;
Tor Norbye788fc2b2015-07-05 16:10:42 -070034import android.annotation.RequiresPermission;
Tor Norbye7b9c9122013-05-30 16:48:33 -070035import android.annotation.StyleRes;
Jose Lima4b6c6692014-08-12 17:41:12 -070036import android.annotation.SystemApi;
Tiger Huangfc218452018-09-27 00:38:50 +080037import android.annotation.TestApi;
Amith Yamasanieeed06c2016-05-03 15:07:03 -070038import android.app.VoiceInteractor.Request;
Jason Monk62515be2014-05-21 16:06:19 -040039import android.app.admin.DevicePolicyManager;
Dianne Hackborn69c6adc2015-06-02 10:52:59 -070040import android.app.assist.AssistContent;
Artur Satayevc895b1b2019-12-10 17:47:51 +000041import android.compat.annotation.UnsupportedAppUsage;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070042import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ComponentName;
44import android.content.ContentResolver;
45import android.content.Context;
Jason parks6ed50de2010-08-25 10:18:50 -050046import android.content.CursorLoader;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070047import android.content.IIntentSender;
Adam Powell33b97432010-04-20 10:01:14 -070048import android.content.Intent;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070049import android.content.IntentSender;
Yuliya Kamatkova48c38072020-01-09 15:43:25 -080050import android.content.LocusId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.SharedPreferences;
52import android.content.pm.ActivityInfo;
Dimitry Ivanov4449ef52016-02-25 17:41:13 -080053import android.content.pm.ApplicationInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070054import android.content.pm.PackageManager;
55import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.res.Configuration;
57import android.content.res.Resources;
Dianne Hackbornba51c3d2010-05-05 18:49:48 -070058import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.database.Cursor;
60import android.graphics.Bitmap;
61import android.graphics.Canvas;
Winson2d476832016-02-17 14:53:46 -080062import android.graphics.Color;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -070063import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.graphics.drawable.Drawable;
Winson Chungd6722032020-02-18 15:16:08 -080065import android.graphics.drawable.Icon;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.media.AudioManager;
RoboErik55011652014-07-09 15:05:53 -070067import android.media.session.MediaController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
Adam Powelld3c63a62016-06-09 12:36:16 -070069import android.os.BadParcelableException;
Dianne Hackborn8d374262009-09-14 21:21:52 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Sunny Goyald40c3452019-03-20 12:46:55 -070072import android.os.CancellationSignal;
Tim Van Pattenddc43912018-12-18 17:47:52 -070073import android.os.GraphicsEnvironment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Handler;
75import android.os.IBinder;
Dianne Hackborn30c9bd82010-12-01 16:07:40 -080076import android.os.Looper;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -070077import android.os.Parcelable;
Winson Chung1af8eda2016-02-05 17:55:56 +000078import android.os.PersistableBundle;
Nicholas Sauer28348ed742019-02-15 11:58:32 -080079import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070080import android.os.RemoteException;
Jeff Sharkey49ca5292016-05-10 12:54:45 -060081import android.os.ServiceManager.ServiceNotFoundException;
Brad Fitzpatrick75803572011-01-13 14:21:03 -080082import android.os.StrictMode;
Felipe Lemeb337e1c2019-01-18 13:06:17 -080083import android.os.Trace;
Dianne Hackbornf1c26e22012-08-23 13:54:58 -070084import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.text.Selection;
86import android.text.SpannableStringBuilder;
svetoslavganov75986cf2009-05-14 22:28:01 -070087import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.text.method.TextKeyListener;
Winson Chung1af8eda2016-02-05 17:55:56 +000089import android.transition.Scene;
90import android.transition.TransitionManager;
91import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.util.EventLog;
94import android.util.Log;
Jeff Brown5182c782013-10-15 20:31:52 -070095import android.util.PrintWriterPrinter;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070096import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.util.SparseArray;
Winson Chung1af8eda2016-02-05 17:55:56 +000098import android.util.SuperNotCalledException;
Adam Powell6e346362010-07-23 10:18:23 -070099import android.view.ActionMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.view.ContextMenu;
Adam Powell6e346362010-07-23 10:18:23 -0700101import android.view.ContextMenu.ContextMenuInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.view.ContextThemeWrapper;
Vladislav Kaznacheev377c3282016-04-20 14:22:23 -0700103import android.view.DragAndDropPermissions;
Winson Chung1af8eda2016-02-05 17:55:56 +0000104import android.view.DragEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.view.KeyEvent;
Clara Bayarri75e09792015-07-29 16:20:40 +0100106import android.view.KeyboardShortcutGroup;
107import android.view.KeyboardShortcutInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.view.LayoutInflater;
109import android.view.Menu;
110import android.view.MenuInflater;
111import android.view.MenuItem;
112import android.view.MotionEvent;
Jorim Jaggif84e2f62018-01-16 14:17:59 +0100113import android.view.RemoteAnimationDefinition;
Tim Kilbourn6a975b32015-04-09 17:14:34 -0700114import android.view.SearchEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.view.View;
Adam Powell6e346362010-07-23 10:18:23 -0700116import android.view.View.OnCreateContextMenuListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.view.ViewGroup;
Adam Powell6e346362010-07-23 10:18:23 -0700118import android.view.ViewGroup.LayoutParams;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.view.ViewManager;
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +0000120import android.view.ViewRootImpl;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700121import android.view.ViewRootImpl.ActivityConfigCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.view.Window;
Winson Chung1af8eda2016-02-05 17:55:56 +0000123import android.view.Window.WindowControllerCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.WindowManager;
Jeff Brown98365d72012-08-19 20:30:52 -0700125import android.view.WindowManagerGlobal;
svetoslavganov75986cf2009-05-14 22:28:01 -0700126import android.view.accessibility.AccessibilityEvent;
Svetoslav Ganov24c90452017-12-27 15:17:14 -0800127import android.view.autofill.AutofillId;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700128import android.view.autofill.AutofillManager;
Felipe Lemebb567ae2017-10-04 09:56:21 -0700129import android.view.autofill.AutofillManager.AutofillClient;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700130import android.view.autofill.AutofillPopupWindow;
131import android.view.autofill.IAutofillWindowPresenter;
Yuliya Kamatkovab5d87a82020-02-13 16:00:52 -0800132import android.view.contentcapture.ContentCaptureContext;
Felipe Leme749b8892018-12-03 16:30:30 -0800133import android.view.contentcapture.ContentCaptureManager;
Felipe Lemecbf7f262019-04-17 13:57:59 -0700134import android.view.contentcapture.ContentCaptureManager.ContentCaptureClient;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import android.widget.AdapterView;
Dimitry Ivanov4449ef52016-02-25 17:41:13 -0800136import android.widget.Toast;
Winson Chung1af8eda2016-02-05 17:55:56 +0000137import android.widget.Toolbar;
Clara Bayarri75e09792015-07-29 16:20:40 +0100138
Adrian Roos4c864592019-04-10 14:47:57 +0200139import com.android.internal.R;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700140import com.android.internal.annotations.GuardedBy;
Andrii Kuliandfbf9712018-03-08 15:42:24 -0800141import com.android.internal.annotations.VisibleForTesting;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700142import com.android.internal.app.IVoiceInteractor;
143import com.android.internal.app.ToolbarActionBar;
144import com.android.internal.app.WindowDecorActionBar;
Philip P. Moltmanne78c7712017-06-19 12:57:13 -0700145import com.android.internal.policy.PhoneWindow;
146
Mathieu Chartier63e14c12019-03-07 09:05:44 -0800147import dalvik.system.VMRuntime;
148
Dianne Hackborn625ac272010-09-17 18:29:22 -0700149import java.io.FileDescriptor;
150import java.io.PrintWriter;
Tor Norbyed9273d62013-05-30 15:59:53 -0700151import java.lang.annotation.Retention;
152import java.lang.annotation.RetentionPolicy;
Mark Renouf1c25fc52019-09-09 13:13:43 -0400153import java.lang.ref.WeakReference;
Adam Powell6e346362010-07-23 10:18:23 -0700154import java.util.ArrayList;
Felipe Leme5b32ebe2018-02-15 12:52:19 -0800155import java.util.Arrays;
Sunny Goyald40c3452019-03-20 12:46:55 -0700156import java.util.Collections;
Adam Powell6e346362010-07-23 10:18:23 -0700157import java.util.HashMap;
Todd Kennedya5fc6f02015-04-14 18:22:54 -0700158import java.util.List;
Sunny Goyald40c3452019-03-20 12:46:55 -0700159import java.util.concurrent.Executor;
160import java.util.function.Consumer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Bryce Leee83f34cd2017-10-31 19:50:54 -0700162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163/**
164 * An activity is a single, focused thing that the user can do. Almost all
165 * activities interact with the user, so the Activity class takes care of
166 * creating a window for you in which you can place your UI with
167 * {@link #setContentView}. While activities are often presented to the user
168 * as full-screen windows, they can also be used in other ways: as floating
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700169 * windows (via a theme with {@link android.R.attr#windowIsFloating} set),
170 * <a href="https://developer.android.com/guide/topics/ui/multi-window">
171 * Multi-Window mode</a> or embedded into other windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 *
173 * There are two methods almost all subclasses of Activity will implement:
RoboErik55011652014-07-09 15:05:53 -0700174 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 * <ul>
176 * <li> {@link #onCreate} is where you initialize your activity. Most
177 * importantly, here you will usually call {@link #setContentView(int)}
178 * with a layout resource defining your UI, and using {@link #findViewById}
179 * to retrieve the widgets in that UI that you need to interact with
180 * programmatically.
RoboErik55011652014-07-09 15:05:53 -0700181 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700182 * <li> {@link #onPause} is where you deal with the user pausing active
183 * interaction with the activity. Any changes made by the user should at
184 * this point be committed (usually to the
185 * {@link android.content.ContentProvider} holding the data). In this
186 * state the activity is still visible on screen.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 * </ul>
188 *
189 * <p>To be of use with {@link android.content.Context#startActivity Context.startActivity()}, all
190 * activity classes must have a corresponding
191 * {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
192 * declaration in their package's <code>AndroidManifest.xml</code>.</p>
RoboErik55011652014-07-09 15:05:53 -0700193 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 * <p>Topics covered here:
195 * <ol>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700196 * <li><a href="#Fragments">Fragments</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 * <li><a href="#ActivityLifecycle">Activity Lifecycle</a>
198 * <li><a href="#ConfigurationChanges">Configuration Changes</a>
199 * <li><a href="#StartingActivities">Starting Activities and Getting Results</a>
200 * <li><a href="#SavingPersistentState">Saving Persistent State</a>
201 * <li><a href="#Permissions">Permissions</a>
202 * <li><a href="#ProcessLifecycle">Process Lifecycle</a>
203 * </ol>
Joe Fernandezb54e7a32011-10-03 15:09:50 -0700204 *
205 * <div class="special reference">
206 * <h3>Developer Guides</h3>
207 * <p>The Activity class is an important part of an application's overall lifecycle,
208 * and the way activities are launched and put together is a fundamental
209 * part of the platform's application model. For a detailed perspective on the structure of an
210 * Android application and how activities behave, please read the
211 * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a> and
Mark Lufa434852016-08-11 17:40:33 -0700212 * <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
Joe Fernandezb54e7a32011-10-03 15:09:50 -0700213 * developer guides.</p>
214 *
215 * <p>You can also find a detailed discussion about how to create activities in the
Mark Lufa434852016-08-11 17:40:33 -0700216 * <a href="{@docRoot}guide/components/activities.html">Activities</a>
Joe Fernandezb54e7a32011-10-03 15:09:50 -0700217 * developer guide.</p>
218 * </div>
219 *
Dianne Hackborn291905e2010-08-17 15:17:15 -0700220 * <a name="Fragments"></a>
221 * <h3>Fragments</h3>
222 *
Ian Lake0a1feb82017-11-13 10:26:46 -0800223 * <p>The {@link android.support.v4.app.FragmentActivity} subclass
224 * can make use of the {@link android.support.v4.app.Fragment} class to better
Dianne Hackborn291905e2010-08-17 15:17:15 -0700225 * modularize their code, build more sophisticated user interfaces for larger
Ian Lake0a1feb82017-11-13 10:26:46 -0800226 * screens, and help scale their application between small and large screens.</p>
227 *
228 * <p>For more information about using fragments, read the
229 * <a href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p>
Dianne Hackborn291905e2010-08-17 15:17:15 -0700230 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 * <a name="ActivityLifecycle"></a>
232 * <h3>Activity Lifecycle</h3>
233 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700234 * <p>Activities in the system are managed as
235 * <a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack">
236 * activity stacks</a>. When a new activity is started, it is usually placed on the top of the
237 * current stack and becomes the running activity -- the previous activity always remains
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 * below it in the stack, and will not come to the foreground again until
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700239 * the new activity exits. There can be one or multiple activity stacks visible
240 * on screen.</p>
RoboErik55011652014-07-09 15:05:53 -0700241 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 * <p>An activity has essentially four states:</p>
243 * <ul>
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700244 * <li>If an activity is in the foreground of the screen (at the highest position of the topmost
245 * stack), it is <em>active</em> or <em>running</em>. This is usually the activity that the
246 * user is currently interacting with.</li>
247 * <li>If an activity has lost focus but is still presented to the user, it is <em>visible</em>.
248 * It is possible if a new non-full-sized or transparent activity has focus on top of your
249 * activity, another activity has higher position in multi-window mode, or the activity
250 * itself is not focusable in current windowing mode. Such activity is completely alive (it
251 * maintains all state and member information and remains attached to the window manager).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 * <li>If an activity is completely obscured by another activity,
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700253 * it is <em>stopped</em> or <em>hidden</em>. It still retains all state and member
254 * information, however, it is no longer visible to the user so its window is hidden
255 * and it will often be killed by the system when memory is needed elsewhere.</li>
256 * <li>The system can drop the activity from memory by either asking it to finish,
257 * or simply killing its process, making it <em>destroyed</em>. When it is displayed again
258 * to the user, it must be completely restarted and restored to its previous state.</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 * </ul>
260 *
261 * <p>The following diagram shows the important state paths of an Activity.
262 * The square rectangles represent callback methods you can implement to
263 * perform operations when the Activity moves between states. The colored
264 * ovals are major states the Activity can be in.</p>
RoboErik55011652014-07-09 15:05:53 -0700265 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 * <p><img src="../../../images/activity_lifecycle.png"
267 * alt="State diagram for an Android Activity Lifecycle." border="0" /></p>
RoboErik55011652014-07-09 15:05:53 -0700268 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * <p>There are three key loops you may be interested in monitoring within your
270 * activity:
RoboErik55011652014-07-09 15:05:53 -0700271 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 * <ul>
273 * <li>The <b>entire lifetime</b> of an activity happens between the first call
274 * to {@link android.app.Activity#onCreate} through to a single final call
275 * to {@link android.app.Activity#onDestroy}. An activity will do all setup
276 * of "global" state in onCreate(), and release all remaining resources in
277 * onDestroy(). For example, if it has a thread running in the background
278 * to download data from the network, it may create that thread in onCreate()
279 * and then stop the thread in onDestroy().
RoboErik55011652014-07-09 15:05:53 -0700280 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 * <li>The <b>visible lifetime</b> of an activity happens between a call to
282 * {@link android.app.Activity#onStart} until a corresponding call to
283 * {@link android.app.Activity#onStop}. During this time the user can see the
284 * activity on-screen, though it may not be in the foreground and interacting
285 * with the user. Between these two methods you can maintain resources that
286 * are needed to show the activity to the user. For example, you can register
287 * a {@link android.content.BroadcastReceiver} in onStart() to monitor for changes
Ken Wakasaf76a50c2012-03-09 19:56:35 +0900288 * that impact your UI, and unregister it in onStop() when the user no
289 * longer sees what you are displaying. The onStart() and onStop() methods
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 * can be called multiple times, as the activity becomes visible and hidden
291 * to the user.
RoboErik55011652014-07-09 15:05:53 -0700292 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 * <li>The <b>foreground lifetime</b> of an activity happens between a call to
294 * {@link android.app.Activity#onResume} until a corresponding call to
295 * {@link android.app.Activity#onPause}. During this time the activity is
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700296 * in visible, active and interacting with the user. An activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 * can frequently go between the resumed and paused states -- for example when
298 * the device goes to sleep, when an activity result is delivered, when a new
299 * intent is delivered -- so the code in these methods should be fairly
300 * lightweight.
301 * </ul>
RoboErik55011652014-07-09 15:05:53 -0700302 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 * <p>The entire lifecycle of an activity is defined by the following
304 * Activity methods. All of these are hooks that you can override
305 * to do appropriate work when the activity changes state. All
306 * activities will implement {@link android.app.Activity#onCreate}
307 * to do their initial setup; many will also implement
308 * {@link android.app.Activity#onPause} to commit changes to data and
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700309 * prepare to pause interacting with the user, and {@link android.app.Activity#onStop}
310 * to handle no longer being visible on screen. You should always
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 * call up to your superclass when implementing these methods.</p>
312 *
313 * </p>
314 * <pre class="prettyprint">
315 * public class Activity extends ApplicationContext {
316 * protected void onCreate(Bundle savedInstanceState);
317 *
318 * protected void onStart();
RoboErik55011652014-07-09 15:05:53 -0700319 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * protected void onRestart();
321 *
322 * protected void onResume();
323 *
324 * protected void onPause();
325 *
326 * protected void onStop();
327 *
328 * protected void onDestroy();
329 * }
330 * </pre>
331 *
332 * <p>In general the movement through an activity's lifecycle looks like
333 * this:</p>
334 *
335 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
336 * <colgroup align="left" span="3" />
337 * <colgroup align="left" />
338 * <colgroup align="center" />
339 * <colgroup align="center" />
340 *
341 * <thead>
342 * <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
343 * </thead>
344 *
345 * <tbody>
smain@google.com10e29b82016-06-23 12:09:30 -0700346 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onCreate onCreate()}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 * <td>Called when the activity is first created.
348 * This is where you should do all of your normal static set up:
349 * create views, bind data to lists, etc. This method also
350 * provides you with a Bundle containing the activity's previously
351 * frozen state, if there was one.
352 * <p>Always followed by <code>onStart()</code>.</td>
353 * <td align="center">No</td>
354 * <td align="center"><code>onStart()</code></td>
355 * </tr>
356 *
357 * <tr><td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
smain@google.com10e29b82016-06-23 12:09:30 -0700358 * <td colspan="2" align="left" border="0">{@link android.app.Activity#onRestart onRestart()}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 * <td>Called after your activity has been stopped, prior to it being
360 * started again.
361 * <p>Always followed by <code>onStart()</code></td>
362 * <td align="center">No</td>
363 * <td align="center"><code>onStart()</code></td>
364 * </tr>
365 *
smain@google.com10e29b82016-06-23 12:09:30 -0700366 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStart onStart()}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 * <td>Called when the activity is becoming visible to the user.
368 * <p>Followed by <code>onResume()</code> if the activity comes
369 * to the foreground, or <code>onStop()</code> if it becomes hidden.</td>
370 * <td align="center">No</td>
371 * <td align="center"><code>onResume()</code> or <code>onStop()</code></td>
372 * </tr>
373 *
374 * <tr><td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
smain@google.com10e29b82016-06-23 12:09:30 -0700375 * <td align="left" border="0">{@link android.app.Activity#onResume onResume()}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 * <td>Called when the activity will start
377 * interacting with the user. At this point your activity is at
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700378 * the top of its activity stack, with user input going to it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 * <p>Always followed by <code>onPause()</code>.</td>
380 * <td align="center">No</td>
381 * <td align="center"><code>onPause()</code></td>
382 * </tr>
383 *
smain@google.com10e29b82016-06-23 12:09:30 -0700384 * <tr><td align="left" border="0">{@link android.app.Activity#onPause onPause()}</td>
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700385 * <td>Called when the activity loses foreground state, is no longer focusable or before
386 * transition to stopped/hidden or destroyed state. The activity is still visible to
387 * user, so it's recommended to keep it visually active and continue updating the UI.
388 * Implementations of this method must be very quick because
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 * the next activity will not be resumed until this method returns.
390 * <p>Followed by either <code>onResume()</code> if the activity
391 * returns back to the front, or <code>onStop()</code> if it becomes
392 * invisible to the user.</td>
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800393 * <td align="center"><font color="#800000"><strong>Pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB}</strong></font></td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 * <td align="center"><code>onResume()</code> or<br>
395 * <code>onStop()</code></td>
396 * </tr>
397 *
smain@google.com10e29b82016-06-23 12:09:30 -0700398 * <tr><td colspan="2" align="left" border="0">{@link android.app.Activity#onStop onStop()}</td>
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700399 * <td>Called when the activity is no longer visible to the user. This may happen either
400 * because a new activity is being started on top, an existing one is being brought in
401 * front of this one, or this one is being destroyed. This is typically used to stop
402 * animations and refreshing the UI, etc.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 * <p>Followed by either <code>onRestart()</code> if
404 * this activity is coming back to interact with the user, or
405 * <code>onDestroy()</code> if this activity is going away.</td>
406 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
407 * <td align="center"><code>onRestart()</code> or<br>
408 * <code>onDestroy()</code></td>
409 * </tr>
410 *
smain@google.com10e29b82016-06-23 12:09:30 -0700411 * <tr><td colspan="3" align="left" border="0">{@link android.app.Activity#onDestroy onDestroy()}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 * <td>The final call you receive before your
413 * activity is destroyed. This can happen either because the
414 * activity is finishing (someone called {@link Activity#finish} on
koprivafdb0bff2018-09-29 15:22:41 -0700415 * it), or because the system is temporarily destroying this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 * instance of the activity to save space. You can distinguish
417 * between these two scenarios with the {@link
418 * Activity#isFinishing} method.</td>
419 * <td align="center"><font color="#800000"><strong>Yes</strong></font></td>
420 * <td align="center"><em>nothing</em></td>
421 * </tr>
422 * </tbody>
423 * </table>
424 *
425 * <p>Note the "Killable" column in the above table -- for those methods that
426 * are marked as being killable, after that method returns the process hosting the
Kris Giesing8b6216d2014-12-16 17:23:15 -0800427 * activity may be killed by the system <em>at any time</em> without another line
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 * of its code being executed. Because of this, you should use the
429 * {@link #onPause} method to write any persistent data (such as user edits)
430 * to storage. In addition, the method
431 * {@link #onSaveInstanceState(Bundle)} is called before placing the activity
432 * in such a background state, allowing you to save away any dynamic instance
433 * state in your activity into the given Bundle, to be later received in
RoboErik55011652014-07-09 15:05:53 -0700434 * {@link #onCreate} if the activity needs to be re-created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 * See the <a href="#ProcessLifecycle">Process Lifecycle</a>
436 * section for more information on how the lifecycle of a process is tied
437 * to the activities it is hosting. Note that it is important to save
438 * persistent data in {@link #onPause} instead of {@link #onSaveInstanceState}
Daisuke Miyakawa5c40f3f2011-02-15 13:24:36 -0800439 * because the latter is not part of the lifecycle callbacks, so will not
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 * be called in every situation as described in its documentation.</p>
441 *
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800442 * <p class="note">Be aware that these semantics will change slightly between
443 * applications targeting platforms starting with {@link android.os.Build.VERSION_CODES#HONEYCOMB}
444 * vs. those targeting prior platforms. Starting with Honeycomb, an application
445 * is not in the killable state until its {@link #onStop} has returned. This
446 * impacts when {@link #onSaveInstanceState(Bundle)} may be called (it may be
Joshua Baxter9a841a62018-03-27 14:42:03 -0700447 * safely called after {@link #onPause()}) and allows an application to safely
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800448 * wait until {@link #onStop()} to save persistent state.</p>
449 *
Andrii Kulian391161f2018-01-29 10:50:02 -0800450 * <p class="note">For applications targeting platforms starting with
451 * {@link android.os.Build.VERSION_CODES#P} {@link #onSaveInstanceState(Bundle)}
452 * will always be called after {@link #onStop}, so an application may safely
453 * perform fragment transactions in {@link #onStop} and will be able to save
454 * persistent state later.</p>
455 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 * <p>For those methods that are not marked as being killable, the activity's
457 * process will not be killed by the system starting from the time the method
458 * is called and continuing after it returns. Thus an activity is in the killable
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700459 * state, for example, between after <code>onStop()</code> to the start of
460 * <code>onResume()</code>. Keep in mind that under extreme memory pressure the
461 * system can kill the application process at any time.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 *
463 * <a name="ConfigurationChanges"></a>
464 * <h3>Configuration Changes</h3>
RoboErik55011652014-07-09 15:05:53 -0700465 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 * <p>If the configuration of the device (as defined by the
467 * {@link Configuration Resources.Configuration} class) changes,
468 * then anything displaying a user interface will need to update to match that
469 * configuration. Because Activity is the primary mechanism for interacting
470 * with the user, it includes special support for handling configuration
471 * changes.</p>
RoboErik55011652014-07-09 15:05:53 -0700472 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 * <p>Unless you specify otherwise, a configuration change (such as a change
474 * in screen orientation, language, input devices, etc) will cause your
475 * current activity to be <em>destroyed</em>, going through the normal activity
476 * lifecycle process of {@link #onPause},
477 * {@link #onStop}, and {@link #onDestroy} as appropriate. If the activity
478 * had been in the foreground or visible to the user, once {@link #onDestroy} is
479 * called in that instance then a new instance of the activity will be
480 * created, with whatever savedInstanceState the previous instance had generated
481 * from {@link #onSaveInstanceState}.</p>
RoboErik55011652014-07-09 15:05:53 -0700482 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 * <p>This is done because any application resource,
484 * including layout files, can change based on any configuration value. Thus
485 * the only safe way to handle a configuration change is to re-retrieve all
486 * resources, including layouts, drawables, and strings. Because activities
487 * must already know how to save their state and re-create themselves from
488 * that state, this is a convenient way to have an activity restart itself
489 * with a new configuration.</p>
RoboErik55011652014-07-09 15:05:53 -0700490 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 * <p>In some special cases, you may want to bypass restarting of your
492 * activity based on one or more types of configuration changes. This is
493 * done with the {@link android.R.attr#configChanges android:configChanges}
494 * attribute in its manifest. For any types of configuration changes you say
495 * that you handle there, you will receive a call to your current activity's
496 * {@link #onConfigurationChanged} method instead of being restarted. If
497 * a configuration change involves any that you do not handle, however, the
498 * activity will still be restarted and {@link #onConfigurationChanged}
499 * will not be called.</p>
RoboErik55011652014-07-09 15:05:53 -0700500 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 * <a name="StartingActivities"></a>
502 * <h3>Starting Activities and Getting Results</h3>
503 *
504 * <p>The {@link android.app.Activity#startActivity}
505 * method is used to start a
506 * new activity, which will be placed at the top of the activity stack. It
507 * takes a single argument, an {@link android.content.Intent Intent},
508 * which describes the activity
509 * to be executed.</p>
510 *
511 * <p>Sometimes you want to get a result back from an activity when it
512 * ends. For example, you may start an activity that lets the user pick
513 * a person in a list of contacts; when it ends, it returns the person
514 * that was selected. To do this, you call the
RoboErik55011652014-07-09 15:05:53 -0700515 * {@link android.app.Activity#startActivityForResult(Intent, int)}
516 * version with a second integer parameter identifying the call. The result
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 * will come back through your {@link android.app.Activity#onActivityResult}
RoboErik55011652014-07-09 15:05:53 -0700518 * method.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 *
520 * <p>When an activity exits, it can call
521 * {@link android.app.Activity#setResult(int)}
522 * to return data back to its parent. It must always supply a result code,
523 * which can be the standard results RESULT_CANCELED, RESULT_OK, or any
524 * custom values starting at RESULT_FIRST_USER. In addition, it can optionally
525 * return back an Intent containing any additional data it wants. All of this
526 * information appears back on the
527 * parent's <code>Activity.onActivityResult()</code>, along with the integer
528 * identifier it originally supplied.</p>
529 *
530 * <p>If a child activity fails for any reason (such as crashing), the parent
531 * activity will receive a result with the code RESULT_CANCELED.</p>
532 *
533 * <pre class="prettyprint">
534 * public class MyActivity extends Activity {
535 * ...
536 *
537 * static final int PICK_CONTACT_REQUEST = 0;
538 *
Michael Wright5438e4e2014-07-25 14:05:42 -0700539 * public boolean onKeyDown(int keyCode, KeyEvent event) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 * if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
541 * // When the user center presses, let them pick a contact.
542 * startActivityForResult(
543 * new Intent(Intent.ACTION_PICK,
544 * new Uri("content://contacts")),
545 * PICK_CONTACT_REQUEST);
546 * return true;
547 * }
548 * return false;
549 * }
550 *
551 * protected void onActivityResult(int requestCode, int resultCode,
552 * Intent data) {
553 * if (requestCode == PICK_CONTACT_REQUEST) {
554 * if (resultCode == RESULT_OK) {
555 * // A contact was picked. Here we will just display it
556 * // to the user.
557 * startActivity(new Intent(Intent.ACTION_VIEW, data));
558 * }
559 * }
560 * }
561 * }
562 * </pre>
563 *
564 * <a name="SavingPersistentState"></a>
565 * <h3>Saving Persistent State</h3>
566 *
koprivafc3949e2018-09-17 11:35:13 -0700567 * <p>There are generally two kinds of persistent state that an activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 * will deal with: shared document-like data (typically stored in a SQLite
569 * database using a {@linkplain android.content.ContentProvider content provider})
570 * and internal state such as user preferences.</p>
571 *
koprivafc3949e2018-09-17 11:35:13 -0700572 * <p>For content provider data, we suggest that activities use an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 * "edit in place" user model. That is, any edits a user makes are effectively
574 * made immediately without requiring an additional confirmation step.
575 * Supporting this model is generally a simple matter of following two rules:</p>
576 *
577 * <ul>
578 * <li> <p>When creating a new document, the backing database entry or file for
579 * it is created immediately. For example, if the user chooses to write
Andrew Solovayab8ea9f2017-10-06 19:02:28 -0700580 * a new email, a new entry for that email is created as soon as they
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * start entering data, so that if they go to any other activity after
Andrew Solovayab8ea9f2017-10-06 19:02:28 -0700582 * that point this email will now appear in the list of drafts.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * <li> <p>When an activity's <code>onPause()</code> method is called, it should
584 * commit to the backing content provider or file any changes the user
585 * has made. This ensures that those changes will be seen by any other
586 * activity that is about to run. You will probably want to commit
587 * your data even more aggressively at key times during your
588 * activity's lifecycle: for example before starting a new
589 * activity, before finishing your own activity, when the user
590 * switches between input fields, etc.</p>
591 * </ul>
592 *
593 * <p>This model is designed to prevent data loss when a user is navigating
594 * between activities, and allows the system to safely kill an activity (because
595 * system resources are needed somewhere else) at any time after it has been
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700596 * stopped (or paused on platform versions before {@link android.os.Build.VERSION_CODES#HONEYCOMB}).
597 * Note this implies that the user pressing BACK from your activity does <em>not</em>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 * mean "cancel" -- it means to leave the activity with its current contents
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800599 * saved away. Canceling edits in an activity must be provided through
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 * some other mechanism, such as an explicit "revert" or "undo" option.</p>
601 *
602 * <p>See the {@linkplain android.content.ContentProvider content package} for
603 * more information about content providers. These are a key aspect of how
604 * different activities invoke and propagate data between themselves.</p>
605 *
606 * <p>The Activity class also provides an API for managing internal persistent state
607 * associated with an activity. This can be used, for example, to remember
608 * the user's preferred initial display in a calendar (day view or week view)
609 * or the user's default home page in a web browser.</p>
610 *
611 * <p>Activity persistent state is managed
612 * with the method {@link #getPreferences},
613 * allowing you to retrieve and
614 * modify a set of name/value pairs associated with the activity. To use
615 * preferences that are shared across multiple application components
616 * (activities, receivers, services, providers), you can use the underlying
617 * {@link Context#getSharedPreferences Context.getSharedPreferences()} method
618 * to retrieve a preferences
619 * object stored under a specific name.
620 * (Note that it is not possible to share settings data across application
621 * packages -- for that you will need a content provider.)</p>
622 *
623 * <p>Here is an excerpt from a calendar activity that stores the user's
624 * preferred view mode in its persistent settings:</p>
625 *
626 * <pre class="prettyprint">
627 * public class CalendarActivity extends Activity {
628 * ...
629 *
630 * static final int DAY_VIEW_MODE = 0;
631 * static final int WEEK_VIEW_MODE = 1;
632 *
633 * private SharedPreferences mPrefs;
634 * private int mCurViewMode;
635 *
636 * protected void onCreate(Bundle savedInstanceState) {
637 * super.onCreate(savedInstanceState);
638 *
639 * SharedPreferences mPrefs = getSharedPreferences();
Quddus Chong3fa98cb2012-04-13 11:17:24 -0700640 * mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 * }
642 *
643 * protected void onPause() {
644 * super.onPause();
RoboErik55011652014-07-09 15:05:53 -0700645 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * SharedPreferences.Editor ed = mPrefs.edit();
647 * ed.putInt("view_mode", mCurViewMode);
648 * ed.commit();
649 * }
650 * }
651 * </pre>
RoboErik55011652014-07-09 15:05:53 -0700652 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * <a name="Permissions"></a>
654 * <h3>Permissions</h3>
RoboErik55011652014-07-09 15:05:53 -0700655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 * <p>The ability to start a particular Activity can be enforced when it is
657 * declared in its
658 * manifest's {@link android.R.styleable#AndroidManifestActivity &lt;activity&gt;}
659 * tag. By doing so, other applications will need to declare a corresponding
660 * {@link android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
661 * element in their own manifest to be able to start that activity.
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800662 *
663 * <p>When starting an Activity you can set {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
664 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
665 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} on the Intent. This will grant the
666 * Activity access to the specific URIs in the Intent. Access will remain
667 * until the Activity has finished (it will remain across the hosting
668 * process being killed and other temporary destruction). As of
669 * {@link android.os.Build.VERSION_CODES#GINGERBREAD}, if the Activity
670 * was already created and a new Intent is being delivered to
671 * {@link #onNewIntent(Intent)}, any newly granted URI permissions will be added
672 * to the existing ones it holds.
673 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
675 * document for more information on permissions and security in general.
RoboErik55011652014-07-09 15:05:53 -0700676 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 * <a name="ProcessLifecycle"></a>
678 * <h3>Process Lifecycle</h3>
RoboErik55011652014-07-09 15:05:53 -0700679 *
kopriva4dddc632018-03-19 14:13:08 -0700680 * <p>The Android system attempts to keep an application process around for as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 * long as possible, but eventually will need to remove old processes when
kopriva4dddc632018-03-19 14:13:08 -0700682 * memory runs low. As described in <a href="#ActivityLifecycle">Activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 * Lifecycle</a>, the decision about which process to remove is intimately
kopriva4dddc632018-03-19 14:13:08 -0700684 * tied to the state of the user's interaction with it. In general, there
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 * are four states a process can be in based on the activities running in it,
kopriva4dddc632018-03-19 14:13:08 -0700686 * listed here in order of importance. The system will kill less important
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 * processes (the last ones) before it resorts to killing more important
688 * processes (the first ones).
RoboErik55011652014-07-09 15:05:53 -0700689 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * <ol>
691 * <li> <p>The <b>foreground activity</b> (the activity at the top of the screen
692 * that the user is currently interacting with) is considered the most important.
693 * Its process will only be killed as a last resort, if it uses more memory
694 * than is available on the device. Generally at this point the device has
695 * reached a memory paging state, so this is required in order to keep the user
696 * interface responsive.
697 * <li> <p>A <b>visible activity</b> (an activity that is visible to the user
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700698 * but not in the foreground, such as one sitting behind a foreground dialog
699 * or next to other activities in multi-window mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 * is considered extremely important and will not be killed unless that is
701 * required to keep the foreground activity running.
702 * <li> <p>A <b>background activity</b> (an activity that is not visible to
Andrii Kulian8e4df1e2019-03-19 15:17:56 -0700703 * the user and has been stopped) is no longer critical, so the system may
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 * safely kill its process to reclaim memory for other foreground or
705 * visible processes. If its process needs to be killed, when the user navigates
706 * back to the activity (making it visible on the screen again), its
707 * {@link #onCreate} method will be called with the savedInstanceState it had previously
708 * supplied in {@link #onSaveInstanceState} so that it can restart itself in the same
709 * state as the user last left it.
710 * <li> <p>An <b>empty process</b> is one hosting no activities or other
711 * application components (such as {@link Service} or
712 * {@link android.content.BroadcastReceiver} classes). These are killed very
713 * quickly by the system as memory becomes low. For this reason, any
714 * background operation you do outside of an activity must be executed in the
715 * context of an activity BroadcastReceiver or Service to ensure that the system
716 * knows it needs to keep your process around.
717 * </ol>
RoboErik55011652014-07-09 15:05:53 -0700718 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 * <p>Sometimes an Activity may need to do a long-running operation that exists
720 * independently of the activity lifecycle itself. An example may be a camera
721 * application that allows you to upload a picture to a web site. The upload
722 * may take a long time, and the application should allow the user to leave
Trevor Johns682c24e2016-04-12 10:13:47 -0700723 * the application while it is executing. To accomplish this, your Activity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 * should start a {@link Service} in which the upload takes place. This allows
725 * the system to properly prioritize your process (considering it to be more
726 * important than other non-visible applications) for the duration of the
727 * upload, independent of whether the original activity is paused, stopped,
728 * or finished.
729 */
730public class Activity extends ContextThemeWrapper
Dianne Hackborn625ac272010-09-17 18:29:22 -0700731 implements LayoutInflater.Factory2,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 Window.Callback, KeyEvent.Callback,
Adam Powell117b6952014-05-05 18:14:56 -0700733 OnCreateContextMenuListener, ComponentCallbacks2,
Mathew Inwoodd6973862019-12-05 10:15:19 +0000734 Window.OnWindowDismissedCallback,
Felipe Lemecbf7f262019-04-17 13:57:59 -0700735 AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 private static final String TAG = "Activity";
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700737 private static final boolean DEBUG_LIFECYCLE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738
739 /** Standard activity result: operation canceled. */
740 public static final int RESULT_CANCELED = 0;
741 /** Standard activity result: operation succeeded. */
742 public static final int RESULT_OK = -1;
743 /** Start of user-defined activity results. */
744 public static final int RESULT_FIRST_USER = 1;
745
Wale Ogunwaleba7881c2015-08-01 19:28:29 -0700746 /** @hide Task isn't finished when activity is finished */
747 public static final int DONT_FINISH_TASK_WITH_ACTIVITY = 0;
Filip Gruszczynskic29ecc82015-10-08 11:08:44 -0700748 /**
749 * @hide Task is finished if the finishing activity is the root of the task. To preserve the
750 * past behavior the task is also removed from recents.
751 */
Wale Ogunwaleba7881c2015-08-01 19:28:29 -0700752 public static final int FINISH_TASK_WITH_ROOT_ACTIVITY = 1;
Filip Gruszczynskic29ecc82015-10-08 11:08:44 -0700753 /**
754 * @hide Task is finished along with the finishing activity, but it is not removed from
755 * recents.
756 */
Wale Ogunwaleba7881c2015-08-01 19:28:29 -0700757 public static final int FINISH_TASK_WITH_ACTIVITY = 2;
758
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100759 @UnsupportedAppUsage
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700760 static final String FRAGMENTS_TAG = "android:fragments";
Phil Weaver846cda932017-06-15 10:10:06 -0700761 private static final String LAST_AUTOFILL_ID = "android:lastAutofillId";
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700762
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700763 private static final String AUTOFILL_RESET_NEEDED = "@android:autofillResetNeeded";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
765 private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
766 private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
767 private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800768 private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
Svetoslavffb32b12015-10-15 16:54:00 -0700769 private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
770 "android:hasCurrentPermissionsRequest";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771
Svetoslav970b59c2015-06-09 16:05:21 -0700772 private static final String REQUEST_PERMISSIONS_WHO_PREFIX = "@android:requestPermissions:";
Svet Ganov782043c2017-02-11 00:52:02 +0000773 private static final String AUTO_FILL_AUTH_WHO_PREFIX = "@android:autoFillAuth:";
Andrei Stingaceanu0bf096f2016-04-14 18:11:57 +0100774 private static final String KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME = "com.android.systemui";
Andrei Stingaceanu0bf096f2016-04-14 18:11:57 +0100775
Winson Chungf2b41772019-11-06 15:00:48 -0800776 private static final int LOG_AM_ON_CREATE_CALLED = 30057;
777 private static final int LOG_AM_ON_START_CALLED = 30059;
778 private static final int LOG_AM_ON_RESUME_CALLED = 30022;
779 private static final int LOG_AM_ON_PAUSE_CALLED = 30021;
780 private static final int LOG_AM_ON_STOP_CALLED = 30049;
781 private static final int LOG_AM_ON_RESTART_CALLED = 30058;
782 private static final int LOG_AM_ON_DESTROY_CALLED = 30060;
783 private static final int LOG_AM_ON_ACTIVITY_RESULT_CALLED = 30062;
784 private static final int LOG_AM_ON_TOP_RESUMED_GAINED_CALLED = 30064;
785 private static final int LOG_AM_ON_TOP_RESUMED_LOST_CALLED = 30065;
786
Dianne Hackborn8ea138c2010-01-26 18:01:04 -0800787 private static class ManagedDialog {
788 Dialog mDialog;
789 Bundle mArgs;
790 }
791 private SparseArray<ManagedDialog> mManagedDialogs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792
793 // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100794 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 private Instrumentation mInstrumentation;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100796 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 private IBinder mToken;
Sunny Goyald40c3452019-03-20 12:46:55 -0700798 private IBinder mAssistToken;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100799 @UnsupportedAppUsage
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700800 private int mIdent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100801 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 /*package*/ String mEmbeddedID;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100803 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 private Application mApplication;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100805 @UnsupportedAppUsage
Christopher Tateb70f3df2009-04-07 16:07:59 -0700806 /*package*/ Intent mIntent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100807 @UnsupportedAppUsage
Dianne Hackborn85d558c2014-11-04 10:31:54 -0800808 /*package*/ String mReferrer;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100809 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 private ComponentName mComponent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100811 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 /*package*/ ActivityInfo mActivityInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100813 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /*package*/ ActivityThread mMainThread;
Charles Chen5c0943d2019-07-30 17:21:47 +0800815 @UnsupportedAppUsage(trackingBug = 137825207, maxTargetSdk = Build.VERSION_CODES.Q,
816 publicAlternatives = "Use {@code androidx.fragment.app.Fragment} and "
817 + "{@code androidx.fragment.app.FragmentManager} instead")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 Activity mParent;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100819 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 boolean mCalled;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100821 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -0600822 /*package*/ boolean mResumed;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100823 @UnsupportedAppUsage
Andrii Kulian58178f22016-03-16 13:44:56 -0700824 /*package*/ boolean mStopped;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100825 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 boolean mFinished;
827 boolean mStartedActivity;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100828 @UnsupportedAppUsage
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -0700829 private boolean mDestroyed;
Dianne Hackborn2286cdc2013-07-01 19:10:06 -0700830 private boolean mDoReportFullyDrawn = true;
Jorim Jaggi4d27b842017-08-17 17:22:26 +0200831 private boolean mRestoredFromBundle;
Winson Chung298f95b2017-08-10 15:57:18 -0700832
833 /** {@code true} if the activity lifecycle is in a state which supports picture-in-picture.
834 * This only affects the client-side exception, the actual state check still happens in AMS. */
835 private boolean mCanEnterPictureInPicture = false;
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -0500836 /** true if the activity is being destroyed in order to recreate it with a new configuration */
837 /*package*/ boolean mChangingConfigurations = false;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100838 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 /*package*/ int mConfigChangeFlags;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100840 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 /*package*/ Configuration mCurrentConfig;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +0100842 private SearchManager mSearchManager;
Adam Powell88ab6972011-07-28 11:25:01 -0700843 private MenuInflater mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700845 /** The autofill manager. Always access via {@link #getAutofillManager()}. */
846 @Nullable private AutofillManager mAutofillManager;
847
Adam He43c06992019-04-15 15:41:49 -0700848 /** The content capture manager. Access via {@link #getContentCaptureManager()}. */
Felipe Lemeecb08be2018-11-27 15:48:47 -0800849 @Nullable private ContentCaptureManager mContentCaptureManager;
Felipe Lemee348dc32018-11-05 12:35:29 -0800850
Ian Lake8a88cd62018-09-28 13:25:20 -0700851 private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacks =
852 new ArrayList<Application.ActivityLifecycleCallbacks>();
Felipe Lemee348dc32018-11-05 12:35:29 -0800853
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700854 static final class NonConfigurationInstances {
855 Object activity;
856 HashMap<String, Object> children;
Adam Powell44ba79e2016-02-04 16:20:37 -0800857 FragmentManagerNonConfig fragments;
Todd Kennedya5fc6f02015-04-14 18:22:54 -0700858 ArrayMap<String, LoaderManager> loaders;
Dianne Hackborn20d94742014-05-29 18:35:45 -0700859 VoiceInteractor voiceInteractor;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700860 }
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100861 @UnsupportedAppUsage
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -0700862 /* package */ NonConfigurationInstances mLastNonConfigurationInstances;
RoboErik55011652014-07-09 15:05:53 -0700863
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100864 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 private Window mWindow;
866
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100867 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 private WindowManager mWindowManager;
869 /*package*/ View mDecor = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100870 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 /*package*/ boolean mWindowAdded = false;
872 /*package*/ boolean mVisibleFromServer = false;
Mathew Inwood31755f92018-12-20 13:53:36 +0000873 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 /*package*/ boolean mVisibleFromClient = true;
Adam Powelle43340c2014-03-17 19:10:43 -0700875 /*package*/ ActionBar mActionBar = null;
Adam Powelldd8fab22012-03-22 17:47:27 -0700876 private boolean mEnableDefaultActionBarUp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877
Mathew Inwood8c854f82018-09-14 12:35:36 +0100878 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Sunny Goyald40c3452019-03-20 12:46:55 -0700879 VoiceInteractor mVoiceInteractor;
Dianne Hackborn91097de2014-04-04 18:02:06 -0700880
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100881 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 private CharSequence mTitle;
883 private int mTitleColor = 0;
884
Todd Kennedya5fc6f02015-04-14 18:22:54 -0700885 // we must have a handler before the FragmentController is constructed
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100886 @UnsupportedAppUsage
Todd Kennedya5fc6f02015-04-14 18:22:54 -0700887 final Handler mHandler = new Handler();
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100888 @UnsupportedAppUsage
Todd Kennedya5fc6f02015-04-14 18:22:54 -0700889 final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
Craig Mautneree2e45a2014-06-27 12:10:03 -0700890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 private static final class ManagedCursor {
892 ManagedCursor(Cursor cursor) {
893 mCursor = cursor;
894 mReleased = false;
895 mUpdated = false;
896 }
897
898 private final Cursor mCursor;
899 private boolean mReleased;
900 private boolean mUpdated;
901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902
Felipe Leme29a5b0d2016-10-25 14:57:11 -0700903 @GuardedBy("mManagedCursors")
904 private final ArrayList<ManagedCursor> mManagedCursors = new ArrayList<>();
905
906 @GuardedBy("this")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100907 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 int mResultCode = RESULT_CANCELED;
Felipe Leme29a5b0d2016-10-25 14:57:11 -0700909 @GuardedBy("this")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100910 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 Intent mResultData = null;
Craig Mautneree2e45a2014-06-27 12:10:03 -0700912
Craig Mautner5eda9b32013-07-02 11:58:16 -0700913 private TranslucentConversionListener mTranslucentCallback;
Craig Mautnerbc57cd12013-08-19 15:47:42 -0700914 private boolean mChangeCanvasToTranslucent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
Tim Kilbourn6a975b32015-04-09 17:14:34 -0700916 private SearchEvent mSearchEvent;
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 private boolean mTitleReady = false;
Clara Bayarri4423d912015-03-02 19:42:48 +0000919 private int mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920
921 private int mDefaultKeyMode = DEFAULT_KEYS_DISABLE;
922 private SpannableStringBuilder mDefaultKeySsb = null;
RoboErik55011652014-07-09 15:05:53 -0700923
Winsonb6403152016-02-23 13:32:09 -0800924 private ActivityManager.TaskDescription mTaskDescription =
925 new ActivityManager.TaskDescription();
926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
928
Dianne Hackborn62bea2f2012-09-04 18:48:15 -0700929 @SuppressWarnings("unused")
Jeff Brown7e442832011-06-10 18:00:16 -0700930 private final Object mInstanceTracker = StrictMode.trackActivity(this);
931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 private Thread mUiThread;
George Mount62ab9b72014-05-02 13:51:17 -0700933
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100934 @UnsupportedAppUsage
George Mount1fecfb22014-06-18 14:55:55 -0700935 ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
George Mount65580562014-08-29 08:15:48 -0700936 SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
937 SharedElementCallback mExitTransitionListener = SharedElementCallback.NULL_CALLBACK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938
Svetoslavffb32b12015-10-15 16:54:00 -0700939 private boolean mHasCurrentPermissionsRequest;
940
Svet Ganov17db9dc2017-02-21 19:54:31 -0800941 private boolean mAutoFillResetNeeded;
Dake Gu67decfa2017-12-27 11:48:08 -0800942 private boolean mAutoFillIgnoreFirstResumePause;
Svet Ganov17db9dc2017-02-21 19:54:31 -0800943
Phil Weaver846cda932017-06-15 10:10:06 -0700944 /** The last autofill id that was returned from {@link #getNextAutofillId()} */
945 private int mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -0700946
Felipe Leme4753bb02017-03-22 20:24:00 -0700947 private AutofillPopupWindow mAutofillPopupWindow;
948
chaviwfeb2e1e2018-12-19 17:24:11 -0800949 /** @hide */
950 boolean mEnterAnimationComplete;
951
Hongwei Wangf7e5a232020-05-06 15:49:44 -0700952 private boolean mIsInMultiWindowMode;
953 private boolean mIsInPictureInPictureMode;
Hongwei Wang2cebfd52019-07-25 15:14:47 -0700954
Mathew Inwoodd6973862019-12-05 10:15:19 +0000955 private final WindowControllerCallback mWindowControllerCallback =
956 new WindowControllerCallback() {
957 /**
958 * Moves the activity between {@link WindowConfiguration#WINDOWING_MODE_FREEFORM} windowing
959 * mode and {@link WindowConfiguration#WINDOWING_MODE_FULLSCREEN}.
960 *
961 * @hide
962 */
963 @Override
964 public void toggleFreeformWindowingMode() throws RemoteException {
965 ActivityTaskManager.getService().toggleFreeformWindowingMode(mToken);
966 }
967
968 /**
969 * Puts the activity in picture-in-picture mode if the activity supports.
970 * @see android.R.attr#supportsPictureInPicture
971 * @hide
972 */
973 @Override
974 public void enterPictureInPictureModeIfPossible() {
975 if (mActivityInfo.supportsPictureInPicture()) {
976 enterPictureInPictureMode();
977 }
978 }
979
980 @Override
981 public boolean isTaskRoot() {
982 try {
983 return ActivityTaskManager.getService().getTaskForActivity(mToken, true) >= 0;
984 } catch (RemoteException e) {
985 return false;
986 }
987 }
988
989 /**
990 * Update the forced status bar color.
991 * @hide
992 */
993 @Override
994 public void updateStatusBarColor(int color) {
995 mTaskDescription.setStatusBarColor(color);
996 setTaskDescription(mTaskDescription);
997 }
998
999 /**
1000 * Update the forced navigation bar color.
1001 * @hide
1002 */
1003 @Override
1004 public void updateNavigationBarColor(int color) {
1005 mTaskDescription.setNavigationBarColor(color);
1006 setTaskDescription(mTaskDescription);
1007 }
1008
1009 };
1010
Dimitry Ivanov4449ef52016-02-25 17:41:13 -08001011 private static native String getDlWarning();
1012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 /** Return the intent that started this activity. */
1014 public Intent getIntent() {
1015 return mIntent;
1016 }
1017
RoboErik55011652014-07-09 15:05:53 -07001018 /**
1019 * Change the intent returned by {@link #getIntent}. This holds a
1020 * reference to the given intent; it does not copy it. Often used in
1021 * conjunction with {@link #onNewIntent}.
1022 *
1023 * @param newIntent The new Intent object to return from getIntent
1024 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 * @see #getIntent
1026 * @see #onNewIntent
RoboErik55011652014-07-09 15:05:53 -07001027 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 public void setIntent(Intent newIntent) {
1029 mIntent = newIntent;
1030 }
1031
Yuliya Kamatkova48c38072020-01-09 15:43:25 -08001032 /**
1033 * Sets the {@link android.content.LocusId} for this activity. The locus id
1034 * helps identify different instances of the same {@code Activity} class.
1035 * <p> For example, a locus id based on a specific conversation could be set on a
1036 * conversation app's chat {@code Activity}. The system can then use this locus id
1037 * along with app's contents to provide ranking signals in various UI surfaces
1038 * including sharing, notifications, shortcuts and so on.
1039 * <p> It is recommended to set the same locus id in the shortcut's locus id using
1040 * {@link android.content.pm.ShortcutInfo.Builder#setLocusId(android.content.LocusId)
1041 * setLocusId}
1042 * so that the system can learn appropriate ranking signals linking the activity's
1043 * locus id with the matching shortcut.
1044 *
1045 * @param locusId a unique, stable id that identifies this {@code Activity} instance from
1046 * others. This can be linked to a shortcut using
1047 * {@link android.content.pm.ShortcutInfo.Builder#setLocusId(android.content.LocusId)
1048 * setLocusId} with the same locus id string.
1049 * @param bundle extras set or updated as part of this locus context. This may help provide
1050 * additional metadata such as URLs, conversation participants specific to this
1051 * {@code Activity}'s context.
1052 *
1053 * @see android.view.contentcapture.ContentCaptureManager
1054 * @see android.view.contentcapture.ContentCaptureContext
1055 */
1056 public void setLocusContext(@Nullable LocusId locusId, @Nullable Bundle bundle) {
1057 try {
1058 ActivityManager.getService().setActivityLocusContext(mComponent, locusId, mToken);
1059 } catch (RemoteException re) {
1060 re.rethrowFromSystemServer();
1061 }
Yuliya Kamatkovab5d87a82020-02-13 16:00:52 -08001062 // If locusId is not null pass it to the Content Capture.
1063 if (locusId != null) {
1064 setLocusContextToContentCapture(locusId, bundle);
1065 }
Yuliya Kamatkova48c38072020-01-09 15:43:25 -08001066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 /** Return the application that owns this activity. */
1069 public final Application getApplication() {
1070 return mApplication;
1071 }
1072
1073 /** Is this activity embedded inside of another activity? */
1074 public final boolean isChild() {
1075 return mParent != null;
1076 }
RoboErik55011652014-07-09 15:05:53 -07001077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 /** Return the parent activity if this view is an embedded child. */
1079 public final Activity getParent() {
1080 return mParent;
1081 }
1082
1083 /** Retrieve the window manager for showing custom windows. */
1084 public WindowManager getWindowManager() {
1085 return mWindowManager;
1086 }
1087
1088 /**
1089 * Retrieve the current {@link android.view.Window} for the activity.
1090 * This can be used to directly access parts of the Window API that
1091 * are not available through Activity/Screen.
RoboErik55011652014-07-09 15:05:53 -07001092 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 * @return Window The current window, or null if the activity is not
1094 * visual.
1095 */
1096 public Window getWindow() {
1097 return mWindow;
1098 }
1099
1100 /**
Mark Doliner9525f2a2014-01-02 11:17:47 -08001101 * Return the LoaderManager for this activity, creating it if needed.
Ian Lake0a1feb82017-11-13 10:26:46 -08001102 *
1103 * @deprecated Use {@link android.support.v4.app.FragmentActivity#getSupportLoaderManager()}
Dianne Hackbornc8017682010-07-06 13:34:38 -07001104 */
Ian Lake0a1feb82017-11-13 10:26:46 -08001105 @Deprecated
Dianne Hackbornc8017682010-07-06 13:34:38 -07001106 public LoaderManager getLoaderManager() {
Todd Kennedya5fc6f02015-04-14 18:22:54 -07001107 return mFragments.getLoaderManager();
Dianne Hackbornc8017682010-07-06 13:34:38 -07001108 }
RoboErik55011652014-07-09 15:05:53 -07001109
Dianne Hackbornc8017682010-07-06 13:34:38 -07001110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * Calls {@link android.view.Window#getCurrentFocus} on the
1112 * Window of this Activity to return the currently focused view.
RoboErik55011652014-07-09 15:05:53 -07001113 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 * @return View The current View with focus or null.
RoboErik55011652014-07-09 15:05:53 -07001115 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 * @see #getWindow
1117 * @see android.view.Window#getCurrentFocus
1118 */
Tor Norbyed9273d62013-05-30 15:59:53 -07001119 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 public View getCurrentFocus() {
1121 return mWindow != null ? mWindow.getCurrentFocus() : null;
1122 }
1123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 /**
Felipe Lemee348dc32018-11-05 12:35:29 -08001125 * (Creates, sets and) returns the autofill manager
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001126 *
1127 * @return The autofill manager
1128 */
1129 @NonNull private AutofillManager getAutofillManager() {
1130 if (mAutofillManager == null) {
1131 mAutofillManager = getSystemService(AutofillManager.class);
1132 }
1133
1134 return mAutofillManager;
1135 }
1136
Felipe Lemee348dc32018-11-05 12:35:29 -08001137 /**
Felipe Lemeecb08be2018-11-27 15:48:47 -08001138 * (Creates, sets, and ) returns the content capture manager
Felipe Lemee348dc32018-11-05 12:35:29 -08001139 *
Felipe Lemeecb08be2018-11-27 15:48:47 -08001140 * @return The content capture manager
Felipe Lemee348dc32018-11-05 12:35:29 -08001141 */
Adam Heb66babb2019-01-08 15:43:53 -08001142 @Nullable private ContentCaptureManager getContentCaptureManager() {
1143 // ContextCapture disabled for system apps
Felipe Leme0c6b23d2019-01-15 17:02:49 -08001144 if (!UserHandle.isApp(myUid())) return null;
Felipe Lemeecb08be2018-11-27 15:48:47 -08001145 if (mContentCaptureManager == null) {
1146 mContentCaptureManager = getSystemService(ContentCaptureManager.class);
Felipe Lemee348dc32018-11-05 12:35:29 -08001147 }
Felipe Lemeecb08be2018-11-27 15:48:47 -08001148 return mContentCaptureManager;
Felipe Lemee348dc32018-11-05 12:35:29 -08001149 }
1150
Felipe Lemeaa5088e2018-12-10 14:53:58 -08001151 /** @hide */ private static final int CONTENT_CAPTURE_START = 1;
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001152 /** @hide */ private static final int CONTENT_CAPTURE_RESUME = 2;
1153 /** @hide */ private static final int CONTENT_CAPTURE_PAUSE = 3;
1154 /** @hide */ private static final int CONTENT_CAPTURE_STOP = 4;
Felipe Lemeaa5088e2018-12-10 14:53:58 -08001155
1156 /** @hide */
1157 @IntDef(prefix = { "CONTENT_CAPTURE_" }, value = {
1158 CONTENT_CAPTURE_START,
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001159 CONTENT_CAPTURE_RESUME,
1160 CONTENT_CAPTURE_PAUSE,
Felipe Lemeaa5088e2018-12-10 14:53:58 -08001161 CONTENT_CAPTURE_STOP
1162 })
1163 @Retention(RetentionPolicy.SOURCE)
1164 @interface ContentCaptureNotificationType{}
1165
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001166 private String getContentCaptureTypeAsString(@ContentCaptureNotificationType int type) {
Felipe Lemeaa5088e2018-12-10 14:53:58 -08001167 switch (type) {
1168 case CONTENT_CAPTURE_START:
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001169 return "START";
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001170 case CONTENT_CAPTURE_RESUME:
1171 return "RESUME";
1172 case CONTENT_CAPTURE_PAUSE:
1173 return "PAUSE";
Felipe Lemeaa5088e2018-12-10 14:53:58 -08001174 case CONTENT_CAPTURE_STOP:
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001175 return "STOP";
Felipe Leme7a534082018-11-05 15:03:04 -08001176 default:
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001177 return "UNKNOW-" + type;
1178 }
1179 }
1180
1181 private void notifyContentCaptureManagerIfNeeded(@ContentCaptureNotificationType int type) {
1182 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1183 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1184 "notifyContentCapture(" + getContentCaptureTypeAsString(type) + ") for "
1185 + mComponent.toShortString());
1186 }
1187 try {
1188 final ContentCaptureManager cm = getContentCaptureManager();
1189 if (cm == null) return;
1190
1191 switch (type) {
1192 case CONTENT_CAPTURE_START:
1193 //TODO(b/111276913): decide whether the InteractionSessionId should be
1194 // saved / restored in the activity bundle - probably not
Adam He43c06992019-04-15 15:41:49 -07001195 final Window window = getWindow();
1196 if (window != null) {
1197 cm.updateWindowAttributes(window.getAttributes());
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001198 }
Adam He43c06992019-04-15 15:41:49 -07001199 cm.onActivityCreated(mToken, getComponentName());
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001200 break;
1201 case CONTENT_CAPTURE_RESUME:
1202 cm.onActivityResumed();
1203 break;
1204 case CONTENT_CAPTURE_PAUSE:
1205 cm.onActivityPaused();
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001206 break;
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001207 case CONTENT_CAPTURE_STOP:
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001208 cm.onActivityDestroyed();
Felipe Lemeb337e1c2019-01-18 13:06:17 -08001209 break;
1210 default:
1211 Log.wtf(TAG, "Invalid @ContentCaptureNotificationType: " + type);
1212 }
1213 } finally {
1214 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Felipe Leme7a534082018-11-05 15:03:04 -08001215 }
1216 }
1217
Yuliya Kamatkovab5d87a82020-02-13 16:00:52 -08001218 private void setLocusContextToContentCapture(LocusId locusId, @Nullable Bundle bundle) {
1219 final ContentCaptureManager cm = getContentCaptureManager();
1220 if (cm == null) return;
1221
1222 ContentCaptureContext.Builder contentCaptureContextBuilder =
1223 new ContentCaptureContext.Builder(locusId);
1224 if (bundle != null) {
1225 contentCaptureContextBuilder.setExtras(bundle);
1226 }
1227 cm.getMainContentCaptureSession().setContentCaptureContext(
1228 contentCaptureContextBuilder.build());
1229 }
1230
Felipe Lemebb567ae2017-10-04 09:56:21 -07001231 @Override
1232 protected void attachBaseContext(Context newBase) {
1233 super.attachBaseContext(newBase);
Felipe Lemed247de82018-05-14 17:51:58 -07001234 if (newBase != null) {
1235 newBase.setAutofillClient(this);
Felipe Leme326f15a2019-02-19 09:42:24 -08001236 newBase.setContentCaptureOptions(getContentCaptureOptions());
Felipe Lemed247de82018-05-14 17:51:58 -07001237 }
Felipe Lemebb567ae2017-10-04 09:56:21 -07001238 }
1239
1240 /** @hide */
1241 @Override
1242 public final AutofillClient getAutofillClient() {
1243 return this;
1244 }
1245
Felipe Lemecbf7f262019-04-17 13:57:59 -07001246 /** @hide */
1247 @Override
1248 public final ContentCaptureClient getContentCaptureClient() {
1249 return this;
1250 }
1251
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001252 /**
Ian Lake8a88cd62018-09-28 13:25:20 -07001253 * Register an {@link Application.ActivityLifecycleCallbacks} instance that receives
1254 * lifecycle callbacks for only this Activity.
1255 * <p>
1256 * In relation to any
1257 * {@link Application#registerActivityLifecycleCallbacks Application registered callbacks},
1258 * the callbacks registered here will always occur nested within those callbacks. This means:
1259 * <ul>
1260 * <li>Pre events will first be sent to Application registered callbacks, then to callbacks
1261 * registered here.</li>
1262 * <li>{@link Application.ActivityLifecycleCallbacks#onActivityCreated(Activity, Bundle)},
1263 * {@link Application.ActivityLifecycleCallbacks#onActivityStarted(Activity)}, and
1264 * {@link Application.ActivityLifecycleCallbacks#onActivityResumed(Activity)} will
1265 * be sent first to Application registered callbacks, then to callbacks registered here.
1266 * For all other events, callbacks registered here will be sent first.</li>
1267 * <li>Post events will first be sent to callbacks registered here, then to
1268 * Application registered callbacks.</li>
1269 * </ul>
1270 * <p>
1271 * If multiple callbacks are registered here, they receive events in a first in (up through
1272 * {@link Application.ActivityLifecycleCallbacks#onActivityPostResumed}, last out
1273 * ordering.
1274 * <p>
1275 * It is strongly recommended to register this in the constructor of your Activity to ensure
1276 * you get all available callbacks. As this callback is associated with only this Activity,
1277 * it is not usually necessary to {@link #unregisterActivityLifecycleCallbacks unregister} it
1278 * unless you specifically do not want to receive further lifecycle callbacks.
1279 *
1280 * @param callback The callback instance to register
1281 */
1282 public void registerActivityLifecycleCallbacks(
1283 @NonNull Application.ActivityLifecycleCallbacks callback) {
1284 synchronized (mActivityLifecycleCallbacks) {
1285 mActivityLifecycleCallbacks.add(callback);
1286 }
1287 }
1288
1289 /**
1290 * Unregister an {@link Application.ActivityLifecycleCallbacks} previously registered
1291 * with {@link #registerActivityLifecycleCallbacks}. It will not receive any further
1292 * callbacks.
1293 *
1294 * @param callback The callback instance to unregister
1295 * @see #registerActivityLifecycleCallbacks
1296 */
1297 public void unregisterActivityLifecycleCallbacks(
1298 @NonNull Application.ActivityLifecycleCallbacks callback) {
1299 synchronized (mActivityLifecycleCallbacks) {
1300 mActivityLifecycleCallbacks.remove(callback);
1301 }
1302 }
1303
1304 private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) {
1305 getApplication().dispatchActivityPreCreated(this, savedInstanceState);
1306 Object[] callbacks = collectActivityLifecycleCallbacks();
1307 if (callbacks != null) {
1308 for (int i = 0; i < callbacks.length; i++) {
1309 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this,
1310 savedInstanceState);
1311 }
1312 }
1313 }
1314
1315 private void dispatchActivityCreated(@Nullable Bundle savedInstanceState) {
1316 getApplication().dispatchActivityCreated(this, savedInstanceState);
1317 Object[] callbacks = collectActivityLifecycleCallbacks();
1318 if (callbacks != null) {
1319 for (int i = 0; i < callbacks.length; i++) {
1320 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityCreated(this,
1321 savedInstanceState);
1322 }
1323 }
1324 }
1325
1326 private void dispatchActivityPostCreated(@Nullable Bundle savedInstanceState) {
1327 Object[] callbacks = collectActivityLifecycleCallbacks();
1328 if (callbacks != null) {
1329 for (int i = 0; i < callbacks.length; i++) {
1330 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostCreated(this,
1331 savedInstanceState);
1332 }
1333 }
1334 getApplication().dispatchActivityPostCreated(this, savedInstanceState);
1335 }
1336
1337 private void dispatchActivityPreStarted() {
1338 getApplication().dispatchActivityPreStarted(this);
1339 Object[] callbacks = collectActivityLifecycleCallbacks();
1340 if (callbacks != null) {
1341 for (int i = 0; i < callbacks.length; i++) {
1342 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this);
1343 }
1344 }
1345 }
1346
1347 private void dispatchActivityStarted() {
1348 getApplication().dispatchActivityStarted(this);
1349 Object[] callbacks = collectActivityLifecycleCallbacks();
1350 if (callbacks != null) {
1351 for (int i = 0; i < callbacks.length; i++) {
1352 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStarted(this);
1353 }
1354 }
1355 }
1356
1357 private void dispatchActivityPostStarted() {
1358 Object[] callbacks = collectActivityLifecycleCallbacks();
1359 if (callbacks != null) {
1360 for (int i = 0; i < callbacks.length; i++) {
1361 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1362 .onActivityPostStarted(this);
1363 }
1364 }
1365 getApplication().dispatchActivityPostStarted(this);
1366 }
1367
1368 private void dispatchActivityPreResumed() {
1369 getApplication().dispatchActivityPreResumed(this);
1370 Object[] callbacks = collectActivityLifecycleCallbacks();
1371 if (callbacks != null) {
1372 for (int i = 0; i < callbacks.length; i++) {
1373 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreResumed(this);
1374 }
1375 }
1376 }
1377
1378 private void dispatchActivityResumed() {
1379 getApplication().dispatchActivityResumed(this);
1380 Object[] callbacks = collectActivityLifecycleCallbacks();
1381 if (callbacks != null) {
1382 for (int i = 0; i < callbacks.length; i++) {
1383 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityResumed(this);
1384 }
1385 }
1386 }
1387
1388 private void dispatchActivityPostResumed() {
1389 Object[] callbacks = collectActivityLifecycleCallbacks();
1390 if (callbacks != null) {
1391 for (int i = 0; i < callbacks.length; i++) {
1392 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostResumed(this);
1393 }
1394 }
1395 getApplication().dispatchActivityPostResumed(this);
1396 }
1397
1398 private void dispatchActivityPrePaused() {
1399 getApplication().dispatchActivityPrePaused(this);
1400 Object[] callbacks = collectActivityLifecycleCallbacks();
1401 if (callbacks != null) {
1402 for (int i = callbacks.length - 1; i >= 0; i--) {
1403 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPrePaused(this);
1404 }
1405 }
1406 }
1407
1408 private void dispatchActivityPaused() {
1409 Object[] callbacks = collectActivityLifecycleCallbacks();
1410 if (callbacks != null) {
1411 for (int i = callbacks.length - 1; i >= 0; i--) {
1412 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPaused(this);
1413 }
1414 }
1415 getApplication().dispatchActivityPaused(this);
1416 }
1417
1418 private void dispatchActivityPostPaused() {
1419 Object[] callbacks = collectActivityLifecycleCallbacks();
1420 if (callbacks != null) {
1421 for (int i = callbacks.length - 1; i >= 0; i--) {
1422 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPostPaused(this);
1423 }
1424 }
1425 getApplication().dispatchActivityPostPaused(this);
1426 }
1427
1428 private void dispatchActivityPreStopped() {
1429 getApplication().dispatchActivityPreStopped(this);
1430 Object[] callbacks = collectActivityLifecycleCallbacks();
1431 if (callbacks != null) {
1432 for (int i = callbacks.length - 1; i >= 0; i--) {
1433 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStopped(this);
1434 }
1435 }
1436 }
1437
1438 private void dispatchActivityStopped() {
1439 Object[] callbacks = collectActivityLifecycleCallbacks();
1440 if (callbacks != null) {
1441 for (int i = callbacks.length - 1; i >= 0; i--) {
1442 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityStopped(this);
1443 }
1444 }
1445 getApplication().dispatchActivityStopped(this);
1446 }
1447
1448 private void dispatchActivityPostStopped() {
1449 Object[] callbacks = collectActivityLifecycleCallbacks();
1450 if (callbacks != null) {
1451 for (int i = callbacks.length - 1; i >= 0; i--) {
1452 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1453 .onActivityPostStopped(this);
1454 }
1455 }
1456 getApplication().dispatchActivityPostStopped(this);
1457 }
1458
1459 private void dispatchActivityPreSaveInstanceState(@NonNull Bundle outState) {
1460 getApplication().dispatchActivityPreSaveInstanceState(this, outState);
1461 Object[] callbacks = collectActivityLifecycleCallbacks();
1462 if (callbacks != null) {
1463 for (int i = callbacks.length - 1; i >= 0; i--) {
1464 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1465 .onActivityPreSaveInstanceState(this, outState);
1466 }
1467 }
1468 }
1469
1470 private void dispatchActivitySaveInstanceState(@NonNull Bundle outState) {
1471 Object[] callbacks = collectActivityLifecycleCallbacks();
1472 if (callbacks != null) {
1473 for (int i = callbacks.length - 1; i >= 0; i--) {
1474 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1475 .onActivitySaveInstanceState(this, outState);
1476 }
1477 }
1478 getApplication().dispatchActivitySaveInstanceState(this, outState);
1479 }
1480
1481 private void dispatchActivityPostSaveInstanceState(@NonNull Bundle outState) {
1482 Object[] callbacks = collectActivityLifecycleCallbacks();
1483 if (callbacks != null) {
1484 for (int i = callbacks.length - 1; i >= 0; i--) {
1485 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1486 .onActivityPostSaveInstanceState(this, outState);
1487 }
1488 }
1489 getApplication().dispatchActivityPostSaveInstanceState(this, outState);
1490 }
1491
1492 private void dispatchActivityPreDestroyed() {
1493 getApplication().dispatchActivityPreDestroyed(this);
1494 Object[] callbacks = collectActivityLifecycleCallbacks();
1495 if (callbacks != null) {
1496 for (int i = callbacks.length - 1; i >= 0; i--) {
1497 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1498 .onActivityPreDestroyed(this);
1499 }
1500 }
1501 }
1502
1503 private void dispatchActivityDestroyed() {
1504 Object[] callbacks = collectActivityLifecycleCallbacks();
1505 if (callbacks != null) {
1506 for (int i = callbacks.length - 1; i >= 0; i--) {
1507 ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityDestroyed(this);
1508 }
1509 }
1510 getApplication().dispatchActivityDestroyed(this);
1511 }
1512
1513 private void dispatchActivityPostDestroyed() {
1514 Object[] callbacks = collectActivityLifecycleCallbacks();
1515 if (callbacks != null) {
1516 for (int i = callbacks.length - 1; i >= 0; i--) {
1517 ((Application.ActivityLifecycleCallbacks) callbacks[i])
1518 .onActivityPostDestroyed(this);
1519 }
1520 }
1521 getApplication().dispatchActivityPostDestroyed(this);
1522 }
1523
1524 private Object[] collectActivityLifecycleCallbacks() {
1525 Object[] callbacks = null;
1526 synchronized (mActivityLifecycleCallbacks) {
1527 if (mActivityLifecycleCallbacks.size() > 0) {
1528 callbacks = mActivityLifecycleCallbacks.toArray();
1529 }
1530 }
1531 return callbacks;
1532 }
1533
1534 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 * Called when the activity is starting. This is where most initialization
1536 * should go: calling {@link #setContentView(int)} to inflate the
1537 * activity's UI, using {@link #findViewById} to programmatically interact
1538 * with widgets in the UI, calling
1539 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
1540 * cursors for data being displayed, etc.
RoboErik55011652014-07-09 15:05:53 -07001541 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 * <p>You can call {@link #finish} from within this function, in
Bryce Lee476edc82018-03-12 10:06:23 -07001543 * which case onDestroy() will be immediately called after {@link #onCreate} without any of the
1544 * rest of the activity lifecycle ({@link #onStart}, {@link #onResume}, {@link #onPause}, etc)
1545 * executing.
RoboErik55011652014-07-09 15:05:53 -07001546 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 * <p><em>Derived classes must call through to the super class's
1548 * implementation of this method. If they do not, an exception will be
1549 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001550 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 * @param savedInstanceState If the activity is being re-initialized after
1552 * previously being shut down then this Bundle contains the data it most
1553 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
RoboErik55011652014-07-09 15:05:53 -07001554 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 * @see #onStart
1556 * @see #onSaveInstanceState
1557 * @see #onRestoreInstanceState
1558 * @see #onPostCreate
1559 */
Tor Norbye83c68962015-03-10 20:55:31 -07001560 @MainThread
Tor Norbyec615c6f2015-03-02 10:11:44 -08001561 @CallSuper
Tor Norbyed9273d62013-05-30 15:59:53 -07001562 protected void onCreate(@Nullable Bundle savedInstanceState) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001563 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
Bryce Lee39791592017-04-26 09:29:12 -07001564
Dianne Hackborn2707d602010-07-09 18:01:20 -07001565 if (mLastNonConfigurationInstances != null) {
Todd Kennedya5fc6f02015-04-14 18:22:54 -07001566 mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
Dianne Hackborn2707d602010-07-09 18:01:20 -07001567 }
Adam Powelldd8fab22012-03-22 17:47:27 -07001568 if (mActivityInfo.parentActivityName != null) {
1569 if (mActionBar == null) {
1570 mEnableDefaultActionBarUp = true;
1571 } else {
1572 mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
1573 }
1574 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001575 if (savedInstanceState != null) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001576 mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
Philip P. Moltmanne78c7712017-06-19 12:57:13 -07001577 mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
1578 View.LAST_APP_AUTOFILL_ID);
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07001579
1580 if (mAutoFillResetNeeded) {
1581 getAutofillManager().onCreate(savedInstanceState);
1582 }
1583
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001584 Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
1585 mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
1586 ? mLastNonConfigurationInstances.fragments : null);
1587 }
1588 mFragments.dispatchCreate();
Ian Lake8a88cd62018-09-28 13:25:20 -07001589 dispatchActivityCreated(savedInstanceState);
Dianne Hackborn20d94742014-05-29 18:35:45 -07001590 if (mVoiceInteractor != null) {
1591 mVoiceInteractor.attachActivity(this);
1592 }
Jorim Jaggi4d27b842017-08-17 17:22:26 +02001593 mRestoredFromBundle = savedInstanceState != null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 mCalled = true;
Felipe Lemee348dc32018-11-05 12:35:29 -08001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597
1598 /**
Craig Mautnera0026042014-04-23 11:45:37 -07001599 * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
Craig Mautner43e52ed2014-06-16 17:18:52 -07001600 * the attribute {@link android.R.attr#persistableMode} set to
1601 * <code>persistAcrossReboots</code>.
Craig Mautnera0026042014-04-23 11:45:37 -07001602 *
1603 * @param savedInstanceState if the activity is being re-initialized after
1604 * previously being shut down then this Bundle contains the data it most
1605 * recently supplied in {@link #onSaveInstanceState}.
1606 * <b><i>Note: Otherwise it is null.</i></b>
1607 * @param persistentState if the activity is being re-initialized after
1608 * previously being shut down or powered off then this Bundle contains the data it most
1609 * recently supplied to outPersistentState in {@link #onSaveInstanceState}.
1610 * <b><i>Note: Otherwise it is null.</i></b>
1611 *
1612 * @see #onCreate(android.os.Bundle)
1613 * @see #onStart
1614 * @see #onSaveInstanceState
1615 * @see #onRestoreInstanceState
1616 * @see #onPostCreate
1617 */
Craig Mautner7a629c22014-09-04 14:57:04 -07001618 public void onCreate(@Nullable Bundle savedInstanceState,
Craig Mautnera0026042014-04-23 11:45:37 -07001619 @Nullable PersistableBundle persistentState) {
1620 onCreate(savedInstanceState);
1621 }
1622
1623 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 * The hook for {@link ActivityThread} to restore the state of this activity.
1625 *
1626 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1627 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1628 *
1629 * @param savedInstanceState contains the saved state
1630 */
Jake Wharton63f4d892018-07-10 12:27:59 -04001631 final void performRestoreInstanceState(@NonNull Bundle savedInstanceState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 onRestoreInstanceState(savedInstanceState);
1633 restoreManagedDialogs(savedInstanceState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635
1636 /**
Craig Mautnera0026042014-04-23 11:45:37 -07001637 * The hook for {@link ActivityThread} to restore the state of this activity.
1638 *
1639 * Calls {@link #onSaveInstanceState(android.os.Bundle)} and
1640 * {@link #restoreManagedDialogs(android.os.Bundle)}.
1641 *
1642 * @param savedInstanceState contains the saved state
1643 * @param persistentState contains the persistable saved state
1644 */
Jake Wharton63f4d892018-07-10 12:27:59 -04001645 final void performRestoreInstanceState(@Nullable Bundle savedInstanceState,
1646 @Nullable PersistableBundle persistentState) {
Craig Mautnera0026042014-04-23 11:45:37 -07001647 onRestoreInstanceState(savedInstanceState, persistentState);
1648 if (savedInstanceState != null) {
1649 restoreManagedDialogs(savedInstanceState);
1650 }
1651 }
1652
1653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 * This method is called after {@link #onStart} when the activity is
1655 * being re-initialized from a previously saved state, given here in
Mike LeBeau305de9d2010-03-11 09:21:08 -08001656 * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 * to restore their state, but it is sometimes convenient to do it here
1658 * after all of the initialization has been done or to allow subclasses to
1659 * decide whether to use your default implementation. The default
1660 * implementation of this method performs a restore of any view state that
1661 * had previously been frozen by {@link #onSaveInstanceState}.
RoboErik55011652014-07-09 15:05:53 -07001662 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 * <p>This method is called between {@link #onStart} and
Kevin Hufnagle4fbcec12019-07-18 21:37:36 +00001664 * {@link #onPostCreate}. This method is called only when recreating
1665 * an activity; the method isn't invoked if {@link #onStart} is called for
1666 * any other reason.</p>
RoboErik55011652014-07-09 15:05:53 -07001667 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}.
RoboErik55011652014-07-09 15:05:53 -07001669 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 * @see #onCreate
1671 * @see #onPostCreate
1672 * @see #onResume
1673 * @see #onSaveInstanceState
1674 */
Jake Wharton63f4d892018-07-10 12:27:59 -04001675 protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if (mWindow != null) {
1677 Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
1678 if (windowState != null) {
1679 mWindow.restoreHierarchyState(windowState);
1680 }
1681 }
1682 }
Craig Mautnera0026042014-04-23 11:45:37 -07001683
1684 /**
1685 * This is the same as {@link #onRestoreInstanceState(Bundle)} but is called for activities
Craig Mautner43e52ed2014-06-16 17:18:52 -07001686 * created with the attribute {@link android.R.attr#persistableMode} set to
1687 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
1688 * came from the restored PersistableBundle first
Craig Mautnera0026042014-04-23 11:45:37 -07001689 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1690 *
1691 * <p>This method is called between {@link #onStart} and
1692 * {@link #onPostCreate}.
1693 *
1694 * <p>If this method is called {@link #onRestoreInstanceState(Bundle)} will not be called.
1695 *
Jake Wharton63f4d892018-07-10 12:27:59 -04001696 * <p>At least one of {@code savedInstanceState} or {@code persistentState} will not be null.
1697 *
1698 * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}
1699 * or null.
1700 * @param persistentState the data most recently supplied in {@link #onSaveInstanceState}
1701 * or null.
Craig Mautnera0026042014-04-23 11:45:37 -07001702 *
1703 * @see #onRestoreInstanceState(Bundle)
1704 * @see #onCreate
1705 * @see #onPostCreate
1706 * @see #onResume
1707 * @see #onSaveInstanceState
1708 */
Jake Wharton63f4d892018-07-10 12:27:59 -04001709 public void onRestoreInstanceState(@Nullable Bundle savedInstanceState,
1710 @Nullable PersistableBundle persistentState) {
Craig Mautnera0026042014-04-23 11:45:37 -07001711 if (savedInstanceState != null) {
1712 onRestoreInstanceState(savedInstanceState);
1713 }
1714 }
1715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 /**
1717 * Restore the state of any saved managed dialogs.
1718 *
1719 * @param savedInstanceState The bundle to restore from.
1720 */
1721 private void restoreManagedDialogs(Bundle savedInstanceState) {
1722 final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG);
1723 if (b == null) {
1724 return;
1725 }
1726
1727 final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY);
1728 final int numDialogs = ids.length;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001729 mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 for (int i = 0; i < numDialogs; i++) {
1731 final Integer dialogId = ids[i];
1732 Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
1733 if (dialogState != null) {
Romain Guye35c2352009-06-19 13:18:12 -07001734 // Calling onRestoreInstanceState() below will invoke dispatchOnCreate
1735 // so tell createDialog() not to do it, otherwise we get an exception
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001736 final ManagedDialog md = new ManagedDialog();
1737 md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId));
1738 md.mDialog = createDialog(dialogId, dialogState, md.mArgs);
1739 if (md.mDialog != null) {
1740 mManagedDialogs.put(dialogId, md);
1741 onPrepareDialog(dialogId, md.mDialog, md.mArgs);
1742 md.mDialog.onRestoreInstanceState(dialogState);
1743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 }
1745 }
1746 }
1747
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001748 private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) {
1749 final Dialog dialog = onCreateDialog(dialogId, args);
Romain Guy764d5332009-06-17 16:52:22 -07001750 if (dialog == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001751 return null;
Romain Guy764d5332009-06-17 16:52:22 -07001752 }
Romain Guy6de4aed2009-07-08 10:54:45 -07001753 dialog.dispatchOnCreate(state);
Romain Guy764d5332009-06-17 16:52:22 -07001754 return dialog;
1755 }
1756
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001757 private static String savedDialogKeyFor(int key) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 return SAVED_DIALOG_KEY_PREFIX + key;
1759 }
1760
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08001761 private static String savedDialogArgsKeyFor(int key) {
1762 return SAVED_DIALOG_ARGS_KEY_PREFIX + key;
1763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764
1765 /**
1766 * Called when activity start-up is complete (after {@link #onStart}
1767 * and {@link #onRestoreInstanceState} have been called). Applications will
1768 * generally not implement this method; it is intended for system
1769 * classes to do final initialization after application code has run.
RoboErik55011652014-07-09 15:05:53 -07001770 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 * <p><em>Derived classes must call through to the super class's
1772 * implementation of this method. If they do not, an exception will be
1773 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001774 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 * @param savedInstanceState If the activity is being re-initialized after
1776 * previously being shut down then this Bundle contains the data it most
1777 * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b>
1778 * @see #onCreate
1779 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001780 @CallSuper
Tor Norbyed9273d62013-05-30 15:59:53 -07001781 protected void onPostCreate(@Nullable Bundle savedInstanceState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 if (!isChild()) {
1783 mTitleReady = true;
1784 onTitleChanged(getTitle(), getTitleColor());
1785 }
Winsonb6403152016-02-23 13:32:09 -08001786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mCalled = true;
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001788
1789 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791
1792 /**
Craig Mautnera0026042014-04-23 11:45:37 -07001793 * This is the same as {@link #onPostCreate(Bundle)} but is called for activities
Craig Mautner43e52ed2014-06-16 17:18:52 -07001794 * created with the attribute {@link android.R.attr#persistableMode} set to
1795 * <code>persistAcrossReboots</code>.
Craig Mautnera0026042014-04-23 11:45:37 -07001796 *
1797 * @param savedInstanceState The data most recently supplied in {@link #onSaveInstanceState}
1798 * @param persistentState The data caming from the PersistableBundle first
1799 * saved in {@link #onSaveInstanceState(Bundle, PersistableBundle)}.
1800 *
1801 * @see #onCreate
1802 */
Craig Mautner7a629c22014-09-04 14:57:04 -07001803 public void onPostCreate(@Nullable Bundle savedInstanceState,
Craig Mautnera0026042014-04-23 11:45:37 -07001804 @Nullable PersistableBundle persistentState) {
1805 onPostCreate(savedInstanceState);
1806 }
1807
1808 /**
RoboErik55011652014-07-09 15:05:53 -07001809 * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when
1810 * the activity had been stopped, but is now again being displayed to the
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07001811 * user. It will usually be followed by {@link #onResume}. This is a good place to begin
1812 * drawing visual elements, running animations, etc.
1813 *
1814 * <p>You can call {@link #finish} from within this function, in
1815 * which case {@link #onStop} will be immediately called after {@link #onStart} without the
1816 * lifecycle transitions in-between ({@link #onResume}, {@link #onPause}, etc) executing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 *
1818 * <p><em>Derived classes must call through to the super class's
1819 * implementation of this method. If they do not, an exception will be
1820 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001821 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 * @see #onCreate
1823 * @see #onStop
1824 * @see #onResume
1825 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001826 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 protected void onStart() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001828 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 mCalled = true;
RoboErik55011652014-07-09 15:05:53 -07001830
Todd Kennedya5fc6f02015-04-14 18:22:54 -07001831 mFragments.doLoaderStart();
Narayan Kamathff5659f2017-02-02 13:31:33 +00001832
Ian Lake8a88cd62018-09-28 13:25:20 -07001833 dispatchActivityStarted();
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07001834
1835 if (mAutoFillResetNeeded) {
Dake Gu67decfa2017-12-27 11:48:08 -08001836 getAutofillManager().onVisibleForAutofill();
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07001837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
1840 /**
1841 * Called after {@link #onStop} when the current activity is being
1842 * re-displayed to the user (the user has navigated back to it). It will
1843 * be followed by {@link #onStart} and then {@link #onResume}.
1844 *
1845 * <p>For activities that are using raw {@link Cursor} objects (instead of
1846 * creating them through
1847 * {@link #managedQuery(android.net.Uri , String[], String, String[], String)},
1848 * this is usually the place
1849 * where the cursor should be requeried (because you had deactivated it in
1850 * {@link #onStop}.
RoboErik55011652014-07-09 15:05:53 -07001851 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 * <p><em>Derived classes must call through to the super class's
1853 * implementation of this method. If they do not, an exception will be
1854 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001855 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 * @see #onStop
1857 * @see #onStart
1858 * @see #onResume
1859 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001860 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 protected void onRestart() {
1862 mCalled = true;
1863 }
1864
1865 /**
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07001866 * Called when an {@link #onResume} is coming up, prior to other pre-resume callbacks
1867 * such as {@link #onNewIntent} and {@link #onActivityResult}. This is primarily intended
1868 * to give the activity a hint that its state is no longer saved -- it will generally
1869 * be called after {@link #onSaveInstanceState} and prior to the activity being
1870 * resumed/started again.
Sergey Vasilinets0de0eca2018-08-23 19:28:57 -07001871 *
1872 * @deprecated starting with {@link android.os.Build.VERSION_CODES#P} onSaveInstanceState is
1873 * called after {@link #onStop}, so this hint isn't accurate anymore: you should consider your
1874 * state not saved in between {@code onStart} and {@code onStop} callbacks inclusively.
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07001875 */
Sergey Vasilinets0de0eca2018-08-23 19:28:57 -07001876 @Deprecated
Dianne Hackborn6bdd3a12015-08-05 15:01:28 -07001877 public void onStateNotSaved() {
1878 }
1879
1880 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07001882 * {@link #onPause}, for your activity to start interacting with the user. This is an indicator
1883 * that the activity became active and ready to receive input. It is on top of an activity stack
1884 * and visible to user.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07001886 * <p>On platform versions prior to {@link android.os.Build.VERSION_CODES#Q} this is also a good
1887 * place to try to open exclusive-access devices or to get access to singleton resources.
1888 * Starting with {@link android.os.Build.VERSION_CODES#Q} there can be multiple resumed
1889 * activities in the system simultaneously, so {@link #onTopResumedActivityChanged(boolean)}
1890 * should be used for that purpose instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 *
1892 * <p><em>Derived classes must call through to the super class's
1893 * implementation of this method. If they do not, an exception will be
1894 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001895 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 * @see #onRestoreInstanceState
1897 * @see #onRestart
1898 * @see #onPostResume
1899 * @see #onPause
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07001900 * @see #onTopResumedActivityChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001902 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 protected void onResume() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001904 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onResume " + this);
Ian Lake8a88cd62018-09-28 13:25:20 -07001905 dispatchActivityResumed();
Sunny Goyal64643f62019-01-31 15:15:33 -08001906 mActivityTransitionState.onResume(this);
Felipe Lemece404982018-09-17 09:46:13 -07001907 enableAutofillCompatibilityIfNeeded();
Dake Gu67decfa2017-12-27 11:48:08 -08001908 if (mAutoFillResetNeeded) {
1909 if (!mAutoFillIgnoreFirstResumePause) {
1910 View focus = getCurrentFocus();
Ben Line55cd3e2018-12-07 20:26:37 +00001911 if (focus != null && focus.canNotifyAutofillEnterExitEvent()) {
Adam He5be0f152020-02-03 15:53:32 -08001912 // TODO(b/148815880): Bring up keyboard if resumed from inline authentication.
Dake Gu67decfa2017-12-27 11:48:08 -08001913 // TODO: in Activity killed/recreated case, i.e. SessionLifecycleTest#
1914 // testDatasetVisibleWhileAutofilledAppIsLifecycled: the View's initial
1915 // window visibility after recreation is INVISIBLE in onResume() and next frame
1916 // ViewRootImpl.performTraversals() changes window visibility to VISIBLE.
1917 // So we cannot call View.notifyEnterOrExited() which will do nothing
1918 // when View.isVisibleToUser() is false.
1919 getAutofillManager().notifyViewEntered(focus);
1920 }
1921 }
1922 }
Felipe Lemeb0da18f2019-02-22 15:10:02 -08001923
1924 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_RESUME);
1925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 mCalled = true;
1927 }
1928
1929 /**
1930 * Called when activity resume is complete (after {@link #onResume} has
1931 * been called). Applications will generally not implement this method;
1932 * it is intended for system classes to do final setup after application
1933 * resume code has run.
RoboErik55011652014-07-09 15:05:53 -07001934 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 * <p><em>Derived classes must call through to the super class's
1936 * implementation of this method. If they do not, an exception will be
1937 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07001938 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 * @see #onResume
1940 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08001941 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 protected void onPostResume() {
1943 final Window win = getWindow();
1944 if (win != null) win.makeActive();
Adam Powell50efbed2011-02-08 16:20:15 -08001945 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 mCalled = true;
1947 }
1948
Andrii Kuliand70cdb92019-01-08 15:03:50 -08001949 /**
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07001950 * Called when activity gets or loses the top resumed position in the system.
Andrii Kuliand70cdb92019-01-08 15:03:50 -08001951 *
1952 * <p>Starting with {@link android.os.Build.VERSION_CODES#Q} multiple activities can be resumed
1953 * at the same time in multi-window and multi-display modes. This callback should be used
1954 * instead of {@link #onResume()} as an indication that the activity can try to open
1955 * exclusive-access devices like camera.</p>
1956 *
1957 * <p>It will always be delivered after the activity was resumed and before it is paused. In
1958 * some cases it might be skipped and activity can go straight from {@link #onResume()} to
1959 * {@link #onPause()} without receiving the top resumed state.</p>
1960 *
1961 * @param isTopResumedActivity {@code true} if it's the topmost resumed activity in the system,
1962 * {@code false} otherwise. A call with this as {@code true} will
1963 * always be followed by another one with {@code false}.
1964 *
1965 * @see #onResume()
1966 * @see #onPause()
1967 * @see #onWindowFocusChanged(boolean)
1968 */
1969 public void onTopResumedActivityChanged(boolean isTopResumedActivity) {
1970 }
1971
Andrii Kulian86024012019-04-18 19:41:23 -07001972 final void performTopResumedActivityChanged(boolean isTopResumedActivity, String reason) {
1973 onTopResumedActivityChanged(isTopResumedActivity);
1974
Jeff Changd136e772019-11-05 20:33:52 +08001975 if (isTopResumedActivity) {
1976 EventLogTags.writeWmOnTopResumedGainedCalled(mIdent, getComponentName().getClassName(),
1977 reason);
1978 } else {
1979 EventLogTags.writeWmOnTopResumedLostCalled(mIdent, getComponentName().getClassName(),
1980 reason);
1981 }
Andrii Kulian86024012019-04-18 19:41:23 -07001982 }
1983
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001984 void setVoiceInteractor(IVoiceInteractor voiceInteractor) {
Amith Yamasanieeed06c2016-05-03 15:07:03 -07001985 if (mVoiceInteractor != null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07001986 final Request[] requests = mVoiceInteractor.getActiveRequests();
1987 if (requests != null) {
1988 for (Request activeRequest : mVoiceInteractor.getActiveRequests()) {
1989 activeRequest.cancel();
1990 activeRequest.clear();
1991 }
Amith Yamasanieeed06c2016-05-03 15:07:03 -07001992 }
1993 }
Amith Yamasani0af6fa72016-01-17 15:36:19 -08001994 if (voiceInteractor == null) {
1995 mVoiceInteractor = null;
1996 } else {
1997 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
1998 Looper.myLooper());
1999 }
2000 }
2001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 /**
Phil Weaver846cda932017-06-15 10:10:06 -07002003 * Gets the next autofill ID.
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002004 *
Phil Weaver846cda932017-06-15 10:10:06 -07002005 * <p>All IDs will be bigger than {@link View#LAST_APP_AUTOFILL_ID}. All IDs returned
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002006 * will be unique.
2007 *
2008 * @return A ID that is unique in the activity
2009 *
2010 * {@hide}
2011 */
Felipe Leme42b97932018-02-20 13:04:31 -08002012 @Override
Phil Weaver846cda932017-06-15 10:10:06 -07002013 public int getNextAutofillId() {
2014 if (mLastAutofillId == Integer.MAX_VALUE - 1) {
2015 mLastAutofillId = View.LAST_APP_AUTOFILL_ID;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002016 }
2017
Phil Weaver846cda932017-06-15 10:10:06 -07002018 mLastAutofillId++;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002019
Phil Weaver846cda932017-06-15 10:10:06 -07002020 return mLastAutofillId;
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002021 }
2022
2023 /**
Felipe Leme42b97932018-02-20 13:04:31 -08002024 * @hide
2025 */
2026 @Override
2027 public AutofillId autofillClientGetNextAutofillId() {
Felipe Leme305fd402018-09-11 18:20:42 +00002028 return new AutofillId(getNextAutofillId());
Felipe Leme42b97932018-02-20 13:04:31 -08002029 }
2030
2031 /**
Dianne Hackborn91097de2014-04-04 18:02:06 -07002032 * Check whether this activity is running as part of a voice interaction with the user.
2033 * If true, it should perform its interaction with the user through the
2034 * {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
2035 */
2036 public boolean isVoiceInteraction() {
2037 return mVoiceInteractor != null;
2038 }
2039
2040 /**
Charles Cheneba0a202019-09-17 21:02:07 +08002041 * Like {@link #isVoiceInteraction}, but only returns {@code true} if this is also the root
2042 * of a voice interaction. That is, returns {@code true} if this activity was directly
Dianne Hackbornfb81d092015-08-03 17:14:46 -07002043 * started by the voice interaction service as the initiation of a voice interaction.
2044 * Otherwise, for example if it was started by another activity while under voice
Charles Cheneba0a202019-09-17 21:02:07 +08002045 * interaction, returns {@code false}.
2046 * If the activity {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode} is
2047 * {@code singleTask}, it forces the activity to launch in a new task, separate from the one
2048 * that started it. Therefore, there is no longer a relationship between them, and
2049 * {@link #isVoiceInteractionRoot()} return {@code false} in this case.
Dianne Hackbornfb81d092015-08-03 17:14:46 -07002050 */
2051 public boolean isVoiceInteractionRoot() {
2052 try {
2053 return mVoiceInteractor != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 && ActivityTaskManager.getService().isRootVoiceInteraction(mToken);
Dianne Hackbornfb81d092015-08-03 17:14:46 -07002055 } catch (RemoteException e) {
2056 }
2057 return false;
2058 }
2059
2060 /**
Dianne Hackborn91097de2014-04-04 18:02:06 -07002061 * Retrieve the active {@link VoiceInteractor} that the user is going through to
2062 * interact with this activity.
2063 */
2064 public VoiceInteractor getVoiceInteractor() {
2065 return mVoiceInteractor;
2066 }
2067
2068 /**
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002069 * Queries whether the currently enabled voice interaction service supports returning
2070 * a voice interactor for use by the activity. This is valid only for the duration of the
2071 * activity.
2072 *
2073 * @return whether the current voice interaction service supports local voice interaction
2074 */
2075 public boolean isLocalVoiceInteractionSupported() {
2076 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 return ActivityTaskManager.getService().supportsLocalVoiceInteraction();
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002078 } catch (RemoteException re) {
2079 }
2080 return false;
2081 }
2082
2083 /**
2084 * Starts a local voice interaction session. When ready,
2085 * {@link #onLocalVoiceInteractionStarted()} is called. You can pass a bundle of private options
2086 * to the registered voice interaction service.
2087 * @param privateOptions a Bundle of private arguments to the current voice interaction service
2088 */
2089 public void startLocalVoiceInteraction(Bundle privateOptions) {
2090 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 ActivityTaskManager.getService().startLocalVoiceInteraction(mToken, privateOptions);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002092 } catch (RemoteException re) {
2093 }
2094 }
2095
2096 /**
2097 * Callback to indicate that {@link #startLocalVoiceInteraction(Bundle)} has resulted in a
2098 * voice interaction session being started. You can now retrieve a voice interactor using
2099 * {@link #getVoiceInteractor()}.
2100 */
2101 public void onLocalVoiceInteractionStarted() {
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002102 }
2103
2104 /**
Amith Yamasanid8d967e2016-04-08 09:57:01 -07002105 * Callback to indicate that the local voice interaction has stopped either
2106 * because it was requested through a call to {@link #stopLocalVoiceInteraction()}
2107 * or because it was canceled by the user. The previously acquired {@link VoiceInteractor}
2108 * is no longer valid after this.
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002109 */
2110 public void onLocalVoiceInteractionStopped() {
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002111 }
2112
2113 /**
2114 * Request to terminate the current voice interaction that was previously started
Amith Yamasanid8d967e2016-04-08 09:57:01 -07002115 * using {@link #startLocalVoiceInteraction(Bundle)}. When the interaction is
2116 * terminated, {@link #onLocalVoiceInteractionStopped()} will be called.
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002117 */
2118 public void stopLocalVoiceInteraction() {
2119 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002120 ActivityTaskManager.getService().stopLocalVoiceInteraction(mToken);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08002121 } catch (RemoteException re) {
2122 }
2123 }
2124
2125 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 * This is called for activities that set launchMode to "singleTop" in
2127 * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
2128 * flag when calling {@link #startActivity}. In either case, when the
2129 * activity is re-launched while at the top of the activity stack instead
2130 * of a new instance of the activity being started, onNewIntent() will be
2131 * called on the existing instance with the Intent that was used to
RoboErik55011652014-07-09 15:05:53 -07002132 * re-launch it.
2133 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002134 * <p>An activity can never receive a new intent in the resumed state. You can count on
2135 * {@link #onResume} being called after this method, though not necessarily immediately after
2136 * the completion this callback. If the activity was resumed, it will be paused and new intent
2137 * will be delivered, followed by {@link #onResume}. If the activity wasn't in the resumed
2138 * state, then new intent can be delivered immediately, with {@link #onResume()} called
2139 * sometime later when activity becomes active again.
RoboErik55011652014-07-09 15:05:53 -07002140 *
2141 * <p>Note that {@link #getIntent} still returns the original Intent. You
2142 * can use {@link #setIntent} to update it to this new Intent.
2143 *
2144 * @param intent The new intent that was started for the activity.
2145 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 * @see #getIntent
RoboErik55011652014-07-09 15:05:53 -07002147 * @see #setIntent
2148 * @see #onResume
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 */
2150 protected void onNewIntent(Intent intent) {
2151 }
2152
2153 /**
2154 * The hook for {@link ActivityThread} to save the state of this activity.
2155 *
2156 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
2157 * and {@link #saveManagedDialogs(android.os.Bundle)}.
2158 *
2159 * @param outState The bundle to save the state to.
2160 */
Jake Wharton63f4d892018-07-10 12:27:59 -04002161 final void performSaveInstanceState(@NonNull Bundle outState) {
Ian Lake8a88cd62018-09-28 13:25:20 -07002162 dispatchActivityPreSaveInstanceState(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 onSaveInstanceState(outState);
2164 saveManagedDialogs(outState);
George Mount62ab9b72014-05-02 13:51:17 -07002165 mActivityTransitionState.saveState(outState);
Svetoslavffb32b12015-10-15 16:54:00 -07002166 storeHasCurrentPermissionRequest(outState);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002167 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
Ian Lake8a88cd62018-09-28 13:25:20 -07002168 dispatchActivityPostSaveInstanceState(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170
2171 /**
Craig Mautnera0026042014-04-23 11:45:37 -07002172 * The hook for {@link ActivityThread} to save the state of this activity.
2173 *
2174 * Calls {@link #onSaveInstanceState(android.os.Bundle)}
2175 * and {@link #saveManagedDialogs(android.os.Bundle)}.
2176 *
2177 * @param outState The bundle to save the state to.
2178 * @param outPersistentState The bundle to save persistent state to.
2179 */
Jake Wharton63f4d892018-07-10 12:27:59 -04002180 final void performSaveInstanceState(@NonNull Bundle outState,
2181 @NonNull PersistableBundle outPersistentState) {
Ian Lake8a88cd62018-09-28 13:25:20 -07002182 dispatchActivityPreSaveInstanceState(outState);
Craig Mautnera0026042014-04-23 11:45:37 -07002183 onSaveInstanceState(outState, outPersistentState);
2184 saveManagedDialogs(outState);
Svetoslavffb32b12015-10-15 16:54:00 -07002185 storeHasCurrentPermissionRequest(outState);
Craig Mautnera0026042014-04-23 11:45:37 -07002186 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState +
2187 ", " + outPersistentState);
Ian Lake8a88cd62018-09-28 13:25:20 -07002188 dispatchActivityPostSaveInstanceState(outState);
Craig Mautnera0026042014-04-23 11:45:37 -07002189 }
2190
2191 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 * Called to retrieve per-instance state from an activity before being killed
2193 * so that the state can be restored in {@link #onCreate} or
2194 * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
2195 * will be passed to both).
2196 *
2197 * <p>This method is called before an activity may be killed so that when it
2198 * comes back some time in the future it can restore its state. For example,
2199 * if activity B is launched in front of activity A, and at some point activity
2200 * A is killed to reclaim resources, activity A will have a chance to save the
2201 * current state of its user interface via this method so that when the user
2202 * returns to activity A, the state of the user interface can be restored
2203 * via {@link #onCreate} or {@link #onRestoreInstanceState}.
2204 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002205 * <p>Do not confuse this method with activity lifecycle callbacks such as {@link #onPause},
2206 * which is always called when the user no longer actively interacts with an activity, or
2207 * {@link #onStop} which is called when activity becomes invisible. One example of when
2208 * {@link #onPause} and {@link #onStop} is called and not this method is when a user navigates
2209 * back from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
2210 * on B because that particular instance will never be restored,
2211 * so the system avoids calling it. An example when {@link #onPause} is called and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
2213 * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
2214 * killed during the lifetime of B since the state of the user interface of
2215 * A will stay intact.
2216 *
2217 * <p>The default implementation takes care of most of the UI per-instance
2218 * state for you by calling {@link android.view.View#onSaveInstanceState()} on each
2219 * view in the hierarchy that has an id, and by saving the id of the currently
2220 * focused view (all of which is restored by the default implementation of
2221 * {@link #onRestoreInstanceState}). If you override this method to save additional
2222 * information not captured by each individual view, you will likely want to
2223 * call through to the default implementation, otherwise be prepared to save
2224 * all of the state of each view yourself.
2225 *
Andrii Kulian391161f2018-01-29 10:50:02 -08002226 * <p>If called, this method will occur after {@link #onStop} for applications
2227 * targeting platforms starting with {@link android.os.Build.VERSION_CODES#P}.
2228 * For applications targeting earlier platform versions this method will occur
2229 * before {@link #onStop} and there are no guarantees about whether it will
2230 * occur before or after {@link #onPause}.
RoboErik55011652014-07-09 15:05:53 -07002231 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 * @param outState Bundle in which to place your saved state.
RoboErik55011652014-07-09 15:05:53 -07002233 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 * @see #onCreate
2235 * @see #onRestoreInstanceState
2236 * @see #onPause
2237 */
Jake Wharton63f4d892018-07-10 12:27:59 -04002238 protected void onSaveInstanceState(@NonNull Bundle outState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002240
Phil Weaver846cda932017-06-15 10:10:06 -07002241 outState.putInt(LAST_AUTOFILL_ID, mLastAutofillId);
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07002242 Parcelable p = mFragments.saveAllState();
2243 if (p != null) {
2244 outState.putParcelable(FRAGMENTS_TAG, p);
2245 }
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07002246 if (mAutoFillResetNeeded) {
Philip P. Moltmanneab62ba2017-03-20 10:55:43 -07002247 outState.putBoolean(AUTOFILL_RESET_NEEDED, true);
2248 getAutofillManager().onSaveInstanceState(outState);
Philip P. Moltmannb42d1332017-03-27 09:55:30 -07002249 }
Ian Lake8a88cd62018-09-28 13:25:20 -07002250 dispatchActivitySaveInstanceState(outState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 }
2252
2253 /**
Craig Mautnera0026042014-04-23 11:45:37 -07002254 * This is the same as {@link #onSaveInstanceState} but is called for activities
Craig Mautner43e52ed2014-06-16 17:18:52 -07002255 * created with the attribute {@link android.R.attr#persistableMode} set to
2256 * <code>persistAcrossReboots</code>. The {@link android.os.PersistableBundle} passed
2257 * in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
2258 * the first time that this activity is restarted following the next device reboot.
Craig Mautnera0026042014-04-23 11:45:37 -07002259 *
2260 * @param outState Bundle in which to place your saved state.
2261 * @param outPersistentState State which will be saved across reboots.
2262 *
2263 * @see #onSaveInstanceState(Bundle)
2264 * @see #onCreate
2265 * @see #onRestoreInstanceState(Bundle, PersistableBundle)
2266 * @see #onPause
2267 */
Jake Wharton63f4d892018-07-10 12:27:59 -04002268 public void onSaveInstanceState(@NonNull Bundle outState,
2269 @NonNull PersistableBundle outPersistentState) {
Craig Mautnera0026042014-04-23 11:45:37 -07002270 onSaveInstanceState(outState);
2271 }
2272
2273 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 * Save the state of any managed dialogs.
2275 *
2276 * @param outState place to store the saved state.
2277 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002278 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 private void saveManagedDialogs(Bundle outState) {
2280 if (mManagedDialogs == null) {
2281 return;
2282 }
2283
2284 final int numDialogs = mManagedDialogs.size();
2285 if (numDialogs == 0) {
2286 return;
2287 }
2288
2289 Bundle dialogState = new Bundle();
2290
2291 int[] ids = new int[mManagedDialogs.size()];
2292
2293 // save each dialog's bundle, gather the ids
2294 for (int i = 0; i < numDialogs; i++) {
2295 final int key = mManagedDialogs.keyAt(i);
2296 ids[i] = key;
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002297 final ManagedDialog md = mManagedDialogs.valueAt(i);
2298 dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState());
2299 if (md.mArgs != null) {
2300 dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs);
2301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 }
2303
2304 dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids);
2305 outState.putBundle(SAVED_DIALOGS_TAG, dialogState);
2306 }
2307
2308
2309 /**
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002310 * Called as part of the activity lifecycle when the user no longer actively interacts with the
2311 * activity, but it is still visible on screen. The counterpart to {@link #onResume}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 *
2313 * <p>When activity B is launched in front of activity A, this callback will
2314 * be invoked on A. B will not be created until A's {@link #onPause} returns,
2315 * so be sure to not do anything lengthy here.
2316 *
2317 * <p>This callback is mostly used for saving any persistent state the
2318 * activity is editing, to present a "edit in place" model to the user and
2319 * making sure nothing is lost if there are not enough resources to start
2320 * the new activity without first killing this one. This is also a good
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002321 * place to stop things that consume a noticeable amount of CPU in order to
2322 * make the switch to the next activity as fast as possible.
RoboErik55011652014-07-09 15:05:53 -07002323 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002324 * <p>On platform versions prior to {@link android.os.Build.VERSION_CODES#Q} this is also a good
2325 * place to try to close exclusive-access devices or to release access to singleton resources.
2326 * Starting with {@link android.os.Build.VERSION_CODES#Q} there can be multiple resumed
2327 * activities in the system at the same time, so {@link #onTopResumedActivityChanged(boolean)}
2328 * should be used for that purpose instead.
RoboErik55011652014-07-09 15:05:53 -07002329 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002330 * <p>If an activity is launched on top, after receiving this call you will usually receive a
2331 * following call to {@link #onStop} (after the next activity has been resumed and displayed
2332 * above). However in some cases there will be a direct call back to {@link #onResume} without
2333 * going through the stopped state. An activity can also rest in paused state in some cases when
2334 * in multi-window mode, still visible to user.
RoboErik55011652014-07-09 15:05:53 -07002335 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 * <p><em>Derived classes must call through to the super class's
2337 * implementation of this method. If they do not, an exception will be
2338 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07002339 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 * @see #onResume
2341 * @see #onSaveInstanceState
2342 * @see #onStop
2343 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08002344 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 protected void onPause() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002346 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
Ian Lake8a88cd62018-09-28 13:25:20 -07002347 dispatchActivityPaused();
Dake Gu67decfa2017-12-27 11:48:08 -08002348 if (mAutoFillResetNeeded) {
2349 if (!mAutoFillIgnoreFirstResumePause) {
2350 if (DEBUG_LIFECYCLE) Slog.v(TAG, "autofill notifyViewExited " + this);
2351 View focus = getCurrentFocus();
2352 if (focus != null && focus.canNotifyAutofillEnterExitEvent()) {
2353 getAutofillManager().notifyViewExited(focus);
2354 }
2355 } else {
2356 // reset after first pause()
2357 if (DEBUG_LIFECYCLE) Slog.v(TAG, "autofill got first pause " + this);
2358 mAutoFillIgnoreFirstResumePause = false;
2359 }
2360 }
Felipe Lemeb0da18f2019-02-22 15:10:02 -08002361
2362 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_PAUSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 mCalled = true;
2364 }
2365
2366 /**
2367 * Called as part of the activity lifecycle when an activity is about to go
2368 * into the background as the result of user choice. For example, when the
2369 * user presses the Home key, {@link #onUserLeaveHint} will be called, but
2370 * when an incoming phone call causes the in-call Activity to be automatically
2371 * brought to the foreground, {@link #onUserLeaveHint} will not be called on
2372 * the activity being interrupted. In cases when it is invoked, this method
2373 * is called right before the activity's {@link #onPause} callback.
RoboErik55011652014-07-09 15:05:53 -07002374 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 * <p>This callback and {@link #onUserInteraction} are intended to help
2376 * activities manage status bar notifications intelligently; specifically,
Wale Ogunwale578b3bd2018-02-13 08:30:53 -08002377 * for helping activities determine the proper time to cancel a notification.
RoboErik55011652014-07-09 15:05:53 -07002378 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 * @see #onUserInteraction()
Louis Changc2e193a2019-01-09 15:33:57 +08002380 * @see android.content.Intent#FLAG_ACTIVITY_NO_USER_ACTION
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 */
2382 protected void onUserLeaveHint() {
2383 }
RoboErik55011652014-07-09 15:05:53 -07002384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 /**
Wale Ogunwale578b3bd2018-02-13 08:30:53 -08002386 * @deprecated Method doesn't do anything and will be removed in the future.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 */
Wale Ogunwale578b3bd2018-02-13 08:30:53 -08002388 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08002390 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392
2393 /**
2394 * Generate a new description for this activity. This method is called
Wale Ogunwale578b3bd2018-02-13 08:30:53 -08002395 * before stopping the activity and can, if desired, return some textual
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 * description of its current state to be displayed to the user.
RoboErik55011652014-07-09 15:05:53 -07002397 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 * <p>The default implementation returns null, which will cause you to
2399 * inherit the description from the previous activity. If all activities
2400 * return null, generally the label of the top activity will be used as the
2401 * description.
RoboErik55011652014-07-09 15:05:53 -07002402 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 * @return A description of what the user is doing. It should be short and
2404 * sweet (only a few words).
RoboErik55011652014-07-09 15:05:53 -07002405 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 * @see #onSaveInstanceState
Wale Ogunwale578b3bd2018-02-13 08:30:53 -08002407 * @see #onStop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 */
Tor Norbyed9273d62013-05-30 15:59:53 -07002409 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 public CharSequence onCreateDescription() {
2411 return null;
2412 }
2413
2414 /**
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002415 * This is called when the user is requesting an assist, to build a full
2416 * {@link Intent#ACTION_ASSIST} Intent with all of the context of the current
2417 * application. You can override this method to place into the bundle anything
2418 * you would like to appear in the {@link Intent#EXTRA_ASSIST_CONTEXT} part
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07002419 * of the assist Intent.
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002420 *
2421 * <p>This function will be called after any global assist callbacks that had
Ying Wang4e0eb222013-04-18 20:39:48 -07002422 * been registered with {@link Application#registerOnProvideAssistDataListener
2423 * Application.registerOnProvideAssistDataListener}.
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002424 */
2425 public void onProvideAssistData(Bundle data) {
Dianne Hackborna83ce1d2015-03-11 15:16:13 -07002426 }
2427
2428 /**
2429 * This is called when the user is requesting an assist, to provide references
2430 * to content related to the current activity. Before being called, the
2431 * {@code outContent} Intent is filled with the base Intent of the activity (the Intent
2432 * returned by {@link #getIntent()}). The Intent's extras are stripped of any types
2433 * that are not valid for {@link PersistableBundle} or non-framework Parcelables, and
2434 * the flags {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} and
2435 * {@link Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION} are cleared from the Intent.
2436 *
2437 * <p>Custom implementation may adjust the content intent to better reflect the top-level
2438 * context of the activity, and fill in its ClipData with additional content of
2439 * interest that the user is currently viewing. For example, an image gallery application
2440 * that has launched in to an activity allowing the user to swipe through pictures should
2441 * modify the intent to reference the current image they are looking it; such an
2442 * application when showing a list of pictures should add a ClipData that has
2443 * references to all of the pictures currently visible on screen.</p>
2444 *
2445 * @param outContent The assist content to return.
2446 */
2447 public void onProvideAssistContent(AssistContent outContent) {
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002448 }
2449
Clara Bayarrieb3c2d32016-04-01 14:37:32 +01002450 /**
Sunny Goyald40c3452019-03-20 12:46:55 -07002451 * Returns the list of direct actions supported by the app.
2452 *
2453 * <p>You should return the list of actions that could be executed in the
2454 * current context, which is in the current state of the app. If the actions
2455 * that could be executed by the app changes you should report that via
2456 * calling {@link VoiceInteractor#notifyDirectActionsChanged()}.
2457 *
2458 * <p>To get the voice interactor you need to call {@link #getVoiceInteractor()}
Andrew Solovay7ad21702019-06-06 15:10:43 -07002459 * which would return non <code>null</code> only if there is an ongoing voice
Sunny Goyald40c3452019-03-20 12:46:55 -07002460 * interaction session. You an also detect when the voice interactor is no
2461 * longer valid because the voice interaction session that is backing is finished
2462 * by calling {@link VoiceInteractor#registerOnDestroyedCallback(Executor, Runnable)}.
2463 *
2464 * <p>This method will be called only after {@link #onStart()} is being called and
2465 * before {@link #onStop()} is being called.
2466 *
Svet Ganov3b6be082019-04-28 10:21:01 -07002467 * <p>You should pass to the callback the currently supported direct actions which
Andrew Solovay7ad21702019-06-06 15:10:43 -07002468 * cannot be <code>null</code> or contain <code>null</code> elements.
Svet Ganov3b6be082019-04-28 10:21:01 -07002469 *
2470 * <p>You should return the action list as soon as possible to ensure the consumer,
2471 * for example the assistant, is as responsive as possible which would improve user
2472 * experience of your app.
2473 *
2474 * @param cancellationSignal A signal to cancel the operation in progress.
2475 * @param callback The callback to send the action list. The actions list cannot
Svet Ganov07e5fb22019-04-30 11:07:09 -07002476 * contain <code>null</code> elements. You can call this on any thread.
Sunny Goyald40c3452019-03-20 12:46:55 -07002477 */
Svet Ganov3b6be082019-04-28 10:21:01 -07002478 public void onGetDirectActions(@NonNull CancellationSignal cancellationSignal,
2479 @NonNull Consumer<List<DirectAction>> callback) {
2480 callback.accept(Collections.emptyList());
Sunny Goyald40c3452019-03-20 12:46:55 -07002481 }
2482
2483 /**
2484 * This is called to perform an action previously defined by the app.
2485 * Apps also have access to {@link #getVoiceInteractor()} to follow up on the action.
2486 *
Svet Ganov07e5fb22019-04-30 11:07:09 -07002487 * @param actionId The ID for the action you previously reported via
2488 * {@link #onGetDirectActions(CancellationSignal, Consumer)}.
2489 * @param arguments Any additional arguments provided by the caller that are
2490 * specific to the given action.
Svet Ganov3b6be082019-04-28 10:21:01 -07002491 * @param cancellationSignal A signal to cancel the operation in progress.
Svet Ganov07e5fb22019-04-30 11:07:09 -07002492 * @param resultListener The callback to provide the result back to the caller.
2493 * You can call this on any thread. The result bundle is action specific.
Sunny Goyald40c3452019-03-20 12:46:55 -07002494 *
Svet Ganov3b6be082019-04-28 10:21:01 -07002495 * @see #onGetDirectActions(CancellationSignal, Consumer)
Sunny Goyald40c3452019-03-20 12:46:55 -07002496 */
2497 public void onPerformDirectAction(@NonNull String actionId,
Svet Ganov3b6be082019-04-28 10:21:01 -07002498 @NonNull Bundle arguments, @NonNull CancellationSignal cancellationSignal,
Sunny Goyald40c3452019-03-20 12:46:55 -07002499 @NonNull Consumer<Bundle> resultListener) { }
2500
2501 /**
Clara Bayarriab591ba2016-05-16 17:48:16 +01002502 * Request the Keyboard Shortcuts screen to show up. This will trigger
Clara Bayarrieb3c2d32016-04-01 14:37:32 +01002503 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
2504 */
Clara Bayarriac6f0342016-05-16 14:15:14 +01002505 public final void requestShowKeyboardShortcuts() {
Winson Chungf2b41772019-11-06 15:00:48 -08002506 final ComponentName sysuiComponent = ComponentName.unflattenFromString(
2507 getResources().getString(
2508 com.android.internal.R.string.config_systemUIServiceComponent));
Clara Bayarrieb3c2d32016-04-01 14:37:32 +01002509 Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
Winson Chungf2b41772019-11-06 15:00:48 -08002510 intent.setPackage(sysuiComponent.getPackageName());
Nicholas Sauer28348ed742019-02-15 11:58:32 -08002511 sendBroadcastAsUser(intent, Process.myUserHandle());
Andrei Stingaceanu0bf096f2016-04-14 18:11:57 +01002512 }
2513
2514 /**
2515 * Dismiss the Keyboard Shortcuts screen.
2516 */
2517 public final void dismissKeyboardShortcutsHelper() {
Winson Chungf2b41772019-11-06 15:00:48 -08002518 final ComponentName sysuiComponent = ComponentName.unflattenFromString(
2519 getResources().getString(
2520 com.android.internal.R.string.config_systemUIServiceComponent));
Andrei Stingaceanu0bf096f2016-04-14 18:11:57 +01002521 Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
Winson Chungf2b41772019-11-06 15:00:48 -08002522 intent.setPackage(sysuiComponent.getPackageName());
Nicholas Sauer28348ed742019-02-15 11:58:32 -08002523 sendBroadcastAsUser(intent, Process.myUserHandle());
Clara Bayarrieb3c2d32016-04-01 14:37:32 +01002524 }
2525
Clara Bayarri75e09792015-07-29 16:20:40 +01002526 @Override
Clara Bayarrifcd7e802016-03-10 12:58:18 +00002527 public void onProvideKeyboardShortcuts(
2528 List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
Clara Bayarri75e09792015-07-29 16:20:40 +01002529 if (menu == null) {
2530 return;
2531 }
2532 KeyboardShortcutGroup group = null;
2533 int menuSize = menu.size();
2534 for (int i = 0; i < menuSize; ++i) {
2535 final MenuItem item = menu.getItem(i);
2536 final CharSequence title = item.getTitle();
2537 final char alphaShortcut = item.getAlphabeticShortcut();
Peeyush Agarwale631e322016-10-19 11:41:42 +01002538 final int alphaModifiers = item.getAlphabeticModifiers();
Clara Bayarri75e09792015-07-29 16:20:40 +01002539 if (title != null && alphaShortcut != MIN_VALUE) {
2540 if (group == null) {
Clara Bayarriada88b32016-02-02 18:08:01 +00002541 final int resource = mApplication.getApplicationInfo().labelRes;
2542 group = new KeyboardShortcutGroup(resource != 0 ? getString(resource) : null);
Clara Bayarri75e09792015-07-29 16:20:40 +01002543 }
2544 group.addItem(new KeyboardShortcutInfo(
Peeyush Agarwale631e322016-10-19 11:41:42 +01002545 title, alphaShortcut, alphaModifiers));
Clara Bayarri75e09792015-07-29 16:20:40 +01002546 }
2547 }
2548 if (group != null) {
2549 data.add(group);
2550 }
2551 }
2552
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08002553 /**
Dianne Hackborn17f69352015-07-17 18:04:14 -07002554 * Ask to have the current assistant shown to the user. This only works if the calling
2555 * activity is the current foreground activity. It is the same as calling
2556 * {@link android.service.voice.VoiceInteractionService#showSession
2557 * VoiceInteractionService.showSession} and requesting all of the possible context.
2558 * The receiver will always see
2559 * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
2560 * @return Returns true if the assistant was successfully invoked, else false. For example
2561 * false will be returned if the caller is not the current top activity.
2562 */
2563 public boolean showAssist(Bundle args) {
2564 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002565 return ActivityTaskManager.getService().showAssistFromActivity(mToken, args);
Dianne Hackborn17f69352015-07-17 18:04:14 -07002566 } catch (RemoteException e) {
2567 }
2568 return false;
2569 }
2570
2571 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 * Called when you are no longer visible to the user. You will next
2573 * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07002574 * depending on later user activity. This is a good place to stop
2575 * refreshing UI, running animations and other visual things.
RoboErik55011652014-07-09 15:05:53 -07002576 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 * <p><em>Derived classes must call through to the super class's
2578 * implementation of this method. If they do not, an exception will be
2579 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07002580 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 * @see #onRestart
2582 * @see #onResume
2583 * @see #onSaveInstanceState
2584 * @see #onDestroy
2585 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08002586 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 protected void onStop() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002588 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
Adam Powell50efbed2011-02-08 16:20:15 -08002589 if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
George Mount62ab9b72014-05-02 13:51:17 -07002590 mActivityTransitionState.onStop();
Ian Lake8a88cd62018-09-28 13:25:20 -07002591 dispatchActivityStopped();
Craig Mautner5eda9b32013-07-02 11:58:16 -07002592 mTranslucentCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 mCalled = true;
Felipe Lemec24a56a2017-08-03 14:27:57 -07002594
Dake Gu67decfa2017-12-27 11:48:08 -08002595 if (mAutoFillResetNeeded) {
TYM Tsai88398352020-01-14 19:49:05 +08002596 // If stopped without changing the configurations, the response should expire.
2597 getAutofillManager().onInvisibleForAutofill(!mChangingConfigurations);
TYM Tsai8af721d2019-07-24 17:11:59 +08002598 } else if (mIntent != null
2599 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)
2600 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) {
2601 restoreAutofillSaveUi();
Felipe Lemebab851c2017-02-03 18:45:08 -08002602 }
chaviwfeb2e1e2018-12-19 17:24:11 -08002603 mEnterAnimationComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605
2606 /**
2607 * Perform any final cleanup before an activity is destroyed. This can
2608 * happen either because the activity is finishing (someone called
koprivafdb0bff2018-09-29 15:22:41 -07002609 * {@link #finish} on it), or because the system is temporarily destroying
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 * this instance of the activity to save space. You can distinguish
2611 * between these two scenarios with the {@link #isFinishing} method.
RoboErik55011652014-07-09 15:05:53 -07002612 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 * <p><em>Note: do not count on this method being called as a place for
2614 * saving data! For example, if an activity is editing data in a content
2615 * provider, those edits should be committed in either {@link #onPause} or
2616 * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to
2617 * free resources like threads that are associated with an activity, so
2618 * that a destroyed activity does not leave such things around while the
2619 * rest of its application is still running. There are situations where
2620 * the system will simply kill the activity's hosting process without
2621 * calling this method (or any others) in it, so it should not be used to
2622 * do things that are intended to remain around after the process goes
2623 * away.
RoboErik55011652014-07-09 15:05:53 -07002624 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 * <p><em>Derived classes must call through to the super class's
2626 * implementation of this method. If they do not, an exception will be
2627 * thrown.</em></p>
RoboErik55011652014-07-09 15:05:53 -07002628 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 * @see #onPause
2630 * @see #onStop
2631 * @see #finish
2632 * @see #isFinishing
2633 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08002634 @CallSuper
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 protected void onDestroy() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002636 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 mCalled = true;
2638
lpeterc054c5d2019-09-11 18:14:56 +08002639 if (isFinishing() && mAutoFillResetNeeded) {
2640 getAutofillManager().onActivityFinishing();
2641 }
2642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 // dismiss any dialogs we are managing.
2644 if (mManagedDialogs != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 final int numDialogs = mManagedDialogs.size();
2646 for (int i = 0; i < numDialogs; i++) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002647 final ManagedDialog md = mManagedDialogs.valueAt(i);
2648 if (md.mDialog.isShowing()) {
2649 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08002652 mManagedDialogs = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654
2655 // close any cursors we are managing.
Makoto Onuki2f6a0182010-02-22 13:26:59 -08002656 synchronized (mManagedCursors) {
2657 int numCursors = mManagedCursors.size();
2658 for (int i = 0; i < numCursors; i++) {
2659 ManagedCursor c = mManagedCursors.get(i);
2660 if (c != null) {
2661 c.mCursor.close();
2662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
Makoto Onuki2f6a0182010-02-22 13:26:59 -08002664 mManagedCursors.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 }
Amith Yamasani49860442010-03-17 20:54:10 -07002666
2667 // Close any open search dialog
2668 if (mSearchManager != null) {
2669 mSearchManager.stopSearch();
2670 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07002671
Chris Banes21b25772016-01-04 20:41:59 +00002672 if (mActionBar != null) {
2673 mActionBar.onDestroy();
2674 }
Narayan Kamathff5659f2017-02-02 13:31:33 +00002675
Ian Lake8a88cd62018-09-28 13:25:20 -07002676 dispatchActivityDestroyed();
Felipe Lemeb0da18f2019-02-22 15:10:02 -08002677
2678 notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_STOP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680
2681 /**
Mathieu Chartier7fe953e2019-10-16 10:27:29 -07002682 * Report to the system that your app is now fully drawn, for diagnostic and
2683 * optimization purposes. The system may adjust optimizations to prioritize
2684 * work that happens before reportFullyDrawn is called, to improve app startup.
2685 * Misrepresenting the startup window by calling reportFullyDrawn too late or too
2686 * early may decrease application and startup performance.<p>
2687 * This is also used to help instrument application launch times, so that the
Dianne Hackbornebc15ef2013-10-09 17:36:57 -07002688 * app can report when it is fully in a usable state; without this, the only thing
2689 * the system itself can determine is the point at which the activity's window
2690 * is <em>first</em> drawn and displayed. To participate in app launch time
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07002691 * measurement, you should always call this method after first launch (when
Dianne Hackbornebc15ef2013-10-09 17:36:57 -07002692 * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07002693 * entirely drawn your UI and populated with all of the significant data. You
2694 * can safely call this method any time after first launch as well, in which case
2695 * it will simply be ignored.
Riddle Hsuc1f8f9c2019-10-25 16:54:33 +08002696 * <p>If this method is called before the activity's window is <em>first</em> drawn
2697 * and displayed as measured by the system, the reported time here will be shifted
2698 * to the system measured time.
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07002699 */
2700 public void reportFullyDrawn() {
2701 if (mDoReportFullyDrawn) {
2702 mDoReportFullyDrawn = false;
2703 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002704 ActivityTaskManager.getService().reportActivityFullyDrawn(
2705 mToken, mRestoredFromBundle);
Mathieu Chartier63e14c12019-03-07 09:05:44 -08002706 VMRuntime.getRuntime().notifyStartupCompleted();
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07002707 } catch (RemoteException e) {
2708 }
2709 }
2710 }
2711
2712 /**
Wale Ogunwale5f986092015-12-04 15:35:38 -08002713 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
Winson Chung5af42fc2017-03-24 17:11:33 -07002714 * visa-versa. This method provides the same configuration that will be sent in the following
2715 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2716 *
Wale Ogunwale5f986092015-12-04 15:35:38 -08002717 * @see android.R.attr#resizeableActivity
2718 *
Andrii Kulian933076d2016-03-29 17:04:42 -07002719 * @param isInMultiWindowMode True if the activity is in multi-window mode.
Winson Chung5af42fc2017-03-24 17:11:33 -07002720 * @param newConfig The new configuration of the activity with the state
2721 * {@param isInMultiWindowMode}.
Wale Ogunwale5f986092015-12-04 15:35:38 -08002722 */
Winson Chung5af42fc2017-03-24 17:11:33 -07002723 public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
2724 // Left deliberately empty. There should be no side effects if a direct
2725 // subclass of Activity does not call super.
2726 onMultiWindowModeChanged(isInMultiWindowMode);
2727 }
2728
2729 /**
2730 * Called by the system when the activity changes from fullscreen mode to multi-window mode and
2731 * visa-versa.
2732 *
2733 * @see android.R.attr#resizeableActivity
2734 *
2735 * @param isInMultiWindowMode True if the activity is in multi-window mode.
2736 *
2737 * @deprecated Use {@link #onMultiWindowModeChanged(boolean, Configuration)} instead.
2738 */
2739 @Deprecated
Andrii Kulian933076d2016-03-29 17:04:42 -07002740 public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
Adam Powell858cf032016-05-09 15:45:37 -07002741 // Left deliberately empty. There should be no side effects if a direct
2742 // subclass of Activity does not call super.
Wale Ogunwale5f986092015-12-04 15:35:38 -08002743 }
2744
2745 /**
2746 * Returns true if the activity is currently in multi-window mode.
2747 * @see android.R.attr#resizeableActivity
2748 *
2749 * @return True if the activity is in multi-window mode.
2750 */
Andrii Kulian933076d2016-03-29 17:04:42 -07002751 public boolean isInMultiWindowMode() {
Hongwei Wangf7e5a232020-05-06 15:49:44 -07002752 return mIsInMultiWindowMode;
Wale Ogunwale5f986092015-12-04 15:35:38 -08002753 }
2754
2755 /**
Winson Chung5af42fc2017-03-24 17:11:33 -07002756 * Called by the system when the activity changes to and from picture-in-picture mode. This
2757 * method provides the same configuration that will be sent in the following
2758 * {@link #onConfigurationChanged(Configuration)} call after the activity enters this mode.
2759 *
Wale Ogunwale5f986092015-12-04 15:35:38 -08002760 * @see android.R.attr#supportsPictureInPicture
2761 *
Andrii Kulian933076d2016-03-29 17:04:42 -07002762 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
Winson Chung5af42fc2017-03-24 17:11:33 -07002763 * @param newConfig The new configuration of the activity with the state
2764 * {@param isInPictureInPictureMode}.
Wale Ogunwale5f986092015-12-04 15:35:38 -08002765 */
Winson Chung5af42fc2017-03-24 17:11:33 -07002766 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode,
2767 Configuration newConfig) {
2768 // Left deliberately empty. There should be no side effects if a direct
2769 // subclass of Activity does not call super.
2770 onPictureInPictureModeChanged(isInPictureInPictureMode);
2771 }
2772
2773 /**
2774 * Called by the system when the activity changes to and from picture-in-picture mode.
2775 *
2776 * @see android.R.attr#supportsPictureInPicture
2777 *
2778 * @param isInPictureInPictureMode True if the activity is in picture-in-picture mode.
2779 *
2780 * @deprecated Use {@link #onPictureInPictureModeChanged(boolean, Configuration)} instead.
2781 */
2782 @Deprecated
Andrii Kulian933076d2016-03-29 17:04:42 -07002783 public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
Adam Powell858cf032016-05-09 15:45:37 -07002784 // Left deliberately empty. There should be no side effects if a direct
2785 // subclass of Activity does not call super.
Wale Ogunwale5f986092015-12-04 15:35:38 -08002786 }
2787
2788 /**
2789 * Returns true if the activity is currently in picture-in-picture mode.
2790 * @see android.R.attr#supportsPictureInPicture
2791 *
2792 * @return True if the activity is in picture-in-picture mode.
2793 */
Andrii Kulian933076d2016-03-29 17:04:42 -07002794 public boolean isInPictureInPictureMode() {
Hongwei Wangf7e5a232020-05-06 15:49:44 -07002795 return mIsInPictureInPictureMode;
Wale Ogunwale5f986092015-12-04 15:35:38 -08002796 }
2797
2798 /**
Winson Chungc2baac02017-01-11 13:34:47 -08002799 * Puts the activity in picture-in-picture mode if possible in the current system state. Any
Winson Chung709904f2017-04-25 11:00:48 -07002800 * prior calls to {@link #setPictureInPictureParams(PictureInPictureParams)} will still apply
2801 * when entering picture-in-picture through this call.
Winson Chungc2baac02017-01-11 13:34:47 -08002802 *
Winson Chung709904f2017-04-25 11:00:48 -07002803 * @see #enterPictureInPictureMode(PictureInPictureParams)
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002804 * @see android.R.attr#supportsPictureInPicture
2805 */
Winson Chung709904f2017-04-25 11:00:48 -07002806 @Deprecated
Andrii Kulian933076d2016-03-29 17:04:42 -07002807 public void enterPictureInPictureMode() {
Winson Chung709904f2017-04-25 11:00:48 -07002808 enterPictureInPictureMode(new PictureInPictureParams.Builder().build());
Wale Ogunwale9c604c72015-12-06 18:42:57 -08002809 }
2810
Winson Chungc2baac02017-01-11 13:34:47 -08002811 /**
Winson Chung709904f2017-04-25 11:00:48 -07002812 * Puts the activity in picture-in-picture mode if possible in the current system state. The
2813 * set parameters in {@param params} will be combined with the parameters from prior calls to
2814 * {@link #setPictureInPictureParams(PictureInPictureParams)}.
2815 *
2816 * The system may disallow entering picture-in-picture in various cases, including when the
2817 * activity is not visible, if the screen is locked or if the user has an activity pinned.
2818 *
Hongwei Wang57ab7c72020-04-06 17:04:45 -07002819 * <p>By default, system calculates the dimension of picture-in-picture window based on the
2820 * given {@param params}.
2821 * See <a href="{@docRoot}guide/topics/ui/picture-in-picture">Picture-in-picture Support</a>
2822 * on how to override this behavior.</p>
2823 *
Winson Chung709904f2017-04-25 11:00:48 -07002824 * @see android.R.attr#supportsPictureInPicture
2825 * @see PictureInPictureParams
2826 *
2827 * @param params non-null parameters to be combined with previously set parameters when entering
2828 * picture-in-picture.
2829 *
Winson Chung80fa2d82018-01-25 13:58:20 -08002830 * @return true if the system successfully put this activity into picture-in-picture mode or was
Andrew Solovay8a788f42018-12-12 14:25:47 -08002831 * already in picture-in-picture mode (see {@link #isInPictureInPictureMode()}). If the device
Winson Chung80fa2d82018-01-25 13:58:20 -08002832 * does not support picture-in-picture, return false.
Winson Chung709904f2017-04-25 11:00:48 -07002833 */
2834 public boolean enterPictureInPictureMode(@NonNull PictureInPictureParams params) {
2835 try {
Winson Chung80fa2d82018-01-25 13:58:20 -08002836 if (!deviceSupportsPictureInPictureMode()) {
2837 return false;
2838 }
Winson Chung709904f2017-04-25 11:00:48 -07002839 if (params == null) {
2840 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
2841 }
Winson Chung298f95b2017-08-10 15:57:18 -07002842 if (!mCanEnterPictureInPicture) {
2843 throw new IllegalStateException("Activity must be resumed to enter"
2844 + " picture-in-picture");
2845 }
Hongwei Wange37b84d2020-05-28 11:37:36 -07002846 // Set mIsInPictureInPictureMode earlier and don't wait for
2847 // onPictureInPictureModeChanged callback here. This is to ensure that
2848 // isInPictureInPictureMode returns true in the following onPause callback.
2849 // See https://developer.android.com/guide/topics/ui/picture-in-picture for guidance.
2850 mIsInPictureInPictureMode = ActivityTaskManager.getService().enterPictureInPictureMode(
2851 mToken, params);
2852 return mIsInPictureInPictureMode;
Winson Chung709904f2017-04-25 11:00:48 -07002853 } catch (RemoteException e) {
2854 return false;
2855 }
2856 }
2857
Winson Chung709904f2017-04-25 11:00:48 -07002858 /**
Winson Chungc2baac02017-01-11 13:34:47 -08002859 * Updates the properties of the picture-in-picture activity, or sets it to be used later when
2860 * {@link #enterPictureInPictureMode()} is called.
2861 *
Winson Chung709904f2017-04-25 11:00:48 -07002862 * @param params the new parameters for the picture-in-picture.
Winson Chungc2baac02017-01-11 13:34:47 -08002863 */
Winson Chung709904f2017-04-25 11:00:48 -07002864 public void setPictureInPictureParams(@NonNull PictureInPictureParams params) {
Winson Chungc2baac02017-01-11 13:34:47 -08002865 try {
Winson Chung80fa2d82018-01-25 13:58:20 -08002866 if (!deviceSupportsPictureInPictureMode()) {
2867 return;
2868 }
Winson Chung709904f2017-04-25 11:00:48 -07002869 if (params == null) {
2870 throw new IllegalArgumentException("Expected non-null picture-in-picture params");
Winson Chungc2baac02017-01-11 13:34:47 -08002871 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 ActivityTaskManager.getService().setPictureInPictureParams(mToken, params);
Winson Chungb5c41b72016-12-07 15:00:47 -08002873 } catch (RemoteException e) {
2874 }
2875 }
2876
Winson Chung8802eac2017-04-17 14:21:44 -07002877 /**
Winson Chung709904f2017-04-25 11:00:48 -07002878 * Return the number of actions that will be displayed in the picture-in-picture UI when the
2879 * user interacts with the activity currently in picture-in-picture mode. This number may change
2880 * if the global configuration changes (ie. if the device is plugged into an external display),
2881 * but will always be larger than three.
2882 */
2883 public int getMaxNumPictureInPictureActions() {
2884 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 return ActivityTaskManager.getService().getMaxNumPictureInPictureActions(mToken);
Winson Chung709904f2017-04-25 11:00:48 -07002886 } catch (RemoteException e) {
2887 return 0;
2888 }
2889 }
2890
Winson Chung80fa2d82018-01-25 13:58:20 -08002891 /**
2892 * @return Whether this device supports picture-in-picture.
2893 */
2894 private boolean deviceSupportsPictureInPictureMode() {
2895 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
2896 }
2897
jorgegil@google.com06bc3232019-10-31 14:51:22 -07002898 /**
jorgegil@google.com7a926dc2020-01-29 10:28:33 -08002899 * This method is called by the system in various cases where picture in picture mode should be
2900 * entered if supported.
2901 *
2902 * <p>It is up to the app developer to choose whether to call
2903 * {@link #enterPictureInPictureMode(PictureInPictureParams)} at this time. For example, the
2904 * system will call this method when the activity is being put into the background, so the app
2905 * developer might want to switch an activity into PIP mode instead.</p>
jorgegil@google.comb8ee18f2020-02-03 13:21:27 -08002906 *
2907 * @return {@code true} if the activity received this callback regardless of if it acts on it
2908 * or not. If {@code false}, the framework will assume the app hasn't been updated to leverage
2909 * this callback and will in turn send a legacy callback of {@link #onUserLeaveHint()} for the
2910 * app to enter picture-in-picture mode.
jorgegil@google.com06bc3232019-10-31 14:51:22 -07002911 */
jorgegil@google.comb8ee18f2020-02-03 13:21:27 -08002912 public boolean onPictureInPictureRequested() {
2913 return false;
jorgegil@google.com06bc3232019-10-31 14:51:22 -07002914 }
2915
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002916 void dispatchMovedToDisplay(int displayId, Configuration config) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002917 updateDisplay(displayId);
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002918 onMovedToDisplay(displayId, config);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002919 }
2920
2921 /**
2922 * Called by the system when the activity is moved from one display to another without
2923 * recreation. This means that this activity is declared to handle all changes to configuration
2924 * that happened when it was switched to another display, so it wasn't destroyed and created
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002925 * again.
2926 *
2927 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
2928 * applied configuration actually changed. It is up to app developer to choose whether to handle
2929 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
2930 * call.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002931 *
2932 * <p>Use this callback to track changes to the displays if some activity functionality relies
2933 * on an association with some display properties.
2934 *
2935 * @param displayId The id of the display to which activity was moved.
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002936 * @param config Configuration of the activity resources on new display after move.
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002937 *
2938 * @see #onConfigurationChanged(Configuration)
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002939 * @see View#onMovedToDisplay(int, Configuration)
Andrii Kuliancadacce2017-04-26 18:09:54 -07002940 * @hide
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002941 */
Artur Satayevf0b7d0b2019-11-04 11:16:45 +00002942 @UnsupportedAppUsage
Tiger Huangfc218452018-09-27 00:38:50 +08002943 @TestApi
Andrii Kuliane5c58ee2017-03-27 19:25:24 -07002944 public void onMovedToDisplay(int displayId, Configuration config) {
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002945 }
2946
Winson Chungb5c41b72016-12-07 15:00:47 -08002947 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 * Called by the system when the device configuration changes while your
2949 * activity is running. Note that this will <em>only</em> be called if
2950 * you have selected configurations you would like to handle with the
2951 * {@link android.R.attr#configChanges} attribute in your manifest. If
2952 * any configuration change occurs that is not selected to be reported
2953 * by that attribute, then instead of reporting it the system will stop
2954 * and restart the activity (to have it launched with the new
2955 * configuration).
RoboErik55011652014-07-09 15:05:53 -07002956 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 * <p>At the time that this function has been called, your Resources
2958 * object will have been updated to return resource values matching the
2959 * new configuration.
RoboErik55011652014-07-09 15:05:53 -07002960 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 * @param newConfig The new device configuration.
2962 */
Ian Lake666a9652018-09-12 15:13:19 -07002963 public void onConfigurationChanged(@NonNull Configuration newConfig) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07002964 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onConfigurationChanged " + this + ": " + newConfig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 mCalled = true;
Bjorn Bringert444c7272009-07-06 21:32:50 +01002966
Dianne Hackborn9d071802010-12-08 14:49:15 -08002967 mFragments.dispatchConfigurationChanged(newConfig);
2968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 if (mWindow != null) {
2970 // Pass the configuration changed event to the window
2971 mWindow.onConfigurationChanged(newConfig);
2972 }
Adam Powell45c0b192011-07-28 15:11:57 -07002973
2974 if (mActionBar != null) {
2975 // Do this last; the action bar will need to access
2976 // view changes from above.
2977 mActionBar.onConfigurationChanged(newConfig);
2978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
RoboErik55011652014-07-09 15:05:53 -07002980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 /**
2982 * If this activity is being destroyed because it can not handle a
2983 * configuration parameter being changed (and thus its
2984 * {@link #onConfigurationChanged(Configuration)} method is
2985 * <em>not</em> being called), then you can use this method to discover
2986 * the set of changes that have occurred while in the process of being
2987 * destroyed. Note that there is no guarantee that these will be
2988 * accurate (other changes could have happened at any time), so you should
2989 * only use this as an optimization hint.
RoboErik55011652014-07-09 15:05:53 -07002990 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 * @return Returns a bit field of the configuration parameters that are
2992 * changing, as defined by the {@link android.content.res.Configuration}
2993 * class.
2994 */
2995 public int getChangingConfigurations() {
2996 return mConfigChangeFlags;
2997 }
RoboErik55011652014-07-09 15:05:53 -07002998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 /**
3000 * Retrieve the non-configuration instance data that was previously
3001 * returned by {@link #onRetainNonConfigurationInstance()}. This will
3002 * be available from the initial {@link #onCreate} and
3003 * {@link #onStart} calls to the new instance, allowing you to extract
3004 * any useful dynamic state from the previous instance.
RoboErik55011652014-07-09 15:05:53 -07003005 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 * <p>Note that the data you retrieve here should <em>only</em> be used
3007 * as an optimization for handling configuration changes. You should always
3008 * be able to handle getting a null pointer back, and an activity must
3009 * still be able to restore itself to its previous state (through the
3010 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
3011 * function returns null.
RoboErik55011652014-07-09 15:05:53 -07003012 *
Adam Powellc4df6bc2016-03-09 15:11:37 -08003013 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003014 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
Adam Powellc4df6bc2016-03-09 15:11:37 -08003015 * available on older platforms through the Android support libraries.
3016 *
3017 * @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 */
Tor Norbyed9273d62013-05-30 15:59:53 -07003019 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 public Object getLastNonConfigurationInstance() {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003021 return mLastNonConfigurationInstances != null
3022 ? mLastNonConfigurationInstances.activity : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 }
RoboErik55011652014-07-09 15:05:53 -07003024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 /**
3026 * Called by the system, as part of destroying an
3027 * activity due to a configuration change, when it is known that a new
3028 * instance will immediately be created for the new configuration. You
3029 * can return any object you like here, including the activity instance
3030 * itself, which can later be retrieved by calling
3031 * {@link #getLastNonConfigurationInstance()} in the new activity
3032 * instance.
RoboErik55011652014-07-09 15:05:53 -07003033 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003034 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3035 * or later, consider instead using a {@link Fragment} with
3036 * {@link Fragment#setRetainInstance(boolean)
3037 * Fragment.setRetainInstance(boolean}.</em>
3038 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 * <p>This function is called purely as an optimization, and you must
3040 * not rely on it being called. When it is called, a number of guarantees
3041 * will be made to help optimize configuration switching:
3042 * <ul>
3043 * <li> The function will be called between {@link #onStop} and
3044 * {@link #onDestroy}.
3045 * <li> A new instance of the activity will <em>always</em> be immediately
Dianne Hackbornce2ef762010-09-20 11:39:14 -07003046 * created after this one's {@link #onDestroy()} is called. In particular,
3047 * <em>no</em> messages will be dispatched during this time (when the returned
3048 * object does not have an activity to be associated with).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 * <li> The object you return here will <em>always</em> be available from
3050 * the {@link #getLastNonConfigurationInstance()} method of the following
3051 * activity instance as described there.
3052 * </ul>
RoboErik55011652014-07-09 15:05:53 -07003053 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 * <p>These guarantees are designed so that an activity can use this API
3055 * to propagate extensive state from the old to new activity instance, from
3056 * loaded bitmaps, to network connections, to evenly actively running
3057 * threads. Note that you should <em>not</em> propagate any data that
3058 * may change based on the configuration, including any data loaded from
3059 * resources such as strings, layouts, or drawables.
RoboErik55011652014-07-09 15:05:53 -07003060 *
Dianne Hackbornce2ef762010-09-20 11:39:14 -07003061 * <p>The guarantee of no message handling during the switch to the next
3062 * activity simplifies use with active objects. For example if your retained
3063 * state is an {@link android.os.AsyncTask} you are guaranteed that its
3064 * call back functions (like {@link android.os.AsyncTask#onPostExecute}) will
3065 * not be called from the call here until you execute the next instance's
3066 * {@link #onCreate(Bundle)}. (Note however that there is of course no such
3067 * guarantee for {@link android.os.AsyncTask#doInBackground} since that is
3068 * running in a separate thread.)
3069 *
Adam Powellc4df6bc2016-03-09 15:11:37 -08003070 * <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003071 * {@link Fragment#setRetainInstance(boolean)} instead; this is also
Adam Powellc4df6bc2016-03-09 15:11:37 -08003072 * available on older platforms through the Android support libraries.
3073 *
3074 * @return any Object holding the desired state to propagate to the
3075 * next activity instance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 */
3077 public Object onRetainNonConfigurationInstance() {
3078 return null;
3079 }
RoboErik55011652014-07-09 15:05:53 -07003080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 /**
3082 * Retrieve the non-configuration instance data that was previously
3083 * returned by {@link #onRetainNonConfigurationChildInstances()}. This will
3084 * be available from the initial {@link #onCreate} and
3085 * {@link #onStart} calls to the new instance, allowing you to extract
3086 * any useful dynamic state from the previous instance.
RoboErik55011652014-07-09 15:05:53 -07003087 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 * <p>Note that the data you retrieve here should <em>only</em> be used
3089 * as an optimization for handling configuration changes. You should always
3090 * be able to handle getting a null pointer back, and an activity must
3091 * still be able to restore itself to its previous state (through the
3092 * normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
3093 * function returns null.
RoboErik55011652014-07-09 15:05:53 -07003094 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 * @return Returns the object previously returned by
3096 * {@link #onRetainNonConfigurationChildInstances()}
3097 */
Tor Norbyed9273d62013-05-30 15:59:53 -07003098 @Nullable
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003099 HashMap<String, Object> getLastNonConfigurationChildInstances() {
3100 return mLastNonConfigurationInstances != null
3101 ? mLastNonConfigurationInstances.children : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
RoboErik55011652014-07-09 15:05:53 -07003103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 /**
3105 * This method is similar to {@link #onRetainNonConfigurationInstance()} except that
3106 * it should return either a mapping from child activity id strings to arbitrary objects,
3107 * or null. This method is intended to be used by Activity framework subclasses that control a
3108 * set of child activities, such as ActivityGroup. The same guarantees and restrictions apply
3109 * as for {@link #onRetainNonConfigurationInstance()}. The default implementation returns null.
3110 */
Tor Norbyed9273d62013-05-30 15:59:53 -07003111 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 HashMap<String,Object> onRetainNonConfigurationChildInstances() {
3113 return null;
3114 }
RoboErik55011652014-07-09 15:05:53 -07003115
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003116 NonConfigurationInstances retainNonConfigurationInstances() {
3117 Object activity = onRetainNonConfigurationInstance();
3118 HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
Adam Powell44ba79e2016-02-04 16:20:37 -08003119 FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
Adam Powellcbade7f2016-04-15 11:14:37 -07003120
3121 // We're already stopped but we've been asked to retain.
3122 // Our fragments are taken care of but we need to mark the loaders for retention.
3123 // In order to do this correctly we need to restart the loaders first before
3124 // handing them off to the next activity.
3125 mFragments.doLoaderStart();
3126 mFragments.doLoaderStop(true);
Todd Kennedya5fc6f02015-04-14 18:22:54 -07003127 ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
Adam Powellcbade7f2016-04-15 11:14:37 -07003128
Todd Kennedya5fc6f02015-04-14 18:22:54 -07003129 if (activity == null && children == null && fragments == null && loaders == null
Dianne Hackborn20d94742014-05-29 18:35:45 -07003130 && mVoiceInteractor == null) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003131 return null;
3132 }
RoboErik55011652014-07-09 15:05:53 -07003133
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003134 NonConfigurationInstances nci = new NonConfigurationInstances();
3135 nci.activity = activity;
3136 nci.children = children;
3137 nci.fragments = fragments;
Todd Kennedya5fc6f02015-04-14 18:22:54 -07003138 nci.loaders = loaders;
Dianne Hackborn57dd7372015-07-27 18:11:14 -07003139 if (mVoiceInteractor != null) {
3140 mVoiceInteractor.retainInstance();
3141 nci.voiceInteractor = mVoiceInteractor;
3142 }
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07003143 return nci;
3144 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 public void onLowMemory() {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003147 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onLowMemory " + this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 mCalled = true;
Dianne Hackborn9d071802010-12-08 14:49:15 -08003149 mFragments.dispatchLowMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003151
3152 public void onTrimMemory(int level) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003153 if (DEBUG_LIFECYCLE) Slog.v(TAG, "onTrimMemory " + this + ": " + level);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07003154 mCalled = true;
3155 mFragments.dispatchTrimMemory(level);
3156 }
3157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 /**
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07003159 * Return the FragmentManager for interacting with fragments associated
3160 * with this activity.
Ian Lake0a1feb82017-11-13 10:26:46 -08003161 *
3162 * @deprecated Use {@link android.support.v4.app.FragmentActivity#getSupportFragmentManager()}
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07003163 */
Ian Lake0a1feb82017-11-13 10:26:46 -08003164 @Deprecated
Dianne Hackbornb7a2e472010-08-12 16:20:42 -07003165 public FragmentManager getFragmentManager() {
Todd Kennedya5fc6f02015-04-14 18:22:54 -07003166 return mFragments.getFragmentManager();
Dianne Hackborn9e14e9f32010-07-14 11:07:38 -07003167 }
RoboErik55011652014-07-09 15:05:53 -07003168
Dianne Hackborn2dedce62010-04-15 14:45:25 -07003169 /**
Dianne Hackbornc8017682010-07-06 13:34:38 -07003170 * Called when a Fragment is being attached to this activity, immediately
3171 * after the call to its {@link Fragment#onAttach Fragment.onAttach()}
3172 * method and before {@link Fragment#onCreate Fragment.onCreate()}.
Ian Lake0a1feb82017-11-13 10:26:46 -08003173 *
3174 * @deprecated Use {@link
3175 * android.support.v4.app.FragmentActivity#onAttachFragment(android.support.v4.app.Fragment)}
Dianne Hackbornc8017682010-07-06 13:34:38 -07003176 */
Ian Lake0a1feb82017-11-13 10:26:46 -08003177 @Deprecated
Dianne Hackbornc8017682010-07-06 13:34:38 -07003178 public void onAttachFragment(Fragment fragment) {
3179 }
RoboErik55011652014-07-09 15:05:53 -07003180
Dianne Hackbornc8017682010-07-06 13:34:38 -07003181 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 * Wrapper around
3183 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
3184 * that gives the resulting {@link Cursor} to call
3185 * {@link #startManagingCursor} so that the activity will manage its
3186 * lifecycle for you.
RoboErik55011652014-07-09 15:05:53 -07003187 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003188 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3189 * or later, consider instead using {@link LoaderManager} instead, available
3190 * via {@link #getLoaderManager()}.</em>
3191 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07003192 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
3193 * this method, because the activity will do that for you at the appropriate time. However, if
3194 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
3195 * not</em> automatically close the cursor and, in that case, you must call
3196 * {@link Cursor#close()}.</p>
RoboErik55011652014-07-09 15:05:53 -07003197 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 * @param uri The URI of the content provider to query.
3199 * @param projection List of columns to return.
3200 * @param selection SQL WHERE clause.
3201 * @param sortOrder SQL ORDER BY clause.
RoboErik55011652014-07-09 15:05:53 -07003202 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 * @return The Cursor that was returned by query().
RoboErik55011652014-07-09 15:05:53 -07003204 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
3206 * @see #startManagingCursor
3207 * @hide
Jason parks6ed50de2010-08-25 10:18:50 -05003208 *
3209 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 */
Jason parks6ed50de2010-08-25 10:18:50 -05003211 @Deprecated
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003212 @UnsupportedAppUsage
Dianne Hackborn291905e2010-08-17 15:17:15 -07003213 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
3214 String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 Cursor c = getContentResolver().query(uri, projection, selection, null, sortOrder);
3216 if (c != null) {
3217 startManagingCursor(c);
3218 }
3219 return c;
3220 }
3221
3222 /**
3223 * Wrapper around
3224 * {@link ContentResolver#query(android.net.Uri , String[], String, String[], String)}
3225 * that gives the resulting {@link Cursor} to call
3226 * {@link #startManagingCursor} so that the activity will manage its
3227 * lifecycle for you.
RoboErik55011652014-07-09 15:05:53 -07003228 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003229 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3230 * or later, consider instead using {@link LoaderManager} instead, available
3231 * via {@link #getLoaderManager()}.</em>
3232 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07003233 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on a cursor obtained using
3234 * this method, because the activity will do that for you at the appropriate time. However, if
3235 * you call {@link #stopManagingCursor} on a cursor from a managed query, the system <em>will
3236 * not</em> automatically close the cursor and, in that case, you must call
3237 * {@link Cursor#close()}.</p>
RoboErik55011652014-07-09 15:05:53 -07003238 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 * @param uri The URI of the content provider to query.
3240 * @param projection List of columns to return.
3241 * @param selection SQL WHERE clause.
3242 * @param selectionArgs The arguments to selection, if any ?s are pesent
3243 * @param sortOrder SQL ORDER BY clause.
RoboErik55011652014-07-09 15:05:53 -07003244 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 * @return The Cursor that was returned by query().
RoboErik55011652014-07-09 15:05:53 -07003246 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 * @see ContentResolver#query(android.net.Uri , String[], String, String[], String)
3248 * @see #startManagingCursor
Jason parks6ed50de2010-08-25 10:18:50 -05003249 *
3250 * @deprecated Use {@link CursorLoader} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 */
Jason parks6ed50de2010-08-25 10:18:50 -05003252 @Deprecated
Dianne Hackborn291905e2010-08-17 15:17:15 -07003253 public final Cursor managedQuery(Uri uri, String[] projection, String selection,
3254 String[] selectionArgs, String sortOrder) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
3256 if (c != null) {
3257 startManagingCursor(c);
3258 }
3259 return c;
3260 }
3261
3262 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 * This method allows the activity to take care of managing the given
3264 * {@link Cursor}'s lifecycle for you based on the activity's lifecycle.
3265 * That is, when the activity is stopped it will automatically call
3266 * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted
3267 * it will call {@link Cursor#requery} for you. When the activity is
3268 * destroyed, all managed Cursors will be closed automatically.
RoboErik55011652014-07-09 15:05:53 -07003269 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07003270 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
3271 * or later, consider instead using {@link LoaderManager} instead, available
3272 * via {@link #getLoaderManager()}.</em>
3273 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07003274 * <p><strong>Warning:</strong> Do not call {@link Cursor#close()} on cursor obtained from
3275 * {@link #managedQuery}, because the activity will do that for you at the appropriate time.
3276 * However, if you call {@link #stopManagingCursor} on a cursor from a managed query, the system
3277 * <em>will not</em> automatically close the cursor and, in that case, you must call
3278 * {@link Cursor#close()}.</p>
RoboErik55011652014-07-09 15:05:53 -07003279 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 * @param c The Cursor to be managed.
RoboErik55011652014-07-09 15:05:53 -07003281 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 * @see #managedQuery(android.net.Uri , String[], String, String[], String)
3283 * @see #stopManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003284 *
3285 * @deprecated Use the new {@link android.content.CursorLoader} class with
3286 * {@link LoaderManager} instead; this is also
3287 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 */
Jason parks6ed50de2010-08-25 10:18:50 -05003289 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 public void startManagingCursor(Cursor c) {
3291 synchronized (mManagedCursors) {
3292 mManagedCursors.add(new ManagedCursor(c));
3293 }
3294 }
3295
3296 /**
3297 * Given a Cursor that was previously given to
3298 * {@link #startManagingCursor}, stop the activity's management of that
3299 * cursor.
RoboErik55011652014-07-09 15:05:53 -07003300 *
Joe Fernandez8ef69702011-09-02 14:32:22 -07003301 * <p><strong>Warning:</strong> After calling this method on a cursor from a managed query,
RoboErik55011652014-07-09 15:05:53 -07003302 * the system <em>will not</em> automatically close the cursor and you must call
Joe Fernandez8ef69702011-09-02 14:32:22 -07003303 * {@link Cursor#close()}.</p>
RoboErik55011652014-07-09 15:05:53 -07003304 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 * @param c The Cursor that was being managed.
RoboErik55011652014-07-09 15:05:53 -07003306 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 * @see #startManagingCursor
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07003308 *
3309 * @deprecated Use the new {@link android.content.CursorLoader} class with
3310 * {@link LoaderManager} instead; this is also
3311 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 */
Jason parks6ed50de2010-08-25 10:18:50 -05003313 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 public void stopManagingCursor(Cursor c) {
3315 synchronized (mManagedCursors) {
3316 final int N = mManagedCursors.size();
3317 for (int i=0; i<N; i++) {
3318 ManagedCursor mc = mManagedCursors.get(i);
3319 if (mc.mCursor == c) {
3320 mManagedCursors.remove(i);
3321 break;
3322 }
3323 }
3324 }
3325 }
3326
3327 /**
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003328 * @deprecated As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}
3329 * this is a no-op.
Dianne Hackborn4f3867e2010-12-14 22:09:51 -08003330 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 */
Dianne Hackbornd3efa392010-09-01 17:34:12 -07003332 @Deprecated
Mathew Inwood61e8ae62018-08-14 14:17:44 +01003333 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 public void setPersistent(boolean isPersistent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
3336
3337 /**
Alan Viverettedb7423c2017-03-31 13:13:58 -04003338 * Finds a view that was identified by the {@code android:id} XML attribute
3339 * that was processed in {@link #onCreate}.
3340 * <p>
3341 * <strong>Note:</strong> In most cases -- depending on compiler support --
3342 * the resulting view is automatically cast to the target class type. If
3343 * the target class type is unconstrained, an explicit cast may be
3344 * necessary.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 *
Alan Viverettedb7423c2017-03-31 13:13:58 -04003346 * @param id the ID to search for
3347 * @return a view with given ID if found, or {@code null} otherwise
3348 * @see View#findViewById(int)
Chris Craik6faa9e52018-01-11 10:46:10 -08003349 * @see Activity#requireViewById(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 */
Scott Kennedyc0519552015-02-11 15:33:10 -08003351 @Nullable
Alan Viverettedb7423c2017-03-31 13:13:58 -04003352 public <T extends View> T findViewById(@IdRes int id) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 return getWindow().findViewById(id);
3354 }
RoboErik55011652014-07-09 15:05:53 -07003355
Adam Powell33b97432010-04-20 10:01:14 -07003356 /**
Chris Craik6faa9e52018-01-11 10:46:10 -08003357 * Finds a view that was identified by the {@code android:id} XML attribute that was processed
3358 * in {@link #onCreate}, or throws an IllegalArgumentException if the ID is invalid, or there is
3359 * no matching view in the hierarchy.
3360 * <p>
3361 * <strong>Note:</strong> In most cases -- depending on compiler support --
3362 * the resulting view is automatically cast to the target class type. If
3363 * the target class type is unconstrained, an explicit cast may be
3364 * necessary.
3365 *
3366 * @param id the ID to search for
3367 * @return a view with given ID
3368 * @see View#requireViewById(int)
3369 * @see Activity#findViewById(int)
3370 */
3371 @NonNull
3372 public final <T extends View> T requireViewById(@IdRes int id) {
3373 T view = findViewById(id);
3374 if (view == null) {
3375 throw new IllegalArgumentException("ID does not reference a View inside this Activity");
3376 }
3377 return view;
3378 }
3379
3380 /**
Adam Powell33b97432010-04-20 10:01:14 -07003381 * Retrieve a reference to this activity's ActionBar.
Adam Powell42c0fe82010-08-10 16:36:56 -07003382 *
Adam Powell33b97432010-04-20 10:01:14 -07003383 * @return The Activity's ActionBar, or null if it does not have one.
3384 */
Tor Norbyed9273d62013-05-30 15:59:53 -07003385 @Nullable
Adam Powell33b97432010-04-20 10:01:14 -07003386 public ActionBar getActionBar() {
Adam Powelle43340c2014-03-17 19:10:43 -07003387 initWindowDecorActionBar();
Adam Powell33b97432010-04-20 10:01:14 -07003388 return mActionBar;
3389 }
Adam Powelle43340c2014-03-17 19:10:43 -07003390
3391 /**
3392 * Set a {@link android.widget.Toolbar Toolbar} to act as the {@link ActionBar} for this
3393 * Activity window.
3394 *
3395 * <p>When set to a non-null value the {@link #getActionBar()} method will return
3396 * an {@link ActionBar} object that can be used to control the given toolbar as if it were
3397 * a traditional window decor action bar. The toolbar's menu will be populated with the
3398 * Activity's options menu and the navigation button will be wired through the standard
3399 * {@link android.R.id#home home} menu select action.</p>
3400 *
3401 * <p>In order to use a Toolbar within the Activity's window content the application
3402 * must not request the window feature {@link Window#FEATURE_ACTION_BAR FEATURE_ACTION_BAR}.</p>
3403 *
Chris Banesc7d6c322016-01-27 14:09:16 +00003404 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
Adam Powelle43340c2014-03-17 19:10:43 -07003405 */
Adam Powell37780142014-06-01 13:31:00 -07003406 public void setActionBar(@Nullable Toolbar toolbar) {
Chris Banes21b25772016-01-04 20:41:59 +00003407 final ActionBar ab = getActionBar();
3408 if (ab instanceof WindowDecorActionBar) {
Adam Powelle43340c2014-03-17 19:10:43 -07003409 throw new IllegalStateException("This Activity already has an action bar supplied " +
3410 "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
3411 "android:windowActionBar to false in your theme to use a Toolbar instead.");
3412 }
Chris Banes21b25772016-01-04 20:41:59 +00003413
3414 // If we reach here then we're setting a new action bar
3415 // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
Chris Banes601bb992015-06-22 10:05:38 +01003416 mMenuInflater = null;
3417
Chris Banes21b25772016-01-04 20:41:59 +00003418 // If we have an action bar currently, destroy it
3419 if (ab != null) {
3420 ab.onDestroy();
3421 }
3422
Chris Banesc7d6c322016-01-27 14:09:16 +00003423 if (toolbar != null) {
3424 final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
3425 mActionBar = tbab;
3426 mWindow.setCallback(tbab.getWrappedWindowCallback());
3427 } else {
3428 mActionBar = null;
3429 // Re-set the original window callback since we may have already set a Toolbar wrapper
3430 mWindow.setCallback(this);
3431 }
3432
3433 invalidateOptionsMenu();
Adam Powelle43340c2014-03-17 19:10:43 -07003434 }
RoboErik55011652014-07-09 15:05:53 -07003435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 /**
Adam Powell33b97432010-04-20 10:01:14 -07003437 * Creates a new ActionBar, locates the inflated ActionBarView,
3438 * initializes the ActionBar with the view, and sets mActionBar.
3439 */
Adam Powelle43340c2014-03-17 19:10:43 -07003440 private void initWindowDecorActionBar() {
Adam Powell89e06452010-06-23 20:24:52 -07003441 Window window = getWindow();
Adam Powella593d982011-05-13 14:09:54 -07003442
3443 // Initializing the window decor can change window feature flags.
3444 // Make sure that we have the correct set before performing the test below.
3445 window.getDecorView();
3446
Adam Powell9b4c8042010-08-10 15:36:44 -07003447 if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
Adam Powell33b97432010-04-20 10:01:14 -07003448 return;
3449 }
Adam Powell04fe6eb2013-05-31 14:39:48 -07003450
Adam Powelle43340c2014-03-17 19:10:43 -07003451 mActionBar = new WindowDecorActionBar(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07003452 mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
Adam Powell04fe6eb2013-05-31 14:39:48 -07003453
3454 mWindow.setDefaultIcon(mActivityInfo.getIconResource());
3455 mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
Adam Powell33b97432010-04-20 10:01:14 -07003456 }
RoboErik55011652014-07-09 15:05:53 -07003457
Adam Powell33b97432010-04-20 10:01:14 -07003458 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 * Set the activity content from a layout resource. The resource will be
3460 * inflated, adding all top-level views to the activity.
Romain Guy482b34a62011-01-20 10:59:28 -08003461 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 * @param layoutResID Resource ID to be inflated.
RoboErik55011652014-07-09 15:05:53 -07003463 *
Romain Guy482b34a62011-01-20 10:59:28 -08003464 * @see #setContentView(android.view.View)
3465 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07003467 public void setContentView(@LayoutRes int layoutResID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 getWindow().setContentView(layoutResID);
Adam Powelle43340c2014-03-17 19:10:43 -07003469 initWindowDecorActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 }
3471
3472 /**
3473 * Set the activity content to an explicit view. This view is placed
3474 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08003475 * view hierarchy. When calling this method, the layout parameters of the
3476 * specified view are ignored. Both the width and the height of the view are
3477 * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use
3478 * your own layout parameters, invoke
3479 * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
3480 * instead.
RoboErik55011652014-07-09 15:05:53 -07003481 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 * @param view The desired content to display.
Romain Guy482b34a62011-01-20 10:59:28 -08003483 *
3484 * @see #setContentView(int)
3485 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 */
3487 public void setContentView(View view) {
3488 getWindow().setContentView(view);
Adam Powelle43340c2014-03-17 19:10:43 -07003489 initWindowDecorActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 }
3491
3492 /**
3493 * Set the activity content to an explicit view. This view is placed
3494 * directly into the activity's view hierarchy. It can itself be a complex
Romain Guy482b34a62011-01-20 10:59:28 -08003495 * view hierarchy.
RoboErik55011652014-07-09 15:05:53 -07003496 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 * @param view The desired content to display.
3498 * @param params Layout parameters for the view.
Romain Guy482b34a62011-01-20 10:59:28 -08003499 *
3500 * @see #setContentView(android.view.View)
3501 * @see #setContentView(int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 */
3503 public void setContentView(View view, ViewGroup.LayoutParams params) {
3504 getWindow().setContentView(view, params);
Adam Powelle43340c2014-03-17 19:10:43 -07003505 initWindowDecorActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 }
3507
3508 /**
3509 * Add an additional content view to the activity. Added after any existing
3510 * ones in the activity -- existing views are NOT removed.
RoboErik55011652014-07-09 15:05:53 -07003511 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 * @param view The desired content to display.
3513 * @param params Layout parameters for the view.
3514 */
3515 public void addContentView(View view, ViewGroup.LayoutParams params) {
3516 getWindow().addContentView(view, params);
Adam Powelle43340c2014-03-17 19:10:43 -07003517 initWindowDecorActionBar();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
3519
3520 /**
Adam Powellcfbe9be2013-11-06 14:58:58 -08003521 * Retrieve the {@link TransitionManager} responsible for default transitions in this window.
3522 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3523 *
3524 * <p>This method will return non-null after content has been initialized (e.g. by using
3525 * {@link #setContentView}) if {@link Window#FEATURE_CONTENT_TRANSITIONS} has been granted.</p>
3526 *
3527 * @return This window's content TransitionManager or null if none is set.
3528 */
3529 public TransitionManager getContentTransitionManager() {
3530 return getWindow().getTransitionManager();
3531 }
3532
3533 /**
3534 * Set the {@link TransitionManager} to use for default transitions in this window.
3535 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3536 *
3537 * @param tm The TransitionManager to use for scene changes.
3538 */
3539 public void setContentTransitionManager(TransitionManager tm) {
3540 getWindow().setTransitionManager(tm);
3541 }
3542
3543 /**
3544 * Retrieve the {@link Scene} representing this window's current content.
3545 * Requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
3546 *
3547 * <p>This method will return null if the current content is not represented by a Scene.</p>
3548 *
3549 * @return Current Scene being shown or null
3550 */
3551 public Scene getContentScene() {
3552 return getWindow().getContentScene();
3553 }
3554
3555 /**
Dianne Hackborncfaf8872011-01-18 13:57:54 -08003556 * Sets whether this activity is finished when touched outside its window's
3557 * bounds.
3558 */
3559 public void setFinishOnTouchOutside(boolean finish) {
3560 mWindow.setCloseOnTouchOutside(finish);
3561 }
Tor Norbyed9273d62013-05-30 15:59:53 -07003562
3563 /** @hide */
Jeff Sharkey6503bd82017-04-19 23:24:18 -06003564 @IntDef(prefix = { "DEFAULT_KEYS_" }, value = {
Tor Norbyed9273d62013-05-30 15:59:53 -07003565 DEFAULT_KEYS_DISABLE,
3566 DEFAULT_KEYS_DIALER,
3567 DEFAULT_KEYS_SHORTCUT,
3568 DEFAULT_KEYS_SEARCH_LOCAL,
Jeff Sharkey6503bd82017-04-19 23:24:18 -06003569 DEFAULT_KEYS_SEARCH_GLOBAL
3570 })
Tor Norbyed9273d62013-05-30 15:59:53 -07003571 @Retention(RetentionPolicy.SOURCE)
3572 @interface DefaultKeyMode {}
3573
Dianne Hackborncfaf8872011-01-18 13:57:54 -08003574 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 * Use with {@link #setDefaultKeyMode} to turn off default handling of
3576 * keys.
RoboErik55011652014-07-09 15:05:53 -07003577 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 * @see #setDefaultKeyMode
3579 */
3580 static public final int DEFAULT_KEYS_DISABLE = 0;
3581 /**
3582 * Use with {@link #setDefaultKeyMode} to launch the dialer during default
3583 * key handling.
RoboErik55011652014-07-09 15:05:53 -07003584 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 * @see #setDefaultKeyMode
3586 */
3587 static public final int DEFAULT_KEYS_DIALER = 1;
3588 /**
3589 * Use with {@link #setDefaultKeyMode} to execute a menu shortcut in
3590 * default key handling.
RoboErik55011652014-07-09 15:05:53 -07003591 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 * <p>That is, the user does not need to hold down the menu key to execute menu shortcuts.
RoboErik55011652014-07-09 15:05:53 -07003593 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 * @see #setDefaultKeyMode
3595 */
3596 static public final int DEFAULT_KEYS_SHORTCUT = 2;
3597 /**
3598 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
3599 * will start an application-defined search. (If the application or activity does not
koprivaa1a78482018-10-09 10:09:23 -07003600 * actually define a search, the keys will be ignored.)
RoboErik55011652014-07-09 15:05:53 -07003601 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
RoboErik55011652014-07-09 15:05:53 -07003603 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 * @see #setDefaultKeyMode
3605 */
3606 static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;
3607
3608 /**
3609 * Use with {@link #setDefaultKeyMode} to specify that unhandled keystrokes
3610 * will start a global search (typically web search, but some platforms may define alternate
3611 * methods for global search)
RoboErik55011652014-07-09 15:05:53 -07003612 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 * <p>See {@link android.app.SearchManager android.app.SearchManager} for more details.
RoboErik55011652014-07-09 15:05:53 -07003614 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 * @see #setDefaultKeyMode
3616 */
3617 static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;
3618
3619 /**
3620 * Select the default key handling for this activity. This controls what
3621 * will happen to key events that are not otherwise handled. The default
3622 * mode ({@link #DEFAULT_KEYS_DISABLE}) will simply drop them on the
3623 * floor. Other modes allow you to launch the dialer
3624 * ({@link #DEFAULT_KEYS_DIALER}), execute a shortcut in your options
3625 * menu without requiring the menu key be held down
RoboErik55011652014-07-09 15:05:53 -07003626 * ({@link #DEFAULT_KEYS_SHORTCUT}), or launch a search ({@link #DEFAULT_KEYS_SEARCH_LOCAL}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 * and {@link #DEFAULT_KEYS_SEARCH_GLOBAL}).
RoboErik55011652014-07-09 15:05:53 -07003628 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 * <p>Note that the mode selected here does not impact the default
3630 * handling of system keys, such as the "back" and "menu" keys, and your
3631 * activity and its views always get a first chance to receive and handle
3632 * all application keys.
RoboErik55011652014-07-09 15:05:53 -07003633 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 * @param mode The desired default key mode constant.
RoboErik55011652014-07-09 15:05:53 -07003635 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 * @see #onKeyDown
3637 */
Tor Norbyed9273d62013-05-30 15:59:53 -07003638 public final void setDefaultKeyMode(@DefaultKeyMode int mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 mDefaultKeyMode = mode;
RoboErik55011652014-07-09 15:05:53 -07003640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 // Some modes use a SpannableStringBuilder to track & dispatch input events
3642 // This list must remain in sync with the switch in onKeyDown()
3643 switch (mode) {
3644 case DEFAULT_KEYS_DISABLE:
3645 case DEFAULT_KEYS_SHORTCUT:
3646 mDefaultKeySsb = null; // not used in these modes
3647 break;
3648 case DEFAULT_KEYS_DIALER:
3649 case DEFAULT_KEYS_SEARCH_LOCAL:
3650 case DEFAULT_KEYS_SEARCH_GLOBAL:
3651 mDefaultKeySsb = new SpannableStringBuilder();
3652 Selection.setSelection(mDefaultKeySsb,0);
3653 break;
3654 default:
3655 throw new IllegalArgumentException();
3656 }
3657 }
3658
3659 /**
3660 * Called when a key was pressed down and not handled by any of the views
RoboErik55011652014-07-09 15:05:53 -07003661 * inside of the activity. So, for example, key presses while the cursor
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 * is inside a TextView will not trigger the event (unless it is a navigation
3663 * to another object) because TextView handles its own key presses.
RoboErik55011652014-07-09 15:05:53 -07003664 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 * <p>If the focused view didn't want this event, this method is called.
3666 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07003667 * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK}
3668 * by calling {@link #onBackPressed()}, though the behavior varies based
3669 * on the application compatibility mode: for
3670 * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications,
3671 * it will set up the dispatch to call {@link #onKeyUp} where the action
3672 * will be performed; for earlier applications, it will perform the
3673 * action immediately in on-down, as those versions of the platform
3674 * behaved.
RoboErik55011652014-07-09 15:05:53 -07003675 *
Dianne Hackborn8d374262009-09-14 21:21:52 -07003676 * <p>Other additional default key handling may be performed
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003677 * if configured with {@link #setDefaultKeyMode}.
RoboErik55011652014-07-09 15:05:53 -07003678 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 * @return Return <code>true</code> to prevent this event from being propagated
RoboErik55011652014-07-09 15:05:53 -07003680 * further, or <code>false</code> to indicate that you have not handled
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 * this event and it should continue to be propagated.
3682 * @see #onKeyUp
3683 * @see android.view.KeyEvent
3684 */
3685 public boolean onKeyDown(int keyCode, KeyEvent event) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003686 if (keyCode == KeyEvent.KEYCODE_BACK) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07003687 if (getApplicationInfo().targetSdkVersion
3688 >= Build.VERSION_CODES.ECLAIR) {
3689 event.startTracking();
3690 } else {
3691 onBackPressed();
3692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 return true;
3694 }
RoboErik55011652014-07-09 15:05:53 -07003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 if (mDefaultKeyMode == DEFAULT_KEYS_DISABLE) {
3697 return false;
3698 } else if (mDefaultKeyMode == DEFAULT_KEYS_SHORTCUT) {
Jose Lima7a22fc62015-01-23 17:24:22 -08003699 Window w = getWindow();
3700 if (w.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
3701 w.performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event,
3702 Menu.FLAG_ALWAYS_PERFORM_CLOSE)) {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003703 return true;
3704 }
3705 return false;
Evan Roskyc46203782017-02-17 13:11:53 -08003706 } else if (keyCode == KeyEvent.KEYCODE_TAB) {
3707 // Don't consume TAB here since it's used for navigation. Arrow keys
3708 // aren't considered "typing keys" so they already won't get consumed.
3709 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 } else {
3711 // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
3712 boolean clearSpannable = false;
3713 boolean handled;
3714 if ((event.getRepeatCount() != 0) || event.isSystem()) {
3715 clearSpannable = true;
3716 handled = false;
3717 } else {
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003718 handled = TextKeyListener.getInstance().onKeyDown(
3719 null, mDefaultKeySsb, keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 if (handled && mDefaultKeySsb.length() > 0) {
3721 // something useable has been typed - dispatch it now.
3722
3723 final String str = mDefaultKeySsb.toString();
3724 clearSpannable = true;
RoboErik55011652014-07-09 15:05:53 -07003725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 switch (mDefaultKeyMode) {
3727 case DEFAULT_KEYS_DIALER:
3728 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
3729 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
RoboErik55011652014-07-09 15:05:53 -07003730 startActivity(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 break;
3732 case DEFAULT_KEYS_SEARCH_LOCAL:
3733 startSearch(str, false, null, false);
3734 break;
3735 case DEFAULT_KEYS_SEARCH_GLOBAL:
3736 startSearch(str, false, null, true);
3737 break;
3738 }
3739 }
3740 }
3741 if (clearSpannable) {
3742 mDefaultKeySsb.clear();
3743 mDefaultKeySsb.clearSpans();
3744 Selection.setSelection(mDefaultKeySsb,0);
3745 }
3746 return handled;
3747 }
3748 }
3749
3750 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003751 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
3752 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
3753 * the event).
Siarhei Vishniakouccf973f2018-10-30 14:04:57 -07003754 *
3755 * To receive this callback, you must return true from onKeyDown for the current
3756 * event stream.
3757 *
Siarhei Vishniakouccf973f2018-10-30 14:04:57 -07003758 * @see KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003759 */
3760 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
3761 return false;
3762 }
3763
3764 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 * Called when a key was released and not handled by any of the views
RoboErik55011652014-07-09 15:05:53 -07003766 * inside of the activity. So, for example, key presses while the cursor
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 * is inside a TextView will not trigger the event (unless it is a navigation
3768 * to another object) because TextView handles its own key presses.
RoboErik55011652014-07-09 15:05:53 -07003769 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003770 * <p>The default implementation handles KEYCODE_BACK to stop the activity
3771 * and go back.
RoboErik55011652014-07-09 15:05:53 -07003772 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 * @return Return <code>true</code> to prevent this event from being propagated
RoboErik55011652014-07-09 15:05:53 -07003774 * further, or <code>false</code> to indicate that you have not handled
3775 * this event and it should continue to be propagated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 * @see #onKeyDown
3777 * @see KeyEvent
3778 */
3779 public boolean onKeyUp(int keyCode, KeyEvent event) {
Dianne Hackborn8d374262009-09-14 21:21:52 -07003780 if (getApplicationInfo().targetSdkVersion
3781 >= Build.VERSION_CODES.ECLAIR) {
3782 if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
3783 && !event.isCanceled()) {
3784 onBackPressed();
3785 return true;
3786 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 return false;
3789 }
3790
3791 /**
3792 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
3793 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
3794 * the event).
3795 */
3796 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3797 return false;
3798 }
RoboErik55011652014-07-09 15:05:53 -07003799
Mark Renouf1c25fc52019-09-09 13:13:43 -04003800 private static final class RequestFinishCallback extends IRequestFinishCallback.Stub {
3801 private final WeakReference<Activity> mActivityRef;
3802
3803 RequestFinishCallback(WeakReference<Activity> activityRef) {
3804 mActivityRef = activityRef;
3805 }
3806
3807 @Override
3808 public void requestFinish() {
3809 Activity activity = mActivityRef.get();
3810 if (activity != null) {
3811 activity.mHandler.post(activity::finishAfterTransition);
3812 }
3813 }
3814 }
3815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 /**
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003817 * Called when the activity has detected the user's press of the back
3818 * key. The default implementation simply finishes the current activity,
3819 * but you can override this to do whatever you want.
3820 */
3821 public void onBackPressed() {
Adam Powell07a74542014-05-30 15:52:44 -07003822 if (mActionBar != null && mActionBar.collapseActionView()) {
3823 return;
3824 }
3825
George Mount27b0dc02017-02-21 10:24:09 -08003826 FragmentManager fragmentManager = mFragments.getFragmentManager();
3827
Mark Renouf446251d2019-04-26 10:22:41 -04003828 if (!fragmentManager.isStateSaved() && fragmentManager.popBackStackImmediate()) {
3829 return;
3830 }
3831 if (!isTaskRoot()) {
3832 // If the activity is not the root of the task, allow finish to proceed normally.
3833 finishAfterTransition();
3834 return;
3835 }
3836 try {
3837 // Inform activity task manager that the activity received a back press
3838 // while at the root of the task. This call allows ActivityTaskManager
3839 // to intercept or defer finishing.
3840 ActivityTaskManager.getService().onBackPressedOnTaskRoot(mToken,
Mark Renouf1c25fc52019-09-09 13:13:43 -04003841 new RequestFinishCallback(new WeakReference<>(this)));
Mark Renouf446251d2019-04-26 10:22:41 -04003842 } catch (RemoteException e) {
Craig Mautner73f843d2014-05-19 09:42:28 -07003843 finishAfterTransition();
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07003844 }
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003845 }
Jeff Brown64da12a2011-01-04 19:57:47 -08003846
3847 /**
3848 * Called when a key shortcut event is not handled by any of the views in the Activity.
3849 * Override this method to implement global key shortcuts for the Activity.
3850 * Key shortcuts can also be implemented by setting the
3851 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
3852 *
3853 * @param keyCode The value in event.getKeyCode().
3854 * @param event Description of the key event.
3855 * @return True if the key shortcut was handled.
3856 */
3857 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
Abodunrinwa Tokia04b7ad2015-06-30 17:44:04 -07003858 // Let the Action Bar have a chance at handling the shortcut.
3859 ActionBar actionBar = getActionBar();
3860 return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
Jeff Brown64da12a2011-01-04 19:57:47 -08003861 }
3862
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003863 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 * Called when a touch screen event was not handled by any of the views
3865 * under it. This is most useful to process touch events that happen
3866 * outside of your window bounds, where there is no view to receive it.
RoboErik55011652014-07-09 15:05:53 -07003867 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 * @param event The touch screen event being processed.
RoboErik55011652014-07-09 15:05:53 -07003869 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 * @return Return true if you have consumed the event, false if you haven't.
3871 * The default implementation always returns false.
3872 */
3873 public boolean onTouchEvent(MotionEvent event) {
Dianne Hackborncfaf8872011-01-18 13:57:54 -08003874 if (mWindow.shouldCloseOnTouch(this, event)) {
3875 finish();
3876 return true;
3877 }
RoboErik55011652014-07-09 15:05:53 -07003878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 return false;
3880 }
RoboErik55011652014-07-09 15:05:53 -07003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 /**
3883 * Called when the trackball was moved and not handled by any of the
3884 * views inside of the activity. So, for example, if the trackball moves
3885 * while focus is on a button, you will receive a call here because
3886 * buttons do not normally do anything with trackball events. The call
3887 * here happens <em>before</em> trackball movements are converted to
3888 * DPAD key events, which then get sent back to the view hierarchy, and
3889 * will be processed at the point for things like focus navigation.
RoboErik55011652014-07-09 15:05:53 -07003890 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 * @param event The trackball event being processed.
RoboErik55011652014-07-09 15:05:53 -07003892 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 * @return Return true if you have consumed the event, false if you haven't.
3894 * The default implementation always returns false.
3895 */
3896 public boolean onTrackballEvent(MotionEvent event) {
3897 return false;
3898 }
Jeff Browncb1404e2011-01-15 18:14:15 -08003899
3900 /**
3901 * Called when a generic motion event was not handled by any of the
3902 * views inside of the activity.
3903 * <p>
Jeff Brown33bbfd22011-02-24 20:55:35 -08003904 * Generic motion events describe joystick movements, mouse hovers, track pad
3905 * touches, scroll wheel movements and other input events. The
Jeff Browncb1404e2011-01-15 18:14:15 -08003906 * {@link MotionEvent#getSource() source} of the motion event specifies
3907 * the class of input that was received. Implementations of this method
3908 * must examine the bits in the source before processing the event.
3909 * The following code example shows how this is done.
Jeff Brown33bbfd22011-02-24 20:55:35 -08003910 * </p><p>
3911 * Generic motion events with source class
3912 * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
3913 * are delivered to the view under the pointer. All other generic motion events are
3914 * delivered to the focused view.
3915 * </p><p>
3916 * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
3917 * handle this event.
Jeff Browncb1404e2011-01-15 18:14:15 -08003918 * </p>
Jeff Browncb1404e2011-01-15 18:14:15 -08003919 *
3920 * @param event The generic motion event being processed.
3921 *
3922 * @return Return true if you have consumed the event, false if you haven't.
3923 * The default implementation always returns false.
3924 */
3925 public boolean onGenericMotionEvent(MotionEvent event) {
3926 return false;
3927 }
3928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 /**
3930 * Called whenever a key, touch, or trackball event is dispatched to the
3931 * activity. Implement this method if you wish to know that the user has
3932 * interacted with the device in some way while your activity is running.
3933 * This callback and {@link #onUserLeaveHint} are intended to help
3934 * activities manage status bar notifications intelligently; specifically,
koprivaa1a78482018-10-09 10:09:23 -07003935 * for helping activities determine the proper time to cancel a notification.
RoboErik55011652014-07-09 15:05:53 -07003936 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
3938 * be accompanied by calls to {@link #onUserInteraction}. This
3939 * ensures that your activity will be told of relevant user activity such
3940 * as pulling down the notification pane and touching an item there.
RoboErik55011652014-07-09 15:05:53 -07003941 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 * <p>Note that this callback will be invoked for the touch down action
3943 * that begins a touch gesture, but may not be invoked for the touch-moved
3944 * and touch-up actions that follow.
RoboErik55011652014-07-09 15:05:53 -07003945 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 * @see #onUserLeaveHint()
3947 */
3948 public void onUserInteraction() {
3949 }
RoboErik55011652014-07-09 15:05:53 -07003950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
3952 // Update window manager if: we have a view, that view is
3953 // attached to its parent (which will be a RootView), and
3954 // this activity is not embedded.
3955 if (mParent == null) {
3956 View decor = mDecor;
3957 if (decor != null && decor.getParent() != null) {
3958 getWindowManager().updateViewLayout(decor, params);
Adam He43c06992019-04-15 15:41:49 -07003959 if (mContentCaptureManager != null) {
3960 mContentCaptureManager.updateWindowAttributes(params);
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 }
3963 }
3964 }
3965
3966 public void onContentChanged() {
3967 }
3968
3969 /**
3970 * Called when the current {@link Window} of the activity gains or loses
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07003971 * focus. This is the best indicator of whether this activity is the entity
3972 * with which the user actively interacts. The default implementation
3973 * clears the key tracking state, so should always be called.
RoboErik55011652014-07-09 15:05:53 -07003974 *
Dianne Hackborn83fe3f52009-09-12 23:38:30 -07003975 * <p>Note that this provides information about global focus state, which
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07003976 * is managed independently of activity lifecycle. As such, while focus
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 * changes will generally have some relation to lifecycle changes (an
3978 * activity that is stopped will not generally get window focus), you
3979 * should not rely on any particular order between the callbacks here and
3980 * those in the other lifecycle methods such as {@link #onResume}.
RoboErik55011652014-07-09 15:05:53 -07003981 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07003982 * <p>As a general rule, however, a foreground activity will have window
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 * focus... unless it has displayed other dialogs or popups that take
3984 * input focus, in which case the activity itself will not have focus
3985 * when the other windows have it. Likewise, the system may display
3986 * system-level windows (such as the status bar notification panel or
3987 * a system alert) which will temporarily take window input focus without
3988 * pausing the foreground activity.
3989 *
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07003990 * <p>Starting with {@link android.os.Build.VERSION_CODES#Q} there can be
3991 * multiple resumed activities at the same time in multi-window mode, so
3992 * resumed state does not guarantee window focus even if there are no
3993 * overlays above.
3994 *
3995 * <p>If the intent is to know when an activity is the topmost active, the
3996 * one the user interacted with last among all activities but not including
3997 * non-activity windows like dialogs and popups, then
3998 * {@link #onTopResumedActivityChanged(boolean)} should be used. On platform
3999 * versions prior to {@link android.os.Build.VERSION_CODES#Q},
4000 * {@link #onResume} is the best indicator.
4001 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 * @param hasFocus Whether the window of this activity has focus.
RoboErik55011652014-07-09 15:05:53 -07004003 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 * @see #hasWindowFocus()
4005 * @see #onResume
Dianne Hackborn3be63c02009-08-20 19:31:38 -07004006 * @see View#onWindowFocusChanged(boolean)
Andrii Kulian8e4df1e2019-03-19 15:17:56 -07004007 * @see #onTopResumedActivityChanged(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 */
4009 public void onWindowFocusChanged(boolean hasFocus) {
4010 }
RoboErik55011652014-07-09 15:05:53 -07004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 /**
Dianne Hackborn3be63c02009-08-20 19:31:38 -07004013 * Called when the main window associated with the activity has been
4014 * attached to the window manager.
4015 * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
4016 * for more information.
4017 * @see View#onAttachedToWindow
4018 */
4019 public void onAttachedToWindow() {
4020 }
RoboErik55011652014-07-09 15:05:53 -07004021
Dianne Hackborn3be63c02009-08-20 19:31:38 -07004022 /**
4023 * Called when the main window associated with the activity has been
4024 * detached from the window manager.
4025 * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
4026 * for more information.
4027 * @see View#onDetachedFromWindow
4028 */
4029 public void onDetachedFromWindow() {
4030 }
RoboErik55011652014-07-09 15:05:53 -07004031
Dianne Hackborn3be63c02009-08-20 19:31:38 -07004032 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 * Returns true if this activity's <em>main</em> window currently has window focus.
4034 * Note that this is not the same as the view itself having focus.
RoboErik55011652014-07-09 15:05:53 -07004035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 * @return True if this activity's main window currently has window focus.
RoboErik55011652014-07-09 15:05:53 -07004037 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
4039 */
4040 public boolean hasWindowFocus() {
4041 Window w = getWindow();
4042 if (w != null) {
4043 View d = w.getDecorView();
4044 if (d != null) {
4045 return d.hasWindowFocus();
4046 }
4047 }
4048 return false;
4049 }
Will Haldean Brownca6234e2014-02-12 10:23:41 -08004050
4051 /**
4052 * Called when the main window associated with the activity has been dismissed.
Adam Powell117b6952014-05-05 18:14:56 -07004053 * @hide
Will Haldean Brownca6234e2014-02-12 10:23:41 -08004054 */
Adam Powell117b6952014-05-05 18:14:56 -07004055 @Override
Ned Burns7d6cb912016-12-02 17:25:33 -05004056 public void onWindowDismissed(boolean finishTask, boolean suppressWindowTransition) {
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07004057 finish(finishTask ? FINISH_TASK_WITH_ACTIVITY : DONT_FINISH_TASK_WITH_ACTIVITY);
Ned Burns7d6cb912016-12-02 17:25:33 -05004058 if (suppressWindowTransition) {
4059 overridePendingTransition(0, 0);
4060 }
Will Haldean Brownca6234e2014-02-12 10:23:41 -08004061 }
RoboErik55011652014-07-09 15:05:53 -07004062
Wale Ogunwale868a5e12015-08-02 16:19:20 -07004063
Skuhnece2faa52015-08-11 10:36:38 -07004064 /**
RoboErik55011652014-07-09 15:05:53 -07004065 * Called to process key events. You can override this to intercept all
4066 * key events before they are dispatched to the window. Be sure to call
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 * this implementation for key events that should be handled normally.
RoboErik55011652014-07-09 15:05:53 -07004068 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 * @param event The key event.
RoboErik55011652014-07-09 15:05:53 -07004070 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 * @return boolean Return true if this event was consumed.
4072 */
4073 public boolean dispatchKeyEvent(KeyEvent event) {
4074 onUserInteraction();
Adam Powell07a74542014-05-30 15:52:44 -07004075
4076 // Let action bars open menus in response to the menu key prioritized over
4077 // the window handling it
George Mount5beb26172015-12-15 13:36:01 -08004078 final int keyCode = event.getKeyCode();
4079 if (keyCode == KeyEvent.KEYCODE_MENU &&
Adam Powell07a74542014-05-30 15:52:44 -07004080 mActionBar != null && mActionBar.onMenuKeyEvent(event)) {
4081 return true;
4082 }
4083
Dianne Hackborn8d374262009-09-14 21:21:52 -07004084 Window win = getWindow();
4085 if (win.superDispatchKeyEvent(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 return true;
4087 }
Dianne Hackborn8d374262009-09-14 21:21:52 -07004088 View decor = mDecor;
4089 if (decor == null) decor = win.getDecorView();
4090 return event.dispatch(this, decor != null
4091 ? decor.getKeyDispatcherState() : null, this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093
4094 /**
Jeff Brown64da12a2011-01-04 19:57:47 -08004095 * Called to process a key shortcut event.
4096 * You can override this to intercept all key shortcut events before they are
4097 * dispatched to the window. Be sure to call this implementation for key shortcut
4098 * events that should be handled normally.
4099 *
4100 * @param event The key shortcut event.
4101 * @return True if this event was consumed.
4102 */
4103 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4104 onUserInteraction();
4105 if (getWindow().superDispatchKeyShortcutEvent(event)) {
4106 return true;
4107 }
4108 return onKeyShortcut(event.getKeyCode(), event);
4109 }
4110
4111 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 * Called to process touch screen events. You can override this to
4113 * intercept all touch screen events before they are dispatched to the
4114 * window. Be sure to call this implementation for touch screen events
4115 * that should be handled normally.
RoboErik55011652014-07-09 15:05:53 -07004116 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 * @param ev The touch screen event.
RoboErik55011652014-07-09 15:05:53 -07004118 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 * @return boolean Return true if this event was consumed.
4120 */
4121 public boolean dispatchTouchEvent(MotionEvent ev) {
4122 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4123 onUserInteraction();
4124 }
4125 if (getWindow().superDispatchTouchEvent(ev)) {
4126 return true;
4127 }
4128 return onTouchEvent(ev);
4129 }
RoboErik55011652014-07-09 15:05:53 -07004130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 /**
4132 * Called to process trackball events. You can override this to
4133 * intercept all trackball events before they are dispatched to the
4134 * window. Be sure to call this implementation for trackball events
4135 * that should be handled normally.
RoboErik55011652014-07-09 15:05:53 -07004136 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 * @param ev The trackball event.
RoboErik55011652014-07-09 15:05:53 -07004138 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 * @return boolean Return true if this event was consumed.
4140 */
4141 public boolean dispatchTrackballEvent(MotionEvent ev) {
4142 onUserInteraction();
4143 if (getWindow().superDispatchTrackballEvent(ev)) {
4144 return true;
4145 }
4146 return onTrackballEvent(ev);
4147 }
svetoslavganov75986cf2009-05-14 22:28:01 -07004148
Jeff Browncb1404e2011-01-15 18:14:15 -08004149 /**
4150 * Called to process generic motion events. You can override this to
4151 * intercept all generic motion events before they are dispatched to the
4152 * window. Be sure to call this implementation for generic motion events
4153 * that should be handled normally.
4154 *
4155 * @param ev The generic motion event.
4156 *
4157 * @return boolean Return true if this event was consumed.
4158 */
4159 public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4160 onUserInteraction();
4161 if (getWindow().superDispatchGenericMotionEvent(ev)) {
4162 return true;
4163 }
4164 return onGenericMotionEvent(ev);
4165 }
4166
svetoslavganov75986cf2009-05-14 22:28:01 -07004167 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4168 event.setClassName(getClass().getName());
4169 event.setPackageName(getPackageName());
4170
4171 LayoutParams params = getWindow().getAttributes();
Romain Guy980a9382010-01-08 15:06:28 -08004172 boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
4173 (params.height == LayoutParams.MATCH_PARENT);
svetoslavganov75986cf2009-05-14 22:28:01 -07004174 event.setFullScreen(isFullScreen);
4175
4176 CharSequence title = getTitle();
4177 if (!TextUtils.isEmpty(title)) {
4178 event.getText().add(title);
4179 }
4180
4181 return true;
4182 }
4183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 /**
4185 * Default implementation of
4186 * {@link android.view.Window.Callback#onCreatePanelView}
4187 * for activities. This
4188 * simply returns null so that all panel sub-windows will have the default
4189 * menu behavior.
4190 */
Tor Norbyed9273d62013-05-30 15:59:53 -07004191 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 public View onCreatePanelView(int featureId) {
4193 return null;
4194 }
4195
4196 /**
4197 * Default implementation of
4198 * {@link android.view.Window.Callback#onCreatePanelMenu}
4199 * for activities. This calls through to the new
4200 * {@link #onCreateOptionsMenu} method for the
4201 * {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
4202 * so that subclasses of Activity don't need to deal with feature codes.
4203 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004204 public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004206 boolean show = onCreateOptionsMenu(menu);
4207 show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
4208 return show;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 }
4210 return false;
4211 }
4212
4213 /**
4214 * Default implementation of
4215 * {@link android.view.Window.Callback#onPreparePanel}
4216 * for activities. This
4217 * calls through to the new {@link #onPrepareOptionsMenu} method for the
4218 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
4219 * panel, so that subclasses of
4220 * Activity don't need to deal with feature codes.
4221 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004222 public boolean onPreparePanel(int featureId, @Nullable View view, @NonNull Menu menu) {
4223 if (featureId == Window.FEATURE_OPTIONS_PANEL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 boolean goforit = onPrepareOptionsMenu(menu);
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004225 goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
Adam Powellef31e7c2012-05-08 09:59:40 -07004226 return goforit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228 return true;
4229 }
4230
4231 /**
4232 * {@inheritDoc}
RoboErik55011652014-07-09 15:05:53 -07004233 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 * @return The default implementation returns true.
4235 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004236 @Override
4237 public boolean onMenuOpened(int featureId, @NonNull Menu menu) {
Adam Powell8515ee82010-11-30 14:09:55 -08004238 if (featureId == Window.FEATURE_ACTION_BAR) {
Adam Powelle43340c2014-03-17 19:10:43 -07004239 initWindowDecorActionBar();
Adam Powell049dd3d2010-12-02 13:43:59 -08004240 if (mActionBar != null) {
4241 mActionBar.dispatchMenuVisibilityChanged(true);
4242 } else {
4243 Log.e(TAG, "Tried to open action bar menu with no action bar");
4244 }
Adam Powell8515ee82010-11-30 14:09:55 -08004245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 return true;
4247 }
4248
4249 /**
4250 * Default implementation of
4251 * {@link android.view.Window.Callback#onMenuItemSelected}
4252 * for activities. This calls through to the new
4253 * {@link #onOptionsItemSelected} method for the
4254 * {@link android.view.Window#FEATURE_OPTIONS_PANEL}
4255 * panel, so that subclasses of
4256 * Activity don't need to deal with feature codes.
4257 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004258 public boolean onMenuItemSelected(int featureId, @NonNull MenuItem item) {
zobject686a8052012-12-14 21:11:08 +09004259 CharSequence titleCondensed = item.getTitleCondensed();
4260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 switch (featureId) {
4262 case Window.FEATURE_OPTIONS_PANEL:
4263 // Put event logging here so it gets called even if subclass
4264 // doesn't call through to superclass's implmeentation of each
4265 // of these methods below
zobject686a8052012-12-14 21:11:08 +09004266 if(titleCondensed != null) {
4267 EventLog.writeEvent(50000, 0, titleCondensed.toString());
4268 }
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004269 if (onOptionsItemSelected(item)) {
4270 return true;
4271 }
Adam Powell04d58112012-04-09 10:22:12 -07004272 if (mFragments.dispatchOptionsItemSelected(item)) {
4273 return true;
4274 }
4275 if (item.getItemId() == android.R.id.home && mActionBar != null &&
4276 (mActionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
4277 if (mParent == null) {
Adam Powell07304f5292012-05-07 17:32:44 -07004278 return onNavigateUp();
Adam Powell04d58112012-04-09 10:22:12 -07004279 } else {
Adam Powell07304f5292012-05-07 17:32:44 -07004280 return mParent.onNavigateUpFromChild(this);
Adam Powell04d58112012-04-09 10:22:12 -07004281 }
Adam Powell04d58112012-04-09 10:22:12 -07004282 }
4283 return false;
RoboErik55011652014-07-09 15:05:53 -07004284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 case Window.FEATURE_CONTEXT_MENU:
zobject686a8052012-12-14 21:11:08 +09004286 if(titleCondensed != null) {
4287 EventLog.writeEvent(50000, 1, titleCondensed.toString());
4288 }
Dianne Hackborn5ddd1272010-06-12 10:15:28 -07004289 if (onContextItemSelected(item)) {
4290 return true;
4291 }
4292 return mFragments.dispatchContextItemSelected(item);
Adam Powell8515ee82010-11-30 14:09:55 -08004293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 default:
4295 return false;
4296 }
4297 }
RoboErik55011652014-07-09 15:05:53 -07004298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 /**
4300 * Default implementation of
4301 * {@link android.view.Window.Callback#onPanelClosed(int, Menu)} for
4302 * activities. This calls through to {@link #onOptionsMenuClosed(Menu)}
4303 * method for the {@link android.view.Window#FEATURE_OPTIONS_PANEL} panel,
4304 * so that subclasses of Activity don't need to deal with feature codes.
4305 * For context menus ({@link Window#FEATURE_CONTEXT_MENU}), the
4306 * {@link #onContextMenuClosed(Menu)} will be called.
4307 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004308 public void onPanelClosed(int featureId, @NonNull Menu menu) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 switch (featureId) {
4310 case Window.FEATURE_OPTIONS_PANEL:
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004311 mFragments.dispatchOptionsMenuClosed(menu);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 onOptionsMenuClosed(menu);
4313 break;
RoboErik55011652014-07-09 15:05:53 -07004314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 case Window.FEATURE_CONTEXT_MENU:
4316 onContextMenuClosed(menu);
4317 break;
Adam Powell8515ee82010-11-30 14:09:55 -08004318
4319 case Window.FEATURE_ACTION_BAR:
Adam Powelle43340c2014-03-17 19:10:43 -07004320 initWindowDecorActionBar();
Adam Powell8515ee82010-11-30 14:09:55 -08004321 mActionBar.dispatchMenuVisibilityChanged(false);
4322 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 }
4324 }
4325
4326 /**
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004327 * Declare that the options menu has changed, so should be recreated.
4328 * The {@link #onCreateOptionsMenu(Menu)} method will be called the next
4329 * time it needs to be displayed.
4330 */
4331 public void invalidateOptionsMenu() {
Jose Lima7a22fc62015-01-23 17:24:22 -08004332 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4333 (mActionBar == null || !mActionBar.invalidateOptionsMenu())) {
Adam Powell07a74542014-05-30 15:52:44 -07004334 mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
4335 }
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004336 }
RoboErik55011652014-07-09 15:05:53 -07004337
Dianne Hackbornb31e84bc2010-06-08 18:04:35 -07004338 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 * Initialize the contents of the Activity's standard options menu. You
4340 * should place your menu items in to <var>menu</var>.
RoboErik55011652014-07-09 15:05:53 -07004341 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 * <p>This is only called once, the first time the options menu is
4343 * displayed. To update the menu every time it is displayed, see
4344 * {@link #onPrepareOptionsMenu}.
RoboErik55011652014-07-09 15:05:53 -07004345 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 * <p>The default implementation populates the menu with standard system
RoboErik55011652014-07-09 15:05:53 -07004347 * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that
4348 * they will be correctly ordered with application-defined menu items.
4349 * Deriving classes should always call through to the base implementation.
4350 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 * <p>You can safely hold on to <var>menu</var> (and any items created
4352 * from it), making modifications to it as desired, until the next
4353 * time onCreateOptionsMenu() is called.
RoboErik55011652014-07-09 15:05:53 -07004354 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 * <p>When you add items to the menu, you can implement the Activity's
4356 * {@link #onOptionsItemSelected} method to handle them there.
RoboErik55011652014-07-09 15:05:53 -07004357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 * @param menu The options menu in which you place your items.
RoboErik55011652014-07-09 15:05:53 -07004359 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 * @return You must return true for the menu to be displayed;
4361 * if you return false it will not be shown.
RoboErik55011652014-07-09 15:05:53 -07004362 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 * @see #onPrepareOptionsMenu
4364 * @see #onOptionsItemSelected
4365 */
4366 public boolean onCreateOptionsMenu(Menu menu) {
4367 if (mParent != null) {
4368 return mParent.onCreateOptionsMenu(menu);
4369 }
4370 return true;
4371 }
4372
4373 /**
4374 * Prepare the Screen's standard options menu to be displayed. This is
4375 * called right before the menu is shown, every time it is shown. You can
4376 * use this method to efficiently enable/disable items or otherwise
4377 * dynamically modify the contents.
RoboErik55011652014-07-09 15:05:53 -07004378 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 * <p>The default implementation updates the system menu items based on the
4380 * activity's state. Deriving classes should always call through to the
4381 * base class implementation.
RoboErik55011652014-07-09 15:05:53 -07004382 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 * @param menu The options menu as last shown or first initialized by
4384 * onCreateOptionsMenu().
RoboErik55011652014-07-09 15:05:53 -07004385 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 * @return You must return true for the menu to be displayed;
4387 * if you return false it will not be shown.
RoboErik55011652014-07-09 15:05:53 -07004388 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 * @see #onCreateOptionsMenu
4390 */
4391 public boolean onPrepareOptionsMenu(Menu menu) {
4392 if (mParent != null) {
4393 return mParent.onPrepareOptionsMenu(menu);
4394 }
4395 return true;
4396 }
4397
4398 /**
4399 * This hook is called whenever an item in your options menu is selected.
4400 * The default implementation simply returns false to have the normal
4401 * processing happen (calling the item's Runnable or sending a message to
4402 * its Handler as appropriate). You can use this method for any items
4403 * for which you would like to do processing without those other
4404 * facilities.
RoboErik55011652014-07-09 15:05:53 -07004405 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 * <p>Derived classes should call through to the base class for it to
Adam Powelldd8fab22012-03-22 17:47:27 -07004407 * perform the default menu handling.</p>
RoboErik55011652014-07-09 15:05:53 -07004408 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 * @param item The menu item that was selected.
RoboErik55011652014-07-09 15:05:53 -07004410 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 * @return boolean Return false to allow normal menu processing to
4412 * proceed, true to consume it here.
RoboErik55011652014-07-09 15:05:53 -07004413 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 * @see #onCreateOptionsMenu
4415 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004416 public boolean onOptionsItemSelected(@NonNull MenuItem item) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 if (mParent != null) {
4418 return mParent.onOptionsItemSelected(item);
4419 }
4420 return false;
4421 }
4422
4423 /**
Adam Powelldd8fab22012-03-22 17:47:27 -07004424 * This method is called whenever the user chooses to navigate Up within your application's
4425 * activity hierarchy from the action bar.
4426 *
4427 * <p>If the attribute {@link android.R.attr#parentActivityName parentActivityName}
4428 * was specified in the manifest for this activity or an activity-alias to it,
4429 * default Up navigation will be handled automatically. If any activity
4430 * along the parent chain requires extra Intent arguments, the Activity subclass
4431 * should override the method {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}
4432 * to supply those arguments.</p>
4433 *
Mark Lufa434852016-08-11 17:40:33 -07004434 * <p>See <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
Adam Powelldd8fab22012-03-22 17:47:27 -07004435 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
4436 * from the design guide for more information about navigating within your app.</p>
4437 *
4438 * <p>See the {@link TaskStackBuilder} class and the Activity methods
4439 * {@link #getParentActivityIntent()}, {@link #shouldUpRecreateTask(Intent)}, and
4440 * {@link #navigateUpTo(Intent)} for help implementing custom Up navigation.
4441 * The AppNavigation sample application in the Android SDK is also available for reference.</p>
4442 *
4443 * @return true if Up navigation completed successfully and this Activity was finished,
4444 * false otherwise.
4445 */
4446 public boolean onNavigateUp() {
4447 // Automatically handle hierarchical Up navigation if the proper
4448 // metadata is available.
4449 Intent upIntent = getParentActivityIntent();
4450 if (upIntent != null) {
Adam Powell0fc5b2b2012-07-18 18:20:29 -07004451 if (mActivityInfo.taskAffinity == null) {
4452 // Activities with a null affinity are special; they really shouldn't
4453 // specify a parent activity intent in the first place. Just finish
4454 // the current activity and call it a day.
4455 finish();
4456 } else if (shouldUpRecreateTask(upIntent)) {
Adam Powellf78a8442012-05-01 18:09:32 -07004457 TaskStackBuilder b = TaskStackBuilder.create(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07004458 onCreateNavigateUpTaskStack(b);
4459 onPrepareNavigateUpTaskStack(b);
4460 b.startActivities();
Adam Powell3d193d92012-05-15 16:51:55 -07004461
4462 // We can't finishAffinity if we have a result.
4463 // Fall back and simply finish the current activity instead.
4464 if (mResultCode != RESULT_CANCELED || mResultData != null) {
4465 // Tell the developer what's going on to avoid hair-pulling.
4466 Log.i(TAG, "onNavigateUp only finishing topmost activity to return a result");
4467 finish();
4468 } else {
4469 finishAffinity();
4470 }
Adam Powelldd8fab22012-03-22 17:47:27 -07004471 } else {
4472 navigateUpTo(upIntent);
4473 }
4474 return true;
4475 }
4476 return false;
4477 }
4478
4479 /**
4480 * This is called when a child activity of this one attempts to navigate up.
4481 * The default implementation simply calls onNavigateUp() on this activity (the parent).
4482 *
4483 * @param child The activity making the call.
Charles Chenc380f022019-08-13 18:39:17 +08004484 * @deprecated Use {@link #onNavigateUp()} instead.
Adam Powelldd8fab22012-03-22 17:47:27 -07004485 */
Charles Chenc380f022019-08-13 18:39:17 +08004486 @Deprecated
Adam Powelldd8fab22012-03-22 17:47:27 -07004487 public boolean onNavigateUpFromChild(Activity child) {
4488 return onNavigateUp();
4489 }
4490
4491 /**
4492 * Define the synthetic task stack that will be generated during Up navigation from
4493 * a different task.
4494 *
4495 * <p>The default implementation of this method adds the parent chain of this activity
4496 * as specified in the manifest to the supplied {@link TaskStackBuilder}. Applications
4497 * may choose to override this method to construct the desired task stack in a different
4498 * way.</p>
4499 *
Adam Powellf0195952012-05-02 21:38:54 -07004500 * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()}
4501 * if {@link #shouldUpRecreateTask(Intent)} returns true when supplied with the intent
4502 * returned by {@link #getParentActivityIntent()}.</p>
4503 *
Adam Powelldd8fab22012-03-22 17:47:27 -07004504 * <p>Applications that wish to supply extra Intent parameters to the parent stack defined
4505 * by the manifest should override {@link #onPrepareNavigateUpTaskStack(TaskStackBuilder)}.</p>
4506 *
4507 * @param builder An empty TaskStackBuilder - the application should add intents representing
4508 * the desired task stack
4509 */
4510 public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
4511 builder.addParentStack(this);
4512 }
4513
4514 /**
4515 * Prepare the synthetic task stack that will be generated during Up navigation
4516 * from a different task.
4517 *
4518 * <p>This method receives the {@link TaskStackBuilder} with the constructed series of
4519 * Intents as generated by {@link #onCreateNavigateUpTaskStack(TaskStackBuilder)}.
4520 * If any extra data should be added to these intents before launching the new task,
4521 * the application should override this method and add that data here.</p>
4522 *
4523 * @param builder A TaskStackBuilder that has been populated with Intents by
4524 * onCreateNavigateUpTaskStack.
4525 */
4526 public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
4527 }
4528
4529 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 * This hook is called whenever the options menu is being closed (either by the user canceling
4531 * the menu with the back/menu button, or when an item is selected).
RoboErik55011652014-07-09 15:05:53 -07004532 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 * @param menu The options menu as last shown or first initialized by
4534 * onCreateOptionsMenu().
4535 */
4536 public void onOptionsMenuClosed(Menu menu) {
4537 if (mParent != null) {
4538 mParent.onOptionsMenuClosed(menu);
4539 }
4540 }
RoboErik55011652014-07-09 15:05:53 -07004541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 /**
4543 * Programmatically opens the options menu. If the options menu is already
4544 * open, this method does nothing.
4545 */
4546 public void openOptionsMenu() {
Jose Lima7a22fc62015-01-23 17:24:22 -08004547 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4548 (mActionBar == null || !mActionBar.openOptionsMenu())) {
Adam Powell07a74542014-05-30 15:52:44 -07004549 mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
4550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 }
RoboErik55011652014-07-09 15:05:53 -07004552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 /**
4554 * Progammatically closes the options menu. If the options menu is already
4555 * closed, this method does nothing.
4556 */
4557 public void closeOptionsMenu() {
Evan Rosky41823d12017-03-21 14:42:35 -07004558 if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) &&
4559 (mActionBar == null || !mActionBar.closeOptionsMenu())) {
Jose Lima7a22fc62015-01-23 17:24:22 -08004560 mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
4561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 }
4563
4564 /**
4565 * Called when a context menu for the {@code view} is about to be shown.
4566 * Unlike {@link #onCreateOptionsMenu(Menu)}, this will be called every
4567 * time the context menu is about to be shown and should be populated for
4568 * the view (or item inside the view for {@link AdapterView} subclasses,
4569 * this can be found in the {@code menuInfo})).
4570 * <p>
4571 * Use {@link #onContextItemSelected(android.view.MenuItem)} to know when an
4572 * item has been selected.
4573 * <p>
4574 * It is not safe to hold onto the context menu after this method returns.
Scott Maincdf51062013-01-08 20:03:05 -08004575 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 */
4577 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
4578 }
4579
4580 /**
4581 * Registers a context menu to be shown for the given view (multiple views
4582 * can show the context menu). This method will set the
4583 * {@link OnCreateContextMenuListener} on the view to this activity, so
4584 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
4585 * called when it is time to show the context menu.
RoboErik55011652014-07-09 15:05:53 -07004586 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 * @see #unregisterForContextMenu(View)
4588 * @param view The view that should show a context menu.
4589 */
4590 public void registerForContextMenu(View view) {
4591 view.setOnCreateContextMenuListener(this);
4592 }
RoboErik55011652014-07-09 15:05:53 -07004593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 /**
4595 * Prevents a context menu to be shown for the given view. This method will remove the
4596 * {@link OnCreateContextMenuListener} on the view.
RoboErik55011652014-07-09 15:05:53 -07004597 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 * @see #registerForContextMenu(View)
4599 * @param view The view that should stop showing a context menu.
4600 */
4601 public void unregisterForContextMenu(View view) {
4602 view.setOnCreateContextMenuListener(null);
4603 }
RoboErik55011652014-07-09 15:05:53 -07004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 /**
4606 * Programmatically opens the context menu for a particular {@code view}.
4607 * The {@code view} should have been added via
4608 * {@link #registerForContextMenu(View)}.
RoboErik55011652014-07-09 15:05:53 -07004609 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 * @param view The view to show the context menu for.
4611 */
4612 public void openContextMenu(View view) {
4613 view.showContextMenu();
4614 }
RoboErik55011652014-07-09 15:05:53 -07004615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 /**
4617 * Programmatically closes the most recently opened context menu, if showing.
4618 */
4619 public void closeContextMenu() {
Jose Limabd769a12015-01-28 10:43:15 -08004620 if (mWindow.hasFeature(Window.FEATURE_CONTEXT_MENU)) {
4621 mWindow.closePanel(Window.FEATURE_CONTEXT_MENU);
4622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
RoboErik55011652014-07-09 15:05:53 -07004624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 /**
4626 * This hook is called whenever an item in a context menu is selected. The
4627 * default implementation simply returns false to have the normal processing
4628 * happen (calling the item's Runnable or sending a message to its Handler
4629 * as appropriate). You can use this method for any items for which you
4630 * would like to do processing without those other facilities.
4631 * <p>
4632 * Use {@link MenuItem#getMenuInfo()} to get extra information set by the
4633 * View that added this menu item.
4634 * <p>
4635 * Derived classes should call through to the base class for it to perform
4636 * the default menu handling.
RoboErik55011652014-07-09 15:05:53 -07004637 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 * @param item The context menu item that was selected.
4639 * @return boolean Return false to allow normal context menu processing to
4640 * proceed, true to consume it here.
4641 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004642 public boolean onContextItemSelected(@NonNull MenuItem item) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 if (mParent != null) {
4644 return mParent.onContextItemSelected(item);
4645 }
4646 return false;
4647 }
4648
4649 /**
4650 * This hook is called whenever the context menu is being closed (either by
4651 * the user canceling the menu with the back/menu button, or when an item is
4652 * selected).
RoboErik55011652014-07-09 15:05:53 -07004653 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 * @param menu The context menu that is being closed.
4655 */
Ian Lake0b71b8e2018-09-13 13:56:26 -07004656 public void onContextMenuClosed(@NonNull Menu menu) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 if (mParent != null) {
4658 mParent.onContextMenuClosed(menu);
4659 }
4660 }
4661
4662 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004663 * @deprecated Old no-arguments version of {@link #onCreateDialog(int, Bundle)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 */
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004665 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666 protected Dialog onCreateDialog(int id) {
4667 return null;
4668 }
4669
4670 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004671 * Callback for creating dialogs that are managed (saved and restored) for you
4672 * by the activity. The default implementation calls through to
4673 * {@link #onCreateDialog(int)} for compatibility.
4674 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07004675 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
4676 * or later, consider instead using a {@link DialogFragment} instead.</em>
4677 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004678 * <p>If you use {@link #showDialog(int)}, the activity will call through to
4679 * this method the first time, and hang onto it thereafter. Any dialog
4680 * that is created by this method will automatically be saved and restored
4681 * for you, including whether it is showing.
4682 *
4683 * <p>If you would like the activity to manage saving and restoring dialogs
4684 * for you, you should override this method and handle any ids that are
4685 * passed to {@link #showDialog}.
4686 *
4687 * <p>If you would like an opportunity to prepare your dialog before it is shown,
4688 * override {@link #onPrepareDialog(int, Dialog, Bundle)}.
4689 *
4690 * @param id The id of the dialog.
4691 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
4692 * @return The dialog. If you return null, the dialog will not be created.
4693 *
4694 * @see #onPrepareDialog(int, Dialog, Bundle)
4695 * @see #showDialog(int, Bundle)
4696 * @see #dismissDialog(int)
4697 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004698 *
4699 * @deprecated Use the new {@link DialogFragment} class with
4700 * {@link FragmentManager} instead; this is also
4701 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004702 */
Tor Norbyed9273d62013-05-30 15:59:53 -07004703 @Nullable
Dianne Hackborn9567a662011-04-19 18:44:03 -07004704 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004705 protected Dialog onCreateDialog(int id, Bundle args) {
4706 return onCreateDialog(id);
4707 }
4708
4709 /**
4710 * @deprecated Old no-arguments version of
4711 * {@link #onPrepareDialog(int, Dialog, Bundle)}.
4712 */
4713 @Deprecated
4714 protected void onPrepareDialog(int id, Dialog dialog) {
4715 dialog.setOwnerActivity(this);
4716 }
4717
4718 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 * Provides an opportunity to prepare a managed dialog before it is being
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004720 * shown. The default implementation calls through to
4721 * {@link #onPrepareDialog(int, Dialog)} for compatibility.
RoboErik55011652014-07-09 15:05:53 -07004722 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 * <p>
4724 * Override this if you need to update a managed dialog based on the state
4725 * of the application each time it is shown. For example, a time picker
4726 * dialog might want to be updated with the current time. You should call
4727 * through to the superclass's implementation. The default implementation
4728 * will set this Activity as the owner activity on the Dialog.
RoboErik55011652014-07-09 15:05:53 -07004729 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 * @param id The id of the managed dialog.
4731 * @param dialog The dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004732 * @param args The dialog arguments provided to {@link #showDialog(int, Bundle)}.
4733 * @see #onCreateDialog(int, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 * @see #showDialog(int)
4735 * @see #dismissDialog(int)
4736 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004737 *
4738 * @deprecated Use the new {@link DialogFragment} class with
4739 * {@link FragmentManager} instead; this is also
4740 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07004742 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004743 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
4744 onPrepareDialog(id, dialog);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 }
4746
4747 /**
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004748 * Simple version of {@link #showDialog(int, Bundle)} that does not
4749 * take any arguments. Simply calls {@link #showDialog(int, Bundle)}
4750 * with null arguments.
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004751 *
4752 * @deprecated Use the new {@link DialogFragment} class with
4753 * {@link FragmentManager} instead; this is also
4754 * available on older platforms through the Android compatibility package.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004755 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07004756 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004757 public final void showDialog(int id) {
4758 showDialog(id, null);
4759 }
4760
4761 /**
4762 * Show a dialog managed by this activity. A call to {@link #onCreateDialog(int, Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 * will be made with the same id the first time this is called for a given
4764 * id. From thereafter, the dialog will be automatically saved and restored.
4765 *
Dianne Hackborn291905e2010-08-17 15:17:15 -07004766 * <em>If you are targeting {@link android.os.Build.VERSION_CODES#HONEYCOMB}
4767 * or later, consider instead using a {@link DialogFragment} instead.</em>
4768 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004769 * <p>Each time a dialog is shown, {@link #onPrepareDialog(int, Dialog, Bundle)} will
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 * be made to provide an opportunity to do any timely preparation.
4771 *
4772 * @param id The id of the managed dialog.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004773 * @param args Arguments to pass through to the dialog. These will be saved
4774 * and restored for you. Note that if the dialog is already created,
4775 * {@link #onCreateDialog(int, Bundle)} will not be called with the new
4776 * arguments but {@link #onPrepareDialog(int, Dialog, Bundle)} will be.
Dianne Hackbornd47c6ed2010-01-27 16:21:20 -08004777 * If you need to rebuild the dialog, call {@link #removeDialog(int)} first.
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004778 * @return Returns true if the Dialog was created; false is returned if
4779 * it is not created because {@link #onCreateDialog(int, Bundle)} returns false.
RoboErik55011652014-07-09 15:05:53 -07004780 *
Joe Onorato37296dc2009-07-31 17:58:55 -07004781 * @see Dialog
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004782 * @see #onCreateDialog(int, Bundle)
4783 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 * @see #dismissDialog(int)
4785 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004786 *
4787 * @deprecated Use the new {@link DialogFragment} class with
4788 * {@link FragmentManager} instead; this is also
4789 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07004791 @Deprecated
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004792 public final boolean showDialog(int id, Bundle args) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 if (mManagedDialogs == null) {
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004794 mManagedDialogs = new SparseArray<ManagedDialog>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004796 ManagedDialog md = mManagedDialogs.get(id);
4797 if (md == null) {
4798 md = new ManagedDialog();
4799 md.mDialog = createDialog(id, null, args);
4800 if (md.mDialog == null) {
4801 return false;
4802 }
4803 mManagedDialogs.put(id, md);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 }
RoboErik55011652014-07-09 15:05:53 -07004805
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004806 md.mArgs = args;
4807 onPrepareDialog(id, md.mDialog, args);
4808 md.mDialog.show();
4809 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 }
4811
4812 /**
4813 * Dismiss a dialog that was previously shown via {@link #showDialog(int)}.
4814 *
4815 * @param id The id of the managed dialog.
4816 *
4817 * @throws IllegalArgumentException if the id was not previously shown via
4818 * {@link #showDialog(int)}.
4819 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004820 * @see #onCreateDialog(int, Bundle)
4821 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 * @see #showDialog(int)
4823 * @see #removeDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004824 *
4825 * @deprecated Use the new {@link DialogFragment} class with
4826 * {@link FragmentManager} instead; this is also
4827 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07004829 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 public final void dismissDialog(int id) {
4831 if (mManagedDialogs == null) {
4832 throw missingDialog(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 }
RoboErik55011652014-07-09 15:05:53 -07004834
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004835 final ManagedDialog md = mManagedDialogs.get(id);
4836 if (md == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 throw missingDialog(id);
4838 }
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004839 md.mDialog.dismiss();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 }
4841
4842 /**
4843 * Creates an exception to throw if a user passed in a dialog id that is
4844 * unexpected.
4845 */
4846 private IllegalArgumentException missingDialog(int id) {
4847 return new IllegalArgumentException("no dialog with id " + id + " was ever "
4848 + "shown via Activity#showDialog");
4849 }
4850
4851 /**
4852 * Removes any internal references to a dialog managed by this Activity.
4853 * If the dialog is showing, it will dismiss it as part of the clean up.
4854 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004855 * <p>This can be useful if you know that you will never show a dialog again and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004856 * want to avoid the overhead of saving and restoring it in the future.
4857 *
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07004858 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, this function
4859 * will not throw an exception if you try to remove an ID that does not
4860 * currently have an associated dialog.</p>
RoboErik55011652014-07-09 15:05:53 -07004861 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004862 * @param id The id of the managed dialog.
4863 *
Dianne Hackborn8ea138c2010-01-26 18:01:04 -08004864 * @see #onCreateDialog(int, Bundle)
4865 * @see #onPrepareDialog(int, Dialog, Bundle)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 * @see #showDialog(int)
4867 * @see #dismissDialog(int)
Dianne Hackborn271c2fe2011-08-09 19:35:13 -07004868 *
4869 * @deprecated Use the new {@link DialogFragment} class with
4870 * {@link FragmentManager} instead; this is also
4871 * available on older platforms through the Android compatibility package.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 */
Dianne Hackborn9567a662011-04-19 18:44:03 -07004873 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004874 public final void removeDialog(int id) {
Dianne Hackbornd2ce8bbb2010-10-06 16:46:05 -07004875 if (mManagedDialogs != null) {
4876 final ManagedDialog md = mManagedDialogs.get(id);
4877 if (md != null) {
4878 md.mDialog.dismiss();
4879 mManagedDialogs.remove(id);
4880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 }
4883
4884 /**
4885 * This hook is called when the user signals the desire to start a search.
RoboErik55011652014-07-09 15:05:53 -07004886 *
Bjorn Bringert6266e402009-09-25 14:25:41 +01004887 * <p>You can use this function as a simple way to launch the search UI, in response to a
RoboErik55011652014-07-09 15:05:53 -07004888 * menu item, search button, or other widgets within your activity. Unless overidden,
Bjorn Bringert6266e402009-09-25 14:25:41 +01004889 * calling this function is the same as calling
4890 * {@link #startSearch startSearch(null, false, null, false)}, which launches
4891 * search for the current activity as specified in its manifest, see {@link SearchManager}.
RoboErik55011652014-07-09 15:05:53 -07004892 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004893 * <p>You can override this function to force global search, e.g. in response to a dedicated
4894 * search key, or to block search entirely (by simply returning false).
RoboErik55011652014-07-09 15:05:53 -07004895 *
Erik Wolsheimerac5cecd2017-12-05 13:11:50 -08004896 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_TELEVISION} or
4897 * {@link Configuration#UI_MODE_TYPE_WATCH}, the default implementation changes to simply
4898 * return false and you must supply your own custom implementation if you want to support
4899 * search.
Dianne Hackbornfdf5b352014-10-08 17:43:48 -07004900 *
Tim Kilbourn6a975b32015-04-09 17:14:34 -07004901 * @param searchEvent The {@link SearchEvent} that signaled this search.
Dianne Hackbornfdf5b352014-10-08 17:43:48 -07004902 * @return Returns {@code true} if search launched, and {@code false} if the activity does
4903 * not respond to search. The default implementation always returns {@code true}, except
4904 * when in {@link Configuration#UI_MODE_TYPE_TELEVISION} mode where it returns false.
RoboErik55011652014-07-09 15:05:53 -07004905 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 * @see android.app.SearchManager
4907 */
Tim Kilbourn6a975b32015-04-09 17:14:34 -07004908 public boolean onSearchRequested(@Nullable SearchEvent searchEvent) {
4909 mSearchEvent = searchEvent;
4910 boolean result = onSearchRequested();
4911 mSearchEvent = null;
4912 return result;
4913 }
4914
4915 /**
4916 * @see #onSearchRequested(SearchEvent)
4917 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 public boolean onSearchRequested() {
Erik Wolsheimerac5cecd2017-12-05 13:11:50 -08004919 final int uiMode = getResources().getConfiguration().uiMode
4920 & Configuration.UI_MODE_TYPE_MASK;
4921 if (uiMode != Configuration.UI_MODE_TYPE_TELEVISION
4922 && uiMode != Configuration.UI_MODE_TYPE_WATCH) {
Dianne Hackbornfdf5b352014-10-08 17:43:48 -07004923 startSearch(null, false, null, false);
4924 return true;
4925 } else {
4926 return false;
4927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004928 }
RoboErik55011652014-07-09 15:05:53 -07004929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 /**
Tim Kilbourn6a975b32015-04-09 17:14:34 -07004931 * During the onSearchRequested() callbacks, this function will return the
4932 * {@link SearchEvent} that triggered the callback, if it exists.
4933 *
4934 * @return SearchEvent The SearchEvent that triggered the {@link
4935 * #onSearchRequested} callback.
4936 */
4937 public final SearchEvent getSearchEvent() {
4938 return mSearchEvent;
4939 }
4940
4941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 * This hook is called to launch the search UI.
RoboErik55011652014-07-09 15:05:53 -07004943 *
4944 * <p>It is typically called from onSearchRequested(), either directly from
4945 * Activity.onSearchRequested() or from an overridden version in any given
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 * Activity. If your goal is simply to activate search, it is preferred to call
Tor Norbyed9273d62013-05-30 15:59:53 -07004947 * onSearchRequested(), which may have been overridden elsewhere in your Activity. If your goal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 * is to inject specific data such as context data, it is preferred to <i>override</i>
4949 * onSearchRequested(), so that any callers to it will benefit from the override.
RoboErik55011652014-07-09 15:05:53 -07004950 *
Erik Wolsheimerac5cecd2017-12-05 13:11:50 -08004951 * <p>Note: when running in a {@link Configuration#UI_MODE_TYPE_WATCH}, use of this API is
4952 * not supported.
4953 *
RoboErik55011652014-07-09 15:05:53 -07004954 * @param initialQuery Any non-null non-empty string will be inserted as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 * pre-entered text in the search query box.
Tor Norbyed9273d62013-05-30 15:59:53 -07004956 * @param selectInitialQuery If true, the initial query will be preselected, which means that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 * any further typing will replace it. This is useful for cases where an entire pre-formed
4958 * query is being inserted. If false, the selection point will be placed at the end of the
4959 * inserted query. This is useful when the inserted query is text that the user entered,
4960 * and the user would expect to be able to keep typing. <i>This parameter is only meaningful
4961 * if initialQuery is a non-empty string.</i>
RoboErik55011652014-07-09 15:05:53 -07004962 * @param appSearchData An application can insert application-specific
4963 * context here, in order to improve quality or specificity of its own
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 * searches. This data will be returned with SEARCH intent(s). Null if
4965 * no extra data is required.
4966 * @param globalSearch If false, this will only launch the search that has been specifically
RoboErik55011652014-07-09 15:05:53 -07004967 * defined by the application (which is usually defined as a local search). If no default
Mike LeBeaucfa419b2009-08-17 10:56:02 -07004968 * search is defined in the current application or activity, global search will be launched.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 * If true, this will always launch a platform-global (e.g. web-based) search instead.
RoboErik55011652014-07-09 15:05:53 -07004970 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 * @see android.app.SearchManager
4972 * @see #onSearchRequested
4973 */
Tor Norbyed9273d62013-05-30 15:59:53 -07004974 public void startSearch(@Nullable String initialQuery, boolean selectInitialQuery,
4975 @Nullable Bundle appSearchData, boolean globalSearch) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07004976 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01004977 mSearchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
RoboErik55011652014-07-09 15:05:53 -07004978 appSearchData, globalSearch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 }
4980
4981 /**
krosaend2d60142009-08-17 08:56:48 -07004982 * Similar to {@link #startSearch}, but actually fires off the search query after invoking
4983 * the search dialog. Made available for testing purposes.
4984 *
4985 * @param query The query to trigger. If empty, the request will be ignored.
4986 * @param appSearchData An application can insert application-specific
4987 * context here, in order to improve quality or specificity of its own
4988 * searches. This data will be returned with SEARCH intent(s). Null if
4989 * no extra data is required.
krosaend2d60142009-08-17 08:56:48 -07004990 */
Tor Norbyed9273d62013-05-30 15:59:53 -07004991 public void triggerSearch(String query, @Nullable Bundle appSearchData) {
krosaend2d60142009-08-17 08:56:48 -07004992 ensureSearchManager();
Bjorn Bringertb782a2f2009-10-01 09:57:33 +01004993 mSearchManager.triggerSearch(query, getComponentName(), appSearchData);
krosaend2d60142009-08-17 08:56:48 -07004994 }
4995
4996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 * Request that key events come to this activity. Use this if your
4998 * activity has no views with focus, but the activity still wants
4999 * a chance to process key events.
RoboErik55011652014-07-09 15:05:53 -07005000 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 * @see android.view.Window#takeKeyEvents
5002 */
5003 public void takeKeyEvents(boolean get) {
5004 getWindow().takeKeyEvents(get);
5005 }
5006
5007 /**
5008 * Enable extended window features. This is a convenience for calling
5009 * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
RoboErik55011652014-07-09 15:05:53 -07005010 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 * @param featureId The desired feature as defined in
5012 * {@link android.view.Window}.
5013 * @return Returns true if the requested feature is supported and now
5014 * enabled.
RoboErik55011652014-07-09 15:05:53 -07005015 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 * @see android.view.Window#requestFeature
5017 */
5018 public final boolean requestWindowFeature(int featureId) {
5019 return getWindow().requestFeature(featureId);
5020 }
5021
5022 /**
5023 * Convenience for calling
5024 * {@link android.view.Window#setFeatureDrawableResource}.
5025 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07005026 public final void setFeatureDrawableResource(int featureId, @DrawableRes int resId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 getWindow().setFeatureDrawableResource(featureId, resId);
5028 }
5029
5030 /**
5031 * Convenience for calling
5032 * {@link android.view.Window#setFeatureDrawableUri}.
5033 */
5034 public final void setFeatureDrawableUri(int featureId, Uri uri) {
5035 getWindow().setFeatureDrawableUri(featureId, uri);
5036 }
5037
5038 /**
5039 * Convenience for calling
5040 * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
5041 */
5042 public final void setFeatureDrawable(int featureId, Drawable drawable) {
5043 getWindow().setFeatureDrawable(featureId, drawable);
5044 }
5045
5046 /**
5047 * Convenience for calling
5048 * {@link android.view.Window#setFeatureDrawableAlpha}.
5049 */
5050 public final void setFeatureDrawableAlpha(int featureId, int alpha) {
5051 getWindow().setFeatureDrawableAlpha(featureId, alpha);
5052 }
5053
5054 /**
5055 * Convenience for calling
5056 * {@link android.view.Window#getLayoutInflater}.
5057 */
Tor Norbyed9273d62013-05-30 15:59:53 -07005058 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 public LayoutInflater getLayoutInflater() {
5060 return getWindow().getLayoutInflater();
5061 }
5062
5063 /**
5064 * Returns a {@link MenuInflater} with this context.
5065 */
Tor Norbyed9273d62013-05-30 15:59:53 -07005066 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 public MenuInflater getMenuInflater() {
Adam Powell88ab6972011-07-28 11:25:01 -07005068 // Make sure that action views can get an appropriate theme.
5069 if (mMenuInflater == null) {
Adam Powelle43340c2014-03-17 19:10:43 -07005070 initWindowDecorActionBar();
Adam Powell88ab6972011-07-28 11:25:01 -07005071 if (mActionBar != null) {
Dianne Hackborn92751972012-05-18 19:22:14 -07005072 mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
Adam Powell88ab6972011-07-28 11:25:01 -07005073 } else {
5074 mMenuInflater = new MenuInflater(this);
5075 }
5076 }
5077 return mMenuInflater;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 }
5079
5080 @Override
Filip Gruszczynski0daf2102015-09-29 08:39:07 -07005081 public void setTheme(int resid) {
5082 super.setTheme(resid);
5083 mWindow.setTheme(resid);
5084 }
5085
5086 @Override
Tor Norbye7b9c9122013-05-30 16:48:33 -07005087 protected void onApplyThemeResource(Resources.Theme theme, @StyleRes int resid,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005088 boolean first) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 if (mParent == null) {
5090 super.onApplyThemeResource(theme, resid, first);
5091 } else {
5092 try {
5093 theme.setTo(mParent.getTheme());
5094 } catch (Exception e) {
5095 // Empty
5096 }
5097 theme.applyStyle(resid, false);
5098 }
Winson073a5262016-02-29 16:04:40 -08005099
5100 // Get the primary color and update the TaskDescription for this activity
5101 TypedArray a = theme.obtainStyledAttributes(
5102 com.android.internal.R.styleable.ActivityTaskDescription);
5103 if (mTaskDescription.getPrimaryColor() == 0) {
5104 int colorPrimary = a.getColor(
5105 com.android.internal.R.styleable.ActivityTaskDescription_colorPrimary, 0);
5106 if (colorPrimary != 0 && Color.alpha(colorPrimary) == 0xFF) {
5107 mTaskDescription.setPrimaryColor(colorPrimary);
5108 }
5109 }
Jorim Jaggi30d64f32017-04-07 16:33:17 +02005110
5111 int colorBackground = a.getColor(
5112 com.android.internal.R.styleable.ActivityTaskDescription_colorBackground, 0);
5113 if (colorBackground != 0 && Color.alpha(colorBackground) == 0xFF) {
5114 mTaskDescription.setBackgroundColor(colorBackground);
Winson073a5262016-02-29 16:04:40 -08005115 }
Jorim Jaggi30d64f32017-04-07 16:33:17 +02005116
5117 final int statusBarColor = a.getColor(
5118 com.android.internal.R.styleable.ActivityTaskDescription_statusBarColor, 0);
5119 if (statusBarColor != 0) {
5120 mTaskDescription.setStatusBarColor(statusBarColor);
5121 }
5122
5123 final int navigationBarColor = a.getColor(
5124 com.android.internal.R.styleable.ActivityTaskDescription_navigationBarColor, 0);
5125 if (navigationBarColor != 0) {
5126 mTaskDescription.setNavigationBarColor(navigationBarColor);
5127 }
5128
Adrian Roos4c864592019-04-10 14:47:57 +02005129 final int targetSdk = getApplicationInfo().targetSdkVersion;
5130 final boolean targetPreQ = targetSdk < Build.VERSION_CODES.Q;
5131 if (!targetPreQ) {
5132 mTaskDescription.setEnsureStatusBarContrastWhenTransparent(a.getBoolean(
Adrian Roos8c7ca4f2019-04-17 11:35:22 +02005133 R.styleable.ActivityTaskDescription_enforceStatusBarContrast,
Adrian Roos4c864592019-04-10 14:47:57 +02005134 false));
5135 mTaskDescription.setEnsureNavigationBarContrastWhenTransparent(a.getBoolean(
Adrian Roos6eb1ed32019-04-08 16:23:43 +02005136 R.styleable
Adrian Roos8c7ca4f2019-04-17 11:35:22 +02005137 .ActivityTaskDescription_enforceNavigationBarContrast,
Adrian Roos4c864592019-04-10 14:47:57 +02005138 true));
5139 }
5140
Winson073a5262016-02-29 16:04:40 -08005141 a.recycle();
5142 setTaskDescription(mTaskDescription);
Winson Chung1af8eda2016-02-05 17:55:56 +00005143 }
5144
5145 /**
Svetoslavc6d1c342015-02-26 14:44:43 -08005146 * Requests permissions to be granted to this application. These permissions
5147 * must be requested in your manifest, they should not be granted to your app,
Peter Visontay2c6b6c42018-06-14 14:47:12 +01005148 * and they should have protection level {@link
5149 * android.content.pm.PermissionInfo#PROTECTION_DANGEROUS dangerous}, regardless
5150 * whether they are declared by the platform or a third-party app.
Svetoslavc6d1c342015-02-26 14:44:43 -08005151 * <p>
5152 * Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}
5153 * are granted at install time if requested in the manifest. Signature permissions
5154 * {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at
5155 * install time if requested in the manifest and the signature of your app matches
5156 * the signature of the app declaring the permissions.
5157 * </p>
5158 * <p>
Philip P. Moltmann677df212020-05-29 17:15:12 -07005159 * Call {@link #shouldShowRequestPermissionRationale(String)} before calling this API to
5160 * check if the system recommends to show a rationale UI before asking for a permission.
5161 * </p>
5162 * <p>
Svetoslavc6d1c342015-02-26 14:44:43 -08005163 * If your app does not have the requested permissions the user will be presented
5164 * with UI for accepting them. After the user has accepted or rejected the
5165 * requested permissions you will receive a callback on {@link
5166 * #onRequestPermissionsResult(int, String[], int[])} reporting whether the
5167 * permissions were granted or not.
5168 * </p>
5169 * <p>
5170 * Note that requesting a permission does not guarantee it will be granted and
5171 * your app should be able to run without having this permission.
5172 * </p>
5173 * <p>
5174 * This method may start an activity allowing the user to choose which permissions
5175 * to grant and which to reject. Hence, you should be prepared that your activity
5176 * may be paused and resumed. Further, granting some permissions may require
5177 * a restart of you application. In such a case, the system will recreate the
5178 * activity stack before delivering the result to {@link
5179 * #onRequestPermissionsResult(int, String[], int[])}.
5180 * </p>
5181 * <p>
5182 * When checking whether you have a permission you should use {@link
5183 * #checkSelfPermission(String)}.
5184 * </p>
5185 * <p>
Svet Ganovd7ad54e2015-08-21 06:18:09 -07005186 * Calling this API for permissions already granted to your app would show UI
5187 * to the user to decide whether the app can still hold these permissions. This
5188 * can be useful if the way your app uses data guarded by the permissions
5189 * changes significantly.
5190 * </p>
5191 * <p>
Svet Ganov255aece2015-07-03 16:03:53 -07005192 * You cannot request a permission if your activity sets {@link
5193 * android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
5194 * <code>true</code> because in this case the activity would not receive
5195 * result callbacks including {@link #onRequestPermissionsResult(int, String[], int[])}.
5196 * </p>
5197 * <p>
Peter Visontay2c6b6c42018-06-14 14:47:12 +01005198 * The <a href="https://github.com/googlesamples/android-RuntimePermissions">
Trevor Johns682c24e2016-04-12 10:13:47 -07005199 * RuntimePermissions</a> sample app demonstrates how to use this method to
5200 * request permissions at run time.
Svetoslavc6d1c342015-02-26 14:44:43 -08005201 * </p>
Svetoslavc6d1c342015-02-26 14:44:43 -08005202 *
Svet Ganovf66381c2016-02-18 20:02:36 -08005203 * @param permissions The requested permissions. Must me non-null and not empty.
Svetoslavc6d1c342015-02-26 14:44:43 -08005204 * @param requestCode Application specific request code to match with a result
5205 * reported to {@link #onRequestPermissionsResult(int, String[], int[])}.
Svet Ganov255aece2015-07-03 16:03:53 -07005206 * Should be >= 0.
Svetoslavc6d1c342015-02-26 14:44:43 -08005207 *
Paul Miller77a0e132016-02-11 13:46:49 -08005208 * @throws IllegalArgumentException if requestCode is negative.
5209 *
Svetoslavc6d1c342015-02-26 14:44:43 -08005210 * @see #onRequestPermissionsResult(int, String[], int[])
5211 * @see #checkSelfPermission(String)
Svetoslavaa048b62015-06-02 15:08:48 -07005212 * @see #shouldShowRequestPermissionRationale(String)
Svetoslavc6d1c342015-02-26 14:44:43 -08005213 */
5214 public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
Paul Miller77a0e132016-02-11 13:46:49 -08005215 if (requestCode < 0) {
5216 throw new IllegalArgumentException("requestCode should be >= 0");
5217 }
Svetoslavffb32b12015-10-15 16:54:00 -07005218 if (mHasCurrentPermissionsRequest) {
Ahmad Melegye2bfbf12017-11-14 21:27:28 +00005219 Log.w(TAG, "Can request only one set of permissions at a time");
Svetoslavffb32b12015-10-15 16:54:00 -07005220 // Dispatch the callback with empty arrays which means a cancellation.
5221 onRequestPermissionsResult(requestCode, new String[0], new int[0]);
5222 return;
5223 }
Svetoslavc6d1c342015-02-26 14:44:43 -08005224 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
Svetoslav970b59c2015-06-09 16:05:21 -07005225 startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
Svetoslavffb32b12015-10-15 16:54:00 -07005226 mHasCurrentPermissionsRequest = true;
Svetoslavc6d1c342015-02-26 14:44:43 -08005227 }
5228
5229 /**
5230 * Callback for the result from requesting permissions. This method
5231 * is invoked for every call on {@link #requestPermissions(String[], int)}.
Svet Ganov0f45c7c2015-07-16 16:28:51 -07005232 * <p>
5233 * <strong>Note:</strong> It is possible that the permissions request interaction
5234 * with the user is interrupted. In this case you will receive empty permissions
5235 * and results arrays which should be treated as a cancellation.
5236 * </p>
Svetoslavc6d1c342015-02-26 14:44:43 -08005237 *
5238 * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
5239 * @param permissions The requested permissions. Never null.
5240 * @param grantResults The grant results for the corresponding permissions
5241 * which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
5242 * or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
5243 *
5244 * @see #requestPermissions(String[], int)
5245 */
5246 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
5247 @NonNull int[] grantResults) {
5248 /* callback - no nothing */
5249 }
5250
5251 /**
Philip P. Moltmann677df212020-05-29 17:15:12 -07005252 * Gets whether you should show UI with rationale before requesting a permission.
Svetoslav20770dd2015-05-29 15:43:04 -07005253 *
5254 * @param permission A permission your app wants to request.
Philip P. Moltmann677df212020-05-29 17:15:12 -07005255 * @return Whether you should show permission rationale UI.
Svetoslav20770dd2015-05-29 15:43:04 -07005256 *
5257 * @see #checkSelfPermission(String)
5258 * @see #requestPermissions(String[], int)
5259 * @see #onRequestPermissionsResult(int, String[], int[])
5260 */
Svetoslav9ce9a152015-06-02 17:59:31 -07005261 public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
Svetoslav20770dd2015-05-29 15:43:04 -07005262 return getPackageManager().shouldShowRequestPermissionRationale(permission);
5263 }
5264
5265 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005266 * Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
5267 * with no options.
5268 *
5269 * @param intent The intent to start.
5270 * @param requestCode If >= 0, this code will be returned in
5271 * onActivityResult() when the activity exits.
5272 *
5273 * @throws android.content.ActivityNotFoundException
5274 *
George Mount0a778ed2013-12-13 13:35:36 -08005275 * @see #startActivity
Dianne Hackborna4972e92012-03-14 10:38:05 -07005276 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005277 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
George Mountabb63cb2014-06-23 11:17:58 -07005278 startActivityForResult(intent, requestCode, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07005279 }
5280
5281 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 * Launch an activity for which you would like a result when it finished.
5283 * When this activity exits, your
George Mount0a778ed2013-12-13 13:35:36 -08005284 * onActivityResult() method will be called with the given requestCode.
RoboErik55011652014-07-09 15:05:53 -07005285 * Using a negative requestCode is the same as calling
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 * {@link #startActivity} (the activity is not launched as a sub-activity).
Dianne Hackborna4972e92012-03-14 10:38:05 -07005287 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 * <p>Note that this method should only be used with Intent protocols
5289 * that are defined to return a result. In other protocols (such as
5290 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
5291 * not get the result when you expect. For example, if the activity you
Mark Renoufcca6d052016-12-02 14:11:18 -05005292 * are launching uses {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
5293 * run in your task and thus you will immediately receive a cancel result.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005294 *
RoboErik55011652014-07-09 15:05:53 -07005295 * <p>As a special case, if you call startActivityForResult() with a requestCode
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
George Mount0a778ed2013-12-13 13:35:36 -08005297 * activity, then your window will not be displayed until a result is
5298 * returned back from the started activity. This is to avoid visible
5299 * flickering when redirecting to another activity.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005300 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 * <p>This method throws {@link android.content.ActivityNotFoundException}
5302 * if there was no Activity found to run the given Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005303 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 * @param intent The intent to start.
5305 * @param requestCode If >= 0, this code will be returned in
5306 * onActivityResult() when the activity exits.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005307 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005308 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005309 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005310 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07005312 *
George Mount0a778ed2013-12-13 13:35:36 -08005313 * @see #startActivity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005315 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
5316 @Nullable Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005317 if (mParent == null) {
George Mount413739e2016-06-08 07:13:37 -07005318 options = transferSpringboardActivityOptions(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 Instrumentation.ActivityResult ar =
5320 mInstrumentation.execStartActivity(
5321 this, mMainThread.getApplicationThread(), mToken, this,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005322 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 if (ar != null) {
5324 mMainThread.sendActivityResult(
5325 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
5326 ar.getResultData());
5327 }
5328 if (requestCode >= 0) {
5329 // If this start is requesting a result, we can avoid making
5330 // the activity visible until the result is received. Setting
5331 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5332 // activity hidden during this time, to avoid flickering.
5333 // This can only be done when a result is requested because
5334 // that guarantees we will get information back when the
5335 // activity is finished, no matter what happens to it.
5336 mStartedActivity = true;
5337 }
Adam Powell14874662013-07-18 19:42:41 -07005338
George Mount41725de2015-04-09 08:23:05 -07005339 cancelInputsAndStartExitTransition(options);
Adam Powell14874662013-07-18 19:42:41 -07005340 // TODO Consider clearing/flushing other event sources and events for child windows.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005342 if (options != null) {
5343 mParent.startActivityFromChild(this, intent, requestCode, options);
5344 } else {
5345 // Note we want to go through this method for compatibility with
5346 // existing applications that may have overridden it.
5347 mParent.startActivityFromChild(this, intent, requestCode);
5348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 }
George Mount41725de2015-04-09 08:23:05 -07005350 }
5351
5352 /**
5353 * Cancels pending inputs and if an Activity Transition is to be run, starts the transition.
5354 *
5355 * @param options The ActivityOptions bundle used to start an Activity.
5356 */
5357 private void cancelInputsAndStartExitTransition(Bundle options) {
5358 final View decor = mWindow != null ? mWindow.peekDecorView() : null;
5359 if (decor != null) {
5360 decor.cancelPendingInputEvents();
5361 }
Sunny Goyald85bed52018-09-25 12:01:01 -07005362 if (options != null) {
George Mountff243282014-07-07 16:12:07 -07005363 mActivityTransitionState.startExitOutTransition(this, options);
5364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005365 }
5366
Chet Haaseb64e777f2016-12-09 07:17:10 -08005367 /**
5368 * Returns whether there are any activity transitions currently running on this
5369 * activity. A return value of {@code true} can mean that either an enter or
5370 * exit transition is running, including whether the background of the activity
5371 * is animating as a part of that transition.
5372 *
5373 * @return true if a transition is currently running on this activity, false otherwise.
5374 */
5375 public boolean isActivityTransitionRunning() {
5376 return mActivityTransitionState.isTransitionRunning();
5377 }
5378
George Mount413739e2016-06-08 07:13:37 -07005379 private Bundle transferSpringboardActivityOptions(Bundle options) {
5380 if (options == null && (mWindow != null && !mWindow.isActive())) {
5381 final ActivityOptions activityOptions = getActivityOptions();
George Mount96383782016-06-08 15:13:52 -07005382 if (activityOptions != null &&
5383 activityOptions.getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) {
George Mount413739e2016-06-08 07:13:37 -07005384 return activityOptions.toBundle();
5385 }
5386 }
5387 return options;
5388 }
5389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 /**
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005391 * @hide Implement to provide correct calling token.
5392 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01005393 @UnsupportedAppUsage
Alexandra Gherghina83231452014-07-04 12:05:20 +01005394 public void startActivityForResultAsUser(Intent intent, int requestCode, UserHandle user) {
5395 startActivityForResultAsUser(intent, requestCode, null, user);
5396 }
5397
5398 /**
5399 * @hide Implement to provide correct calling token.
5400 */
5401 public void startActivityForResultAsUser(Intent intent, int requestCode,
5402 @Nullable Bundle options, UserHandle user) {
Tony Mak96d26fe2017-04-11 20:05:39 +01005403 startActivityForResultAsUser(intent, mEmbeddedID, requestCode, options, user);
5404 }
5405
5406 /**
5407 * @hide Implement to provide correct calling token.
5408 */
5409 public void startActivityForResultAsUser(Intent intent, String resultWho, int requestCode,
5410 @Nullable Bundle options, UserHandle user) {
Alexandra Gherghina83231452014-07-04 12:05:20 +01005411 if (mParent != null) {
5412 throw new RuntimeException("Can't be called from a child");
5413 }
George Mount413739e2016-06-08 07:13:37 -07005414 options = transferSpringboardActivityOptions(options);
Alexandra Gherghina83231452014-07-04 12:05:20 +01005415 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
Tony Mak96d26fe2017-04-11 20:05:39 +01005416 this, mMainThread.getApplicationThread(), mToken, resultWho, intent, requestCode,
Alexandra Gherghina83231452014-07-04 12:05:20 +01005417 options, user);
5418 if (ar != null) {
5419 mMainThread.sendActivityResult(
5420 mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
5421 }
5422 if (requestCode >= 0) {
5423 // If this start is requesting a result, we can avoid making
5424 // the activity visible until the result is received. Setting
5425 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5426 // activity hidden during this time, to avoid flickering.
5427 // This can only be done when a result is requested because
5428 // that guarantees we will get information back when the
5429 // activity is finished, no matter what happens to it.
5430 mStartedActivity = true;
5431 }
5432
George Mount41725de2015-04-09 08:23:05 -07005433 cancelInputsAndStartExitTransition(options);
Alexandra Gherghina83231452014-07-04 12:05:20 +01005434 }
5435
5436 /**
5437 * @hide Implement to provide correct calling token.
5438 */
Philip P. Moltmann4e615e62018-08-28 14:57:49 -07005439 @Override
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005440 public void startActivityAsUser(Intent intent, UserHandle user) {
5441 startActivityAsUser(intent, null, user);
5442 }
5443
5444 /**
5445 * @hide Implement to provide correct calling token.
5446 */
5447 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
5448 if (mParent != null) {
Alexandra Gherghina83231452014-07-04 12:05:20 +01005449 throw new RuntimeException("Can't be called from a child");
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005450 }
George Mount413739e2016-06-08 07:13:37 -07005451 options = transferSpringboardActivityOptions(options);
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005452 Instrumentation.ActivityResult ar =
5453 mInstrumentation.execStartActivity(
Tony Mak96d26fe2017-04-11 20:05:39 +01005454 this, mMainThread.getApplicationThread(), mToken, mEmbeddedID,
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005455 intent, -1, options, user);
5456 if (ar != null) {
5457 mMainThread.sendActivityResult(
5458 mToken, mEmbeddedID, -1, ar.getResultCode(),
5459 ar.getResultData());
5460 }
George Mount41725de2015-04-09 08:23:05 -07005461 cancelInputsAndStartExitTransition(options);
Dianne Hackbornf1c26e22012-08-23 13:54:58 -07005462 }
5463
5464 /**
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005465 * Start a new activity as if it was started by the activity that started our
5466 * current activity. This is for the resolver and chooser activities, which operate
5467 * as intermediaries that dispatch their intent to the target the user selects -- to
5468 * do this, they must perform all security checks including permission grants as if
5469 * their launch had come from the original activity.
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07005470 * @param intent The Intent to start.
5471 * @param options ActivityOptions or null.
Alison Cichowlas3e340502018-08-07 17:15:01 -04005472 * @param permissionToken Token received from the system that permits this call to be made.
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07005473 * @param ignoreTargetSecurity If true, the activity manager will not check whether the
5474 * caller it is doing the start is, is actually allowed to start the target activity.
5475 * If you set this to true, you must set an explicit component in the Intent and do any
5476 * appropriate security checks yourself.
5477 * @param userId The user the new activity should run as.
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005478 * @hide
5479 */
Dianne Hackborna7cfbe02015-07-16 10:52:52 -07005480 public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
Alison Cichowlas3e340502018-08-07 17:15:01 -04005481 IBinder permissionToken, boolean ignoreTargetSecurity, int userId) {
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005482 if (mParent != null) {
5483 throw new RuntimeException("Can't be called from a child");
5484 }
George Mount413739e2016-06-08 07:13:37 -07005485 options = transferSpringboardActivityOptions(options);
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005486 Instrumentation.ActivityResult ar =
5487 mInstrumentation.execStartActivityAsCaller(
5488 this, mMainThread.getApplicationThread(), mToken, this,
Alison Cichowlas3e340502018-08-07 17:15:01 -04005489 intent, -1, options, permissionToken, ignoreTargetSecurity, userId);
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005490 if (ar != null) {
5491 mMainThread.sendActivityResult(
5492 mToken, mEmbeddedID, -1, ar.getResultCode(),
5493 ar.getResultData());
5494 }
George Mount41725de2015-04-09 08:23:05 -07005495 cancelInputsAndStartExitTransition(options);
Dianne Hackborn028ceeb2014-08-17 17:45:48 -07005496 }
5497
5498 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005499 * Same as calling {@link #startIntentSenderForResult(IntentSender, int,
5500 * Intent, int, int, int, Bundle)} with no options.
5501 *
5502 * @param intent The IntentSender to launch.
5503 * @param requestCode If >= 0, this code will be returned in
5504 * onActivityResult() when the activity exits.
5505 * @param fillInIntent If non-null, this will be provided as the
5506 * intent parameter to {@link IntentSender#sendIntent}.
5507 * @param flagsMask Intent flags in the original IntentSender that you
5508 * would like to change.
5509 * @param flagsValues Desired values for any bits set in
5510 * <var>flagsMask</var>
5511 * @param extraFlags Always set to 0.
5512 */
5513 public void startIntentSenderForResult(IntentSender intent, int requestCode,
Tor Norbyed9273d62013-05-30 15:59:53 -07005514 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
Dianne Hackborna4972e92012-03-14 10:38:05 -07005515 throws IntentSender.SendIntentException {
5516 startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask,
5517 flagsValues, extraFlags, null);
5518 }
5519
5520 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005521 * Like {@link #startActivityForResult(Intent, int)}, but allowing you
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005522 * to use a IntentSender to describe the activity to be started. If
5523 * the IntentSender is for an activity, that activity will be started
5524 * as if you had called the regular {@link #startActivityForResult(Intent, int)}
5525 * here; otherwise, its associated action will be executed (such as
5526 * sending a broadcast) as if you had called
5527 * {@link IntentSender#sendIntent IntentSender.sendIntent} on it.
RoboErik55011652014-07-09 15:05:53 -07005528 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005529 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005530 * @param requestCode If >= 0, this code will be returned in
5531 * onActivityResult() when the activity exits.
5532 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005533 * intent parameter to {@link IntentSender#sendIntent}.
5534 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005535 * would like to change.
5536 * @param flagsValues Desired values for any bits set in
5537 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005538 * @param extraFlags Always set to 0.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005539 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005540 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005541 * Context.startActivity(Intent, Bundle)} for more details. If options
5542 * have also been supplied by the IntentSender, options given here will
5543 * override any that conflict with those given by the IntentSender.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005544 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005545 public void startIntentSenderForResult(IntentSender intent, int requestCode,
Tor Norbyed9273d62013-05-30 15:59:53 -07005546 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005547 Bundle options) throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005548 if (mParent == null) {
Clara Bayarria0c2dc32016-04-12 12:00:15 +01005549 startIntentSenderForResultInner(intent, mEmbeddedID, requestCode, fillInIntent,
5550 flagsMask, flagsValues, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07005551 } else if (options != null) {
5552 mParent.startIntentSenderFromChild(this, intent, requestCode,
5553 fillInIntent, flagsMask, flagsValues, extraFlags, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005554 } else {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005555 // Note we want to go through this call for compatibility with
5556 // existing applications that may have overridden the method.
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005557 mParent.startIntentSenderFromChild(this, intent, requestCode,
5558 fillInIntent, flagsMask, flagsValues, extraFlags);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005559 }
5560 }
5561
Clara Bayarria0c2dc32016-04-12 12:00:15 +01005562 private void startIntentSenderForResultInner(IntentSender intent, String who, int requestCode,
5563 Intent fillInIntent, int flagsMask, int flagsValues,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005564 Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005565 throws IntentSender.SendIntentException {
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005566 try {
Sunny Goyald85bed52018-09-25 12:01:01 -07005567 options = transferSpringboardActivityOptions(options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005568 String resolvedType = null;
5569 if (fillInIntent != null) {
Zimc7496a32020-06-01 12:04:55 +01005570 fillInIntent.migrateExtraStreamToClipData(this);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005571 fillInIntent.prepareToLeaveProcess(this);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005572 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
5573 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005574 int result = ActivityTaskManager.getService()
Dianne Hackborn3e6e3852017-05-19 16:12:08 -07005575 .startActivityIntentSender(mMainThread.getApplicationThread(),
5576 intent != null ? intent.getTarget() : null,
5577 intent != null ? intent.getWhitelistToken() : null,
Clara Bayarria0c2dc32016-04-12 12:00:15 +01005578 fillInIntent, resolvedType, mToken, who,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005579 requestCode, flagsMask, flagsValues, options);
5580 if (result == ActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005581 throw new IntentSender.SendIntentException();
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005582 }
5583 Instrumentation.checkStartActivityResult(result, null);
Sunny Goyald85bed52018-09-25 12:01:01 -07005584
5585 if (options != null) {
5586 // Only when the options are not null, as the intent can point to something other
5587 // than an Activity.
5588 cancelInputsAndStartExitTransition(options);
5589 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005590 } catch (RemoteException e) {
5591 }
5592 if (requestCode >= 0) {
5593 // If this start is requesting a result, we can avoid making
5594 // the activity visible until the result is received. Setting
5595 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5596 // activity hidden during this time, to avoid flickering.
5597 // This can only be done when a result is requested because
5598 // that guarantees we will get information back when the
5599 // activity is finished, no matter what happens to it.
5600 mStartedActivity = true;
5601 }
5602 }
5603
5604 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005605 * Same as {@link #startActivity(Intent, Bundle)} with no options
5606 * specified.
5607 *
5608 * @param intent The intent to start.
5609 *
5610 * @throws android.content.ActivityNotFoundException
5611 *
Mark Lufa434852016-08-11 17:40:33 -07005612 * @see #startActivity(Intent, Bundle)
Dianne Hackborna4972e92012-03-14 10:38:05 -07005613 * @see #startActivityForResult
5614 */
5615 @Override
5616 public void startActivity(Intent intent) {
George Mounte1803372014-02-26 19:00:52 +00005617 this.startActivity(intent, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07005618 }
5619
5620 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 * Launch a new activity. You will not receive any information about when
5622 * the activity exits. This implementation overrides the base version,
5623 * providing information about
5624 * the activity performing the launch. Because of this additional
5625 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5626 * required; if not specified, the new activity will be added to the
5627 * task of the caller.
RoboErik55011652014-07-09 15:05:53 -07005628 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 * <p>This method throws {@link android.content.ActivityNotFoundException}
5630 * if there was no Activity found to run the given Intent.
RoboErik55011652014-07-09 15:05:53 -07005631 *
5632 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005633 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005634 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005635 * Context.startActivity(Intent, Bundle)} for more details.
RoboErik55011652014-07-09 15:05:53 -07005636 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 * @throws android.content.ActivityNotFoundException
Dianne Hackborna4972e92012-03-14 10:38:05 -07005638 *
Mark Lufa434852016-08-11 17:40:33 -07005639 * @see #startActivity(Intent)
RoboErik55011652014-07-09 15:05:53 -07005640 * @see #startActivityForResult
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 */
5642 @Override
Tor Norbyed9273d62013-05-30 15:59:53 -07005643 public void startActivity(Intent intent, @Nullable Bundle options) {
TYM Tsai8af721d2019-07-24 17:11:59 +08005644 if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)
5645 && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) {
5646 if (TextUtils.equals(getPackageName(),
5647 intent.resolveActivity(getPackageManager()).getPackageName())) {
5648 // Apply Autofill restore mechanism on the started activity by startActivity()
5649 final IBinder token =
5650 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
5651 // Remove restore ability from current activity
5652 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
5653 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY);
5654 // Put restore token
5655 intent.putExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN, token);
5656 intent.putExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY, true);
5657 }
5658 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07005659 if (options != null) {
5660 startActivityForResult(intent, -1, options);
5661 } else {
5662 // Note we want to go through this call for compatibility with
5663 // applications that may have overridden the method.
5664 startActivityForResult(intent, -1);
5665 }
5666 }
5667
5668 /**
5669 * Same as {@link #startActivities(Intent[], Bundle)} with no options
5670 * specified.
5671 *
5672 * @param intents The intents to start.
5673 *
5674 * @throws android.content.ActivityNotFoundException
5675 *
Mark Lufa434852016-08-11 17:40:33 -07005676 * @see #startActivities(Intent[], Bundle)
Dianne Hackborna4972e92012-03-14 10:38:05 -07005677 * @see #startActivityForResult
5678 */
5679 @Override
5680 public void startActivities(Intent[] intents) {
5681 startActivities(intents, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 }
5683
5684 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005685 * Launch a new activity. You will not receive any information about when
5686 * the activity exits. This implementation overrides the base version,
5687 * providing information about
5688 * the activity performing the launch. Because of this additional
5689 * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not
5690 * required; if not specified, the new activity will be added to the
5691 * task of the caller.
5692 *
5693 * <p>This method throws {@link android.content.ActivityNotFoundException}
5694 * if there was no Activity found to run the given Intent.
5695 *
5696 * @param intents The intents to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005697 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005698 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005699 * Context.startActivity(Intent, Bundle)} for more details.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005700 *
5701 * @throws android.content.ActivityNotFoundException
5702 *
Mark Lufa434852016-08-11 17:40:33 -07005703 * @see #startActivities(Intent[])
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005704 * @see #startActivityForResult
5705 */
5706 @Override
Tor Norbyed9273d62013-05-30 15:59:53 -07005707 public void startActivities(Intent[] intents, @Nullable Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005708 mInstrumentation.execStartActivities(this, mMainThread.getApplicationThread(),
Dianne Hackborna4972e92012-03-14 10:38:05 -07005709 mToken, this, intents, options);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005710 }
5711
5712 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005713 * Same as calling {@link #startIntentSender(IntentSender, Intent, int, int, int, Bundle)}
5714 * with no options.
RoboErik55011652014-07-09 15:05:53 -07005715 *
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005716 * @param intent The IntentSender to launch.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005717 * @param fillInIntent If non-null, this will be provided as the
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005718 * intent parameter to {@link IntentSender#sendIntent}.
5719 * @param flagsMask Intent flags in the original IntentSender that you
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005720 * would like to change.
5721 * @param flagsValues Desired values for any bits set in
5722 * <var>flagsMask</var>
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005723 * @param extraFlags Always set to 0.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005724 */
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005725 public void startIntentSender(IntentSender intent,
Tor Norbyed9273d62013-05-30 15:59:53 -07005726 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07005727 throws IntentSender.SendIntentException {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005728 startIntentSender(intent, fillInIntent, flagsMask, flagsValues,
5729 extraFlags, null);
5730 }
5731
5732 /**
5733 * Like {@link #startActivity(Intent, Bundle)}, but taking a IntentSender
5734 * to start; see
5735 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
5736 * for more information.
5737 *
5738 * @param intent The IntentSender to launch.
5739 * @param fillInIntent If non-null, this will be provided as the
5740 * intent parameter to {@link IntentSender#sendIntent}.
5741 * @param flagsMask Intent flags in the original IntentSender that you
5742 * would like to change.
5743 * @param flagsValues Desired values for any bits set in
5744 * <var>flagsMask</var>
5745 * @param extraFlags Always set to 0.
5746 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005747 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005748 * Context.startActivity(Intent, Bundle)} for more details. If options
5749 * have also been supplied by the IntentSender, options given here will
5750 * override any that conflict with those given by the IntentSender.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005751 */
5752 public void startIntentSender(IntentSender intent,
Tor Norbyed9273d62013-05-30 15:59:53 -07005753 @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005754 Bundle options) throws IntentSender.SendIntentException {
5755 if (options != null) {
5756 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
5757 flagsValues, extraFlags, options);
5758 } else {
5759 // Note we want to go through this call for compatibility with
5760 // applications that may have overridden the method.
5761 startIntentSenderForResult(intent, -1, fillInIntent, flagsMask,
5762 flagsValues, extraFlags);
5763 }
5764 }
5765
5766 /**
5767 * Same as calling {@link #startActivityIfNeeded(Intent, int, Bundle)}
5768 * with no options.
5769 *
5770 * @param intent The intent to start.
5771 * @param requestCode If >= 0, this code will be returned in
5772 * onActivityResult() when the activity exits, as described in
5773 * {@link #startActivityForResult}.
5774 *
5775 * @return If a new activity was launched then true is returned; otherwise
5776 * false is returned and you must handle the Intent yourself.
5777 *
5778 * @see #startActivity
5779 * @see #startActivityForResult
5780 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005781 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
5782 int requestCode) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005783 return startActivityIfNeeded(intent, requestCode, null);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07005784 }
5785
5786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 * A special variation to launch an activity only if a new activity
5788 * instance is needed to handle the given Intent. In other words, this is
RoboErik55011652014-07-09 15:05:53 -07005789 * just like {@link #startActivityForResult(Intent, int)} except: if you are
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or
RoboErik55011652014-07-09 15:05:53 -07005791 * singleTask or singleTop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode},
RoboErik55011652014-07-09 15:05:53 -07005793 * and the activity
5794 * that handles <var>intent</var> is the same as your currently running
5795 * activity, then a new instance is not needed. In this case, instead of
5796 * the normal behavior of calling {@link #onNewIntent} this function will
5797 * return and you can handle the Intent yourself.
5798 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 * <p>This function can only be called from a top-level activity; if it is
5800 * called from a child activity, a runtime exception will be thrown.
RoboErik55011652014-07-09 15:05:53 -07005801 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 * @param intent The intent to start.
5803 * @param requestCode If >= 0, this code will be returned in
5804 * onActivityResult() when the activity exits, as described in
5805 * {@link #startActivityForResult}.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005806 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005807 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005808 * Context.startActivity(Intent, Bundle)} for more details.
RoboErik55011652014-07-09 15:05:53 -07005809 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 * @return If a new activity was launched then true is returned; otherwise
5811 * false is returned and you must handle the Intent yourself.
RoboErik55011652014-07-09 15:05:53 -07005812 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 * @see #startActivity
5814 * @see #startActivityForResult
5815 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005816 public boolean startActivityIfNeeded(@RequiresPermission @NonNull Intent intent,
5817 int requestCode, @Nullable Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 if (mParent == null) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005819 int result = ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 try {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07005821 Uri referrer = onProvideReferrer();
5822 if (referrer != null) {
5823 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
5824 }
Zimc7496a32020-06-01 12:04:55 +01005825 intent.migrateExtraStreamToClipData(this);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005826 intent.prepareToLeaveProcess(this);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005827 result = ActivityTaskManager.getService()
Dianne Hackbornf265ea92013-01-31 15:00:51 -08005828 .startActivity(mMainThread.getApplicationThread(), getBasePackageName(),
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -08005829 getAttributionTag(), intent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005830 intent.resolveTypeIfNeeded(getContentResolver()), mToken, mEmbeddedID,
5831 requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 } catch (RemoteException e) {
5833 // Empty
5834 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08005835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 Instrumentation.checkStartActivityResult(result, intent);
Siva Velusamy92a8b222012-03-09 16:24:04 -08005837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 if (requestCode >= 0) {
5839 // If this start is requesting a result, we can avoid making
5840 // the activity visible until the result is received. Setting
5841 // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
5842 // activity hidden during this time, to avoid flickering.
5843 // This can only be done when a result is requested because
5844 // that guarantees we will get information back when the
5845 // activity is finished, no matter what happens to it.
5846 mStartedActivity = true;
5847 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07005848 return result != ActivityManager.START_RETURN_INTENT_TO_CALLER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
5850
5851 throw new UnsupportedOperationException(
5852 "startActivityIfNeeded can only be called from a top-level activity");
5853 }
5854
5855 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005856 * Same as calling {@link #startNextMatchingActivity(Intent, Bundle)} with
5857 * no options.
5858 *
5859 * @param intent The intent to dispatch to the next activity. For
5860 * correct behavior, this must be the same as the Intent that started
5861 * your own activity; the only changes you can make are to the extras
5862 * inside of it.
5863 *
5864 * @return Returns a boolean indicating whether there was another Activity
5865 * to start: true if there was a next activity to start, false if there
5866 * wasn't. In general, if true is returned you will then want to call
5867 * finish() on yourself.
5868 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005869 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent) {
Dianne Hackborna4972e92012-03-14 10:38:05 -07005870 return startNextMatchingActivity(intent, null);
5871 }
5872
5873 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 * Special version of starting an activity, for use when you are replacing
5875 * other activity components. You can use this to hand the Intent off
5876 * to the next Activity that can handle it. You typically call this in
5877 * {@link #onCreate} with the Intent returned by {@link #getIntent}.
RoboErik55011652014-07-09 15:05:53 -07005878 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 * @param intent The intent to dispatch to the next activity. For
5880 * correct behavior, this must be the same as the Intent that started
5881 * your own activity; the only changes you can make are to the extras
5882 * inside of it.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005883 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005884 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005885 * Context.startActivity(Intent, Bundle)} for more details.
RoboErik55011652014-07-09 15:05:53 -07005886 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 * @return Returns a boolean indicating whether there was another Activity
5888 * to start: true if there was a next activity to start, false if there
5889 * wasn't. In general, if true is returned you will then want to call
5890 * finish() on yourself.
5891 */
Tor Norbye788fc2b2015-07-05 16:10:42 -07005892 public boolean startNextMatchingActivity(@RequiresPermission @NonNull Intent intent,
5893 @Nullable Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 if (mParent == null) {
5895 try {
Zimc7496a32020-06-01 12:04:55 +01005896 intent.migrateExtraStreamToClipData(this);
Jeff Sharkey344744b2016-01-28 19:03:30 -07005897 intent.prepareToLeaveProcess(this);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07005898 return ActivityTaskManager.getService()
Dianne Hackborna4972e92012-03-14 10:38:05 -07005899 .startNextMatchingActivity(mToken, intent, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 } catch (RemoteException e) {
5901 // Empty
5902 }
5903 return false;
5904 }
5905
5906 throw new UnsupportedOperationException(
5907 "startNextMatchingActivity can only be called from a top-level activity");
5908 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07005909
5910 /**
5911 * Same as calling {@link #startActivityFromChild(Activity, Intent, int, Bundle)}
5912 * with no options.
5913 *
5914 * @param child The activity making the call.
5915 * @param intent The intent to start.
5916 * @param requestCode Reply request code. < 0 if reply is not requested.
5917 *
5918 * @throws android.content.ActivityNotFoundException
5919 *
5920 * @see #startActivity
5921 * @see #startActivityForResult
Charles Chenc380f022019-08-13 18:39:17 +08005922 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5923 * androidx.fragment.app.Fragment,Intent,int)}
Dianne Hackborna4972e92012-03-14 10:38:05 -07005924 */
Charles Chenc380f022019-08-13 18:39:17 +08005925 @Deprecated
Tor Norbye788fc2b2015-07-05 16:10:42 -07005926 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005927 int requestCode) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005928 startActivityFromChild(child, intent, requestCode, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07005929 }
5930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 /**
RoboErik55011652014-07-09 15:05:53 -07005932 * This is called when a child activity of this one calls its
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 * {@link #startActivity} or {@link #startActivityForResult} method.
RoboErik55011652014-07-09 15:05:53 -07005934 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 * <p>This method throws {@link android.content.ActivityNotFoundException}
5936 * if there was no Activity found to run the given Intent.
RoboErik55011652014-07-09 15:05:53 -07005937 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 * @param child The activity making the call.
5939 * @param intent The intent to start.
Dianne Hackborna4972e92012-03-14 10:38:05 -07005940 * @param requestCode Reply request code. < 0 if reply is not requested.
5941 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08005942 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07005943 * Context.startActivity(Intent, Bundle)} for more details.
RoboErik55011652014-07-09 15:05:53 -07005944 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 * @throws android.content.ActivityNotFoundException
RoboErik55011652014-07-09 15:05:53 -07005946 *
5947 * @see #startActivity
5948 * @see #startActivityForResult
Charles Chenc380f022019-08-13 18:39:17 +08005949 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5950 * androidx.fragment.app.Fragment,Intent,int,Bundle)}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 */
Charles Chenc380f022019-08-13 18:39:17 +08005952 @Deprecated
Tor Norbye788fc2b2015-07-05 16:10:42 -07005953 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
Tor Norbyed9273d62013-05-30 15:59:53 -07005954 int requestCode, @Nullable Bundle options) {
George Mount413739e2016-06-08 07:13:37 -07005955 options = transferSpringboardActivityOptions(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 Instrumentation.ActivityResult ar =
5957 mInstrumentation.execStartActivity(
5958 this, mMainThread.getApplicationThread(), mToken, child,
Dianne Hackborna4972e92012-03-14 10:38:05 -07005959 intent, requestCode, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 if (ar != null) {
5961 mMainThread.sendActivityResult(
5962 mToken, child.mEmbeddedID, requestCode,
5963 ar.getResultCode(), ar.getResultData());
5964 }
George Mount41725de2015-04-09 08:23:05 -07005965 cancelInputsAndStartExitTransition(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
5967
5968 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07005969 * Same as calling {@link #startActivityFromFragment(Fragment, Intent, int, Bundle)}
5970 * with no options.
5971 *
5972 * @param fragment The fragment making the call.
5973 * @param intent The intent to start.
5974 * @param requestCode Reply request code. < 0 if reply is not requested.
5975 *
5976 * @throws android.content.ActivityNotFoundException
5977 *
5978 * @see Fragment#startActivity
5979 * @see Fragment#startActivityForResult
Ian Lake0a1feb82017-11-13 10:26:46 -08005980 *
Charles Chenc380f022019-08-13 18:39:17 +08005981 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
5982 * androidx.fragment.app.Fragment,Intent,int)}
Dianne Hackborna4972e92012-03-14 10:38:05 -07005983 */
Ian Lake0a1feb82017-11-13 10:26:46 -08005984 @Deprecated
Tor Norbye788fc2b2015-07-05 16:10:42 -07005985 public void startActivityFromFragment(@NonNull Fragment fragment,
5986 @RequiresPermission Intent intent, int requestCode) {
George Mountabb63cb2014-06-23 11:17:58 -07005987 startActivityFromFragment(fragment, intent, requestCode, null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07005988 }
5989
5990 /**
RoboErik55011652014-07-09 15:05:53 -07005991 * This is called when a Fragment in this activity calls its
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07005992 * {@link Fragment#startActivity} or {@link Fragment#startActivityForResult}
5993 * method.
RoboErik55011652014-07-09 15:05:53 -07005994 *
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07005995 * <p>This method throws {@link android.content.ActivityNotFoundException}
5996 * if there was no Activity found to run the given Intent.
RoboErik55011652014-07-09 15:05:53 -07005997 *
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07005998 * @param fragment The fragment making the call.
5999 * @param intent The intent to start.
RoboErik55011652014-07-09 15:05:53 -07006000 * @param requestCode Reply request code. < 0 if reply is not requested.
Dianne Hackborna4972e92012-03-14 10:38:05 -07006001 * @param options Additional options for how the Activity should be started.
Elliot Waite54de7742017-01-11 15:30:35 -08006002 * See {@link android.content.Context#startActivity(Intent, Bundle)}
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07006003 * Context.startActivity(Intent, Bundle)} for more details.
RoboErik55011652014-07-09 15:05:53 -07006004 *
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006005 * @throws android.content.ActivityNotFoundException
RoboErik55011652014-07-09 15:05:53 -07006006 *
6007 * @see Fragment#startActivity
6008 * @see Fragment#startActivityForResult
Ian Lake0a1feb82017-11-13 10:26:46 -08006009 *
Charles Chenc380f022019-08-13 18:39:17 +08006010 * @deprecated Use {@code androidx.fragment.app.FragmentActivity#startActivityFromFragment(
6011 * androidx.fragment.app.Fragment,Intent,int,Bundle)}
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006012 */
Ian Lake0a1feb82017-11-13 10:26:46 -08006013 @Deprecated
Tor Norbye788fc2b2015-07-05 16:10:42 -07006014 public void startActivityFromFragment(@NonNull Fragment fragment,
6015 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006016 startActivityForResult(fragment.mWho, intent, requestCode, options);
6017 }
6018
Charles Chenc380f022019-08-13 18:39:17 +08006019 private void startActivityAsUserFromFragment(@NonNull Fragment fragment,
Tony Mak96d26fe2017-04-11 20:05:39 +01006020 @RequiresPermission Intent intent, int requestCode, @Nullable Bundle options,
6021 UserHandle user) {
6022 startActivityForResultAsUser(intent, fragment.mWho, requestCode, options, user);
6023 }
6024
6025 /**
6026 * @hide
6027 */
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006028 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006029 @UnsupportedAppUsage
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006030 public void startActivityForResult(
6031 String who, Intent intent, int requestCode, @Nullable Bundle options) {
Dianne Hackborna3acdb32015-06-08 17:07:40 -07006032 Uri referrer = onProvideReferrer();
6033 if (referrer != null) {
6034 intent.putExtra(Intent.EXTRA_REFERRER, referrer);
6035 }
George Mount413739e2016-06-08 07:13:37 -07006036 options = transferSpringboardActivityOptions(options);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006037 Instrumentation.ActivityResult ar =
6038 mInstrumentation.execStartActivity(
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006039 this, mMainThread.getApplicationThread(), mToken, who,
Dianne Hackborna4972e92012-03-14 10:38:05 -07006040 intent, requestCode, options);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006041 if (ar != null) {
6042 mMainThread.sendActivityResult(
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006043 mToken, who, requestCode,
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006044 ar.getResultCode(), ar.getResultData());
6045 }
George Mount41725de2015-04-09 08:23:05 -07006046 cancelInputsAndStartExitTransition(options);
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006047 }
6048
6049 /**
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00006050 * @hide
6051 */
6052 @Override
6053 public boolean canStartActivityForResult() {
6054 return true;
6055 }
6056
6057 /**
Dianne Hackborna4972e92012-03-14 10:38:05 -07006058 * Same as calling {@link #startIntentSenderFromChild(Activity, IntentSender,
6059 * int, Intent, int, int, int, Bundle)} with no options.
Charles Chenc380f022019-08-13 18:39:17 +08006060 * @deprecated Use {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6061 * instead.
Dianne Hackborna4972e92012-03-14 10:38:05 -07006062 */
Charles Chenc380f022019-08-13 18:39:17 +08006063 @Deprecated
Dianne Hackborna4972e92012-03-14 10:38:05 -07006064 public void startIntentSenderFromChild(Activity child, IntentSender intent,
6065 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
6066 int extraFlags)
6067 throws IntentSender.SendIntentException {
6068 startIntentSenderFromChild(child, intent, requestCode, fillInIntent,
6069 flagsMask, flagsValues, extraFlags, null);
6070 }
6071
6072 /**
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07006073 * Like {@link #startActivityFromChild(Activity, Intent, int)}, but
Dianne Hackbornfa82f222009-09-17 15:14:12 -07006074 * taking a IntentSender; see
Dianne Hackbornae22c052009-09-17 18:46:22 -07006075 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07006076 * for more information.
Charles Chenc380f022019-08-13 18:39:17 +08006077 * @deprecated Use
6078 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int, Bundle)}
6079 * instead.
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07006080 */
Charles Chenc380f022019-08-13 18:39:17 +08006081 @Deprecated
Dianne Hackbornfa82f222009-09-17 15:14:12 -07006082 public void startIntentSenderFromChild(Activity child, IntentSender intent,
6083 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
Tor Norbyed9273d62013-05-30 15:59:53 -07006084 int extraFlags, @Nullable Bundle options)
Dianne Hackbornfa82f222009-09-17 15:14:12 -07006085 throws IntentSender.SendIntentException {
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006086 startIntentSenderForResultInner(intent, child.mEmbeddedID, requestCode, fillInIntent,
6087 flagsMask, flagsValues, options);
6088 }
6089
6090 /**
Charles Chenc380f022019-08-13 18:39:17 +08006091 * Like {@link #startIntentSender}, but taking a Fragment; see
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006092 * {@link #startIntentSenderForResult(IntentSender, int, Intent, int, int, int)}
6093 * for more information.
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006094 */
Charles Chenc380f022019-08-13 18:39:17 +08006095 private void startIntentSenderFromFragment(Fragment fragment, IntentSender intent,
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006096 int requestCode, Intent fillInIntent, int flagsMask, int flagsValues,
Charles Chenc380f022019-08-13 18:39:17 +08006097 @Nullable Bundle options)
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006098 throws IntentSender.SendIntentException {
Charles Chenc380f022019-08-13 18:39:17 +08006099 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
Clara Bayarria0c2dc32016-04-12 12:00:15 +01006100 flagsMask, flagsValues, options);
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07006101 }
6102
6103 /**
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006104 * Call immediately after one of the flavors of {@link #startActivity(Intent)}
6105 * or {@link #finish} to specify an explicit transition animation to
6106 * perform next.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07006107 *
6108 * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN} an alternative
6109 * to using this with starting activities is to supply the desired animation
6110 * information through a {@link ActivityOptions} bundle to
Mark Lufa434852016-08-11 17:40:33 -07006111 * {@link #startActivity(Intent, Bundle)} or a related function. This allows
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07006112 * you to specify a custom animation even when starting an activity from
6113 * outside the context of the current top activity.
6114 *
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006115 * @param enterAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07006116 * the incoming activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006117 * @param exitAnim A resource ID of the animation resource to use for
Dianne Hackborn8b571a82009-09-25 16:09:43 -07006118 * the outgoing activity. Use 0 for no animation.
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006119 */
6120 public void overridePendingTransition(int enterAnim, int exitAnim) {
6121 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006122 ActivityTaskManager.getService().overridePendingTransition(
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006123 mToken, getPackageName(), enterAnim, exitAnim);
6124 } catch (RemoteException e) {
6125 }
6126 }
RoboErik55011652014-07-09 15:05:53 -07006127
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07006128 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 * Call this to set the result that your activity will return to its
6130 * caller.
RoboErik55011652014-07-09 15:05:53 -07006131 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 * @param resultCode The result code to propagate back to the originating
6133 * activity, often RESULT_CANCELED or RESULT_OK
RoboErik55011652014-07-09 15:05:53 -07006134 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 * @see #RESULT_CANCELED
6136 * @see #RESULT_OK
6137 * @see #RESULT_FIRST_USER
6138 * @see #setResult(int, Intent)
6139 */
6140 public final void setResult(int resultCode) {
6141 synchronized (this) {
6142 mResultCode = resultCode;
6143 mResultData = null;
6144 }
6145 }
6146
6147 /**
6148 * Call this to set the result that your activity will return to its
6149 * caller.
Dianne Hackborn21c241e2012-03-08 13:57:23 -08006150 *
6151 * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent
6152 * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION
6153 * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION
6154 * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the
6155 * Activity receiving the result access to the specific URIs in the Intent.
6156 * Access will remain until the Activity has finished (it will remain across the hosting
6157 * process being killed and other temporary destruction) and will be added
6158 * to any existing set of URI permissions it already holds.
6159 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 * @param resultCode The result code to propagate back to the originating
6161 * activity, often RESULT_CANCELED or RESULT_OK
6162 * @param data The data to propagate back to the originating activity.
RoboErik55011652014-07-09 15:05:53 -07006163 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 * @see #RESULT_CANCELED
6165 * @see #RESULT_OK
6166 * @see #RESULT_FIRST_USER
6167 * @see #setResult(int)
6168 */
6169 public final void setResult(int resultCode, Intent data) {
6170 synchronized (this) {
6171 mResultCode = resultCode;
6172 mResultData = data;
6173 }
6174 }
6175
6176 /**
Dianne Hackborn85d558c2014-11-04 10:31:54 -08006177 * Return information about who launched this activity. If the launching Intent
6178 * contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
6179 * that will be returned as-is; otherwise, if known, an
6180 * {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
6181 * package name that started the Intent will be returned. This may return null if no
6182 * referrer can be identified -- it is neither explicitly specified, nor is it known which
6183 * application package was involved.
6184 *
6185 * <p>If called while inside the handling of {@link #onNewIntent}, this function will
6186 * return the referrer that submitted that new intent to the activity. Otherwise, it
6187 * always returns the referrer of the original Intent.</p>
6188 *
6189 * <p>Note that this is <em>not</em> a security feature -- you can not trust the
6190 * referrer information, applications can spoof it.</p>
6191 */
6192 @Nullable
6193 public Uri getReferrer() {
6194 Intent intent = getIntent();
Adam Powelld3c63a62016-06-09 12:36:16 -07006195 try {
6196 Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
6197 if (referrer != null) {
6198 return referrer;
6199 }
6200 String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
6201 if (referrerName != null) {
6202 return Uri.parse(referrerName);
6203 }
6204 } catch (BadParcelableException e) {
6205 Log.w(TAG, "Cannot read referrer from intent;"
6206 + " intent extras contain unknown custom Parcelable objects");
Dianne Hackborn85d558c2014-11-04 10:31:54 -08006207 }
6208 if (mReferrer != null) {
6209 return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
6210 }
6211 return null;
6212 }
6213
6214 /**
Dianne Hackborna3acdb32015-06-08 17:07:40 -07006215 * Override to generate the desired referrer for the content currently being shown
6216 * by the app. The default implementation returns null, meaning the referrer will simply
6217 * be the android-app: of the package name of this activity. Return a non-null Uri to
6218 * have that supplied as the {@link Intent#EXTRA_REFERRER} of any activities started from it.
6219 */
6220 public Uri onProvideReferrer() {
6221 return null;
6222 }
6223
6224 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 * Return the name of the package that invoked this activity. This is who
6226 * the data in {@link #setResult setResult()} will be sent to. You can
6227 * use this information to validate that the recipient is allowed to
6228 * receive the data.
RoboErik55011652014-07-09 15:05:53 -07006229 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07006230 * <p class="note">Note: if the calling activity is not expecting a result (that is it
RoboErik55011652014-07-09 15:05:53 -07006231 * did not use the {@link #startActivityForResult}
6232 * form that includes a request code), then the calling package will be
Dianne Hackborn7b924672013-04-11 18:08:42 -07006233 * null.</p>
6234 *
6235 * <p class="note">Note: prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
6236 * the result from this method was unstable. If the process hosting the calling
6237 * package was no longer running, it would return null instead of the proper package
6238 * name. You can use {@link #getCallingActivity()} and retrieve the package name
6239 * from that instead.</p>
RoboErik55011652014-07-09 15:05:53 -07006240 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 * @return The package of the activity that will receive your
6242 * reply, or null if none.
6243 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006244 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 public String getCallingPackage() {
6246 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006247 return ActivityTaskManager.getService().getCallingPackage(mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 } catch (RemoteException e) {
6249 return null;
6250 }
6251 }
6252
6253 /**
6254 * Return the name of the activity that invoked this activity. This is
6255 * who the data in {@link #setResult setResult()} will be sent to. You
6256 * can use this information to validate that the recipient is allowed to
6257 * receive the data.
RoboErik55011652014-07-09 15:05:53 -07006258 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07006259 * <p class="note">Note: if the calling activity is not expecting a result (that is it
RoboErik55011652014-07-09 15:05:53 -07006260 * did not use the {@link #startActivityForResult}
6261 * form that includes a request code), then the calling package will be
6262 * null.
6263 *
Dianne Hackborn7b924672013-04-11 18:08:42 -07006264 * @return The ComponentName of the activity that will receive your
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 * reply, or null if none.
6266 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006267 @Nullable
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 public ComponentName getCallingActivity() {
6269 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006270 return ActivityTaskManager.getService().getCallingActivity(mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 } catch (RemoteException e) {
6272 return null;
6273 }
6274 }
6275
6276 /**
6277 * Control whether this activity's main window is visible. This is intended
6278 * only for the special case of an activity that is not going to show a
6279 * UI itself, but can't just finish prior to onResume() because it needs
6280 * to wait for a service binding or such. Setting this to false allows
6281 * you to prevent your UI from being shown during that time.
RoboErik55011652014-07-09 15:05:53 -07006282 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 * <p>The default value for this is taken from the
6284 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
6285 */
6286 public void setVisible(boolean visible) {
6287 if (mVisibleFromClient != visible) {
6288 mVisibleFromClient = visible;
6289 if (mVisibleFromServer) {
6290 if (visible) makeVisible();
6291 else mDecor.setVisibility(View.INVISIBLE);
6292 }
6293 }
6294 }
RoboErik55011652014-07-09 15:05:53 -07006295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 void makeVisible() {
6297 if (!mWindowAdded) {
6298 ViewManager wm = getWindowManager();
6299 wm.addView(mDecor, getWindow().getAttributes());
6300 mWindowAdded = true;
6301 }
6302 mDecor.setVisibility(View.VISIBLE);
6303 }
RoboErik55011652014-07-09 15:05:53 -07006304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 /**
6306 * Check to see whether this activity is in the process of finishing,
6307 * either because you called {@link #finish} on it or someone else
6308 * has requested that it finished. This is often used in
6309 * {@link #onPause} to determine whether the activity is simply pausing or
6310 * completely finishing.
RoboErik55011652014-07-09 15:05:53 -07006311 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 * @return If the activity is finishing, returns true; else returns false.
RoboErik55011652014-07-09 15:05:53 -07006313 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 * @see #finish
6315 */
6316 public boolean isFinishing() {
6317 return mFinished;
6318 }
6319
6320 /**
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07006321 * Returns true if the final {@link #onDestroy()} call has been made
6322 * on the Activity, so this instance is now dead.
6323 */
6324 public boolean isDestroyed() {
6325 return mDestroyed;
6326 }
6327
6328 /**
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05006329 * Check to see whether this activity is in the process of being destroyed in order to be
6330 * recreated with a new configuration. This is often used in
6331 * {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
6332 * on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
RoboErik55011652014-07-09 15:05:53 -07006333 *
Jeff Hamilton3d32f6e2010-04-01 00:04:16 -05006334 * @return If the activity is being torn down in order to be recreated with a new configuration,
6335 * returns true; else returns false.
6336 */
6337 public boolean isChangingConfigurations() {
6338 return mChangingConfigurations;
6339 }
6340
6341 /**
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08006342 * Cause this Activity to be recreated with a new instance. This results
6343 * in essentially the same flow as when the Activity is created due to
6344 * a configuration change -- the current instance will go through its
6345 * lifecycle to {@link #onDestroy} and a new instance then created after it.
6346 */
6347 public void recreate() {
6348 if (mParent != null) {
6349 throw new IllegalStateException("Can only be called on top-level activity");
6350 }
Wale Ogunwale0527d912018-05-16 17:23:48 -07006351 if (Looper.myLooper() != mMainThread.getLooper()) {
6352 throw new IllegalStateException("Must be called from main thread");
6353 }
Andrii Kulian320e3b52018-05-03 16:26:25 -07006354 mMainThread.scheduleRelaunchActivity(mToken);
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08006355 }
6356
6357 /**
Winson Chung3b3f4642014-04-22 10:08:18 -07006358 * Finishes the current activity and specifies whether to remove the task associated with this
6359 * activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01006361 @UnsupportedAppUsage
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07006362 private void finish(int finishTask) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 if (mParent == null) {
6364 int resultCode;
6365 Intent resultData;
6366 synchronized (this) {
6367 resultCode = mResultCode;
6368 resultData = mResultData;
6369 }
Joe Onorato43a17652011-04-06 19:22:23 -07006370 if (false) Log.v(TAG, "Finishing self: token=" + mToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 try {
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04006372 if (resultData != null) {
Jeff Sharkey344744b2016-01-28 19:03:30 -07006373 resultData.prepareToLeaveProcess(this);
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04006374 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006375 if (ActivityTaskManager.getService()
Winson Chung3b3f4642014-04-22 10:08:18 -07006376 .finishActivity(mToken, resultCode, resultData, finishTask)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 mFinished = true;
6378 }
6379 } catch (RemoteException e) {
6380 // Empty
6381 }
6382 } else {
6383 mParent.finishFromChild(this);
6384 }
Felipe Lemec24a56a2017-08-03 14:27:57 -07006385
6386 // Activity was launched when user tapped a link in the Autofill Save UI - Save UI must
6387 // be restored now.
6388 if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)) {
TYM Tsai8af721d2019-07-24 17:11:59 +08006389 restoreAutofillSaveUi();
Felipe Lemec24a56a2017-08-03 14:27:57 -07006390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
6392
6393 /**
TYM Tsai8af721d2019-07-24 17:11:59 +08006394 * Restores Autofill Save UI
6395 */
6396 private void restoreAutofillSaveUi() {
6397 final IBinder token =
6398 mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
6399 // Make only restore Autofill once
6400 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
6401 mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY);
6402 getAutofillManager().onPendingSaveUi(AutofillManager.PENDING_UI_OPERATION_RESTORE,
6403 token);
6404 }
6405
6406 /**
Winson Chung3b3f4642014-04-22 10:08:18 -07006407 * Call this when your activity is done and should be closed. The
6408 * ActivityResult is propagated back to whoever launched you via
6409 * onActivityResult().
6410 */
6411 public void finish() {
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07006412 finish(DONT_FINISH_TASK_WITH_ACTIVITY);
Winson Chung3b3f4642014-04-22 10:08:18 -07006413 }
6414
6415 /**
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07006416 * Finish this activity as well as all activities immediately below it
6417 * in the current task that have the same affinity. This is typically
6418 * used when an application can be launched on to another task (such as
6419 * from an ACTION_VIEW of a content type it understands) and the user
6420 * has used the up navigation to switch out of the current task and in
6421 * to its own task. In this case, if the user has navigated down into
6422 * any other activities of the second application, all of those should
6423 * be removed from the original task as part of the task switch.
6424 *
6425 * <p>Note that this finish does <em>not</em> allow you to deliver results
6426 * to the previous activity, and an exception will be thrown if you are trying
6427 * to do so.</p>
6428 */
6429 public void finishAffinity() {
6430 if (mParent != null) {
6431 throw new IllegalStateException("Can not be called from an embedded activity");
6432 }
6433 if (mResultCode != RESULT_CANCELED || mResultData != null) {
6434 throw new IllegalStateException("Can not be called to deliver a result");
6435 }
6436 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006437 if (ActivityTaskManager.getService().finishActivityAffinity(mToken)) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07006438 mFinished = true;
6439 }
6440 } catch (RemoteException e) {
6441 // Empty
6442 }
6443 }
6444
6445 /**
RoboErik55011652014-07-09 15:05:53 -07006446 * This is called when a child activity of this one calls its
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 * {@link #finish} method. The default implementation simply calls
6448 * finish() on this activity (the parent), finishing the entire group.
RoboErik55011652014-07-09 15:05:53 -07006449 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 * @param child The activity making the call.
RoboErik55011652014-07-09 15:05:53 -07006451 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 * @see #finish
Charles Chenc380f022019-08-13 18:39:17 +08006453 * @deprecated Use {@link #finish()} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 */
Charles Chenc380f022019-08-13 18:39:17 +08006455 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 public void finishFromChild(Activity child) {
6457 finish();
6458 }
6459
6460 /**
George Mountcb4b7d92014-02-25 10:47:55 -08006461 * Reverses the Activity Scene entry Transition and triggers the calling Activity
6462 * to reverse its exit Transition. When the exit Transition completes,
6463 * {@link #finish()} is called. If no entry Transition was used, finish() is called
6464 * immediately and the Activity exit Transition is run.
George Mount62ab9b72014-05-02 13:51:17 -07006465 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(Activity, android.util.Pair[])
George Mountcb4b7d92014-02-25 10:47:55 -08006466 */
Craig Mautner73f843d2014-05-19 09:42:28 -07006467 public void finishAfterTransition() {
George Mount62ab9b72014-05-02 13:51:17 -07006468 if (!mActivityTransitionState.startExitBackTransition(this)) {
George Mount31a21722014-03-24 17:44:36 -07006469 finish();
6470 }
George Mountcb4b7d92014-02-25 10:47:55 -08006471 }
6472
6473 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 * Force finish another activity that you had previously started with
6475 * {@link #startActivityForResult}.
RoboErik55011652014-07-09 15:05:53 -07006476 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 * @param requestCode The request code of the activity that you had
6478 * given to startActivityForResult(). If there are multiple
6479 * activities started with this request code, they
6480 * will all be finished.
6481 */
6482 public void finishActivity(int requestCode) {
6483 if (mParent == null) {
6484 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006485 ActivityTaskManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 .finishSubActivity(mToken, mEmbeddedID, requestCode);
6487 } catch (RemoteException e) {
6488 // Empty
6489 }
6490 } else {
6491 mParent.finishActivityFromChild(this, requestCode);
6492 }
6493 }
6494
6495 /**
6496 * This is called when a child activity of this one calls its
6497 * finishActivity().
RoboErik55011652014-07-09 15:05:53 -07006498 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 * @param child The activity making the call.
6500 * @param requestCode Request code that had been used to start the
6501 * activity.
Charles Chenc380f022019-08-13 18:39:17 +08006502 * @deprecated Use {@link #finishActivity(int)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 */
Charles Chenc380f022019-08-13 18:39:17 +08006504 @Deprecated
Tor Norbyed9273d62013-05-30 15:59:53 -07006505 public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006507 ActivityTaskManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 .finishSubActivity(mToken, child.mEmbeddedID, requestCode);
6509 } catch (RemoteException e) {
6510 // Empty
6511 }
6512 }
6513
6514 /**
Winson Chung3b3f4642014-04-22 10:08:18 -07006515 * Call this when your activity is done and should be closed and the task should be completely
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07006516 * removed as a part of finishing the root activity of the task.
Winson Chung3b3f4642014-04-22 10:08:18 -07006517 */
6518 public void finishAndRemoveTask() {
Wale Ogunwaleba7881c2015-08-01 19:28:29 -07006519 finish(FINISH_TASK_WITH_ROOT_ACTIVITY);
Winson Chung3b3f4642014-04-22 10:08:18 -07006520 }
6521
6522 /**
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006523 * Ask that the local app instance of this activity be released to free up its memory.
6524 * This is asking for the activity to be destroyed, but does <b>not</b> finish the activity --
6525 * a new instance of the activity will later be re-created if needed due to the user
6526 * navigating back to it.
6527 *
6528 * @return Returns true if the activity was in a state that it has started the process
6529 * of destroying its current instance; returns false if for any reason this could not
6530 * be done: it is currently visible to the user, it is already being destroyed, it is
6531 * being finished, it hasn't yet saved its state, etc.
6532 */
6533 public boolean releaseInstance() {
6534 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006535 return ActivityTaskManager.getService().releaseActivityInstance(mToken);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07006536 } catch (RemoteException e) {
6537 // Empty
6538 }
6539 return false;
6540 }
6541
6542 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 * Called when an activity you launched exits, giving you the requestCode
6544 * you started it with, the resultCode it returned, and any additional
6545 * data from it. The <var>resultCode</var> will be
6546 * {@link #RESULT_CANCELED} if the activity explicitly returned that,
6547 * didn't return any result, or crashed during its operation.
RoboErik55011652014-07-09 15:05:53 -07006548 *
Diego Vela6e99bfc2020-04-21 16:22:47 -07006549 * <p>An activity can never receive a result in the resumed state. You can count on
6550 * {@link #onResume} being called after this method, though not necessarily immediately after.
6551 * If the activity was resumed, it will be paused and the result will be delivered, followed
6552 * by {@link #onResume}. If the activity wasn't in the resumed state, then the result will
6553 * be delivered, with {@link #onResume} called sometime later when the activity becomes active
6554 * again.
RoboErik55011652014-07-09 15:05:53 -07006555 *
Ricardo Cervera92f6a742014-04-04 11:17:06 -07006556 * <p>This method is never invoked if your activity sets
6557 * {@link android.R.styleable#AndroidManifestActivity_noHistory noHistory} to
6558 * <code>true</code>.
Ricardo Cervera93f94c22015-01-16 09:54:30 -08006559 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 * @param requestCode The integer request code originally supplied to
6561 * startActivityForResult(), allowing you to identify who this
6562 * result came from.
6563 * @param resultCode The integer result code returned by the child activity
6564 * through its setResult().
6565 * @param data An Intent, which can return result data to the caller
6566 * (various data can be attached to Intent "extras").
RoboErik55011652014-07-09 15:05:53 -07006567 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 * @see #startActivityForResult
6569 * @see #createPendingResult
6570 * @see #setResult(int)
6571 */
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07006572 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
6574
6575 /**
George Mount62ab9b72014-05-02 13:51:17 -07006576 * Called when an activity you launched with an activity transition exposes this
6577 * Activity through a returning activity transition, giving you the resultCode
6578 * and any additional data from it. This method will only be called if the activity
6579 * set a result code other than {@link #RESULT_CANCELED} and it supports activity
George Mount9826f632014-09-11 08:50:09 -07006580 * transitions with {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
George Mount62ab9b72014-05-02 13:51:17 -07006581 *
6582 * <p>The purpose of this function is to let the called Activity send a hint about
6583 * its state so that this underlying Activity can prepare to be exposed. A call to
6584 * this method does not guarantee that the called Activity has or will be exiting soon.
6585 * It only indicates that it will expose this Activity's Window and it has
6586 * some data to pass to prepare it.</p>
6587 *
6588 * @param resultCode The integer result code returned by the child activity
6589 * through its setResult().
6590 * @param data An Intent, which can return result data to the caller
6591 * (various data can be attached to Intent "extras").
6592 */
Craig Mautner7a629c22014-09-04 14:57:04 -07006593 public void onActivityReenter(int resultCode, Intent data) {
George Mount62ab9b72014-05-02 13:51:17 -07006594 }
6595
6596 /**
RoboErik55011652014-07-09 15:05:53 -07006597 * Create a new PendingIntent object which you can hand to others
6598 * for them to use to send result data back to your
6599 * {@link #onActivityResult} callback. The created object will be either
6600 * one-shot (becoming invalid after a result is sent back) or multiple
6601 * (allowing any number of results to be sent through it).
6602 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 * @param requestCode Private request code for the sender that will be
6604 * associated with the result data when it is returned. The sender can not
6605 * modify this value, allowing you to identify incoming results.
6606 * @param data Default data to supply in the result, which may be modified
6607 * by the sender.
6608 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT PendingIntent.FLAG_ONE_SHOT},
6609 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE},
6610 * {@link PendingIntent#FLAG_CANCEL_CURRENT PendingIntent.FLAG_CANCEL_CURRENT},
6611 * {@link PendingIntent#FLAG_UPDATE_CURRENT PendingIntent.FLAG_UPDATE_CURRENT},
6612 * or any of the flags as supported by
6613 * {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
6614 * of the intent that can be supplied when the actual send happens.
RoboErik55011652014-07-09 15:05:53 -07006615 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 * @return Returns an existing or new PendingIntent matching the given
6617 * parameters. May return null only if
6618 * {@link PendingIntent#FLAG_NO_CREATE PendingIntent.FLAG_NO_CREATE} has been
6619 * supplied.
RoboErik55011652014-07-09 15:05:53 -07006620 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 * @see PendingIntent
6622 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006623 public PendingIntent createPendingResult(int requestCode, @NonNull Intent data,
6624 @PendingIntent.Flags int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 String packageName = getPackageName();
6626 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07006627 data.prepareToLeaveProcess(this);
Philip P. Moltmann12ac3f42020-03-05 15:01:29 -08006628 IIntentSender target = ActivityManager.getService().getIntentSenderWithFeature(
6629 ActivityManager.INTENT_SENDER_ACTIVITY_RESULT, packageName, getAttributionTag(),
6630 mParent == null ? mToken : mParent.mToken, mEmbeddedID, requestCode,
6631 new Intent[]{data}, null, flags, null, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 return target != null ? new PendingIntent(target) : null;
6633 } catch (RemoteException e) {
6634 // Empty
6635 }
6636 return null;
6637 }
6638
6639 /**
6640 * Change the desired orientation of this activity. If the activity
6641 * is currently in the foreground or otherwise impacting the screen
6642 * orientation, the screen will immediately be changed (possibly causing
6643 * the activity to be restarted). Otherwise, this will be used the next
6644 * time the activity is visible.
RoboErik55011652014-07-09 15:05:53 -07006645 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 * @param requestedOrientation An orientation constant as used in
6647 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6648 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006649 public void setRequestedOrientation(@ActivityInfo.ScreenOrientation int requestedOrientation) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 if (mParent == null) {
6651 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006652 ActivityTaskManager.getService().setRequestedOrientation(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 mToken, requestedOrientation);
6654 } catch (RemoteException e) {
6655 // Empty
6656 }
6657 } else {
6658 mParent.setRequestedOrientation(requestedOrientation);
6659 }
6660 }
RoboErik55011652014-07-09 15:05:53 -07006661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 /**
6663 * Return the current requested orientation of the activity. This will
6664 * either be the orientation requested in its component's manifest, or
6665 * the last requested orientation given to
6666 * {@link #setRequestedOrientation(int)}.
RoboErik55011652014-07-09 15:05:53 -07006667 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 * @return Returns an orientation constant as used in
6669 * {@link ActivityInfo#screenOrientation ActivityInfo.screenOrientation}.
6670 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006671 @ActivityInfo.ScreenOrientation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006672 public int getRequestedOrientation() {
6673 if (mParent == null) {
6674 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006675 return ActivityTaskManager.getService()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 .getRequestedOrientation(mToken);
6677 } catch (RemoteException e) {
6678 // Empty
6679 }
6680 } else {
6681 return mParent.getRequestedOrientation();
6682 }
6683 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
6684 }
RoboErik55011652014-07-09 15:05:53 -07006685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 /**
6687 * Return the identifier of the task this activity is in. This identifier
6688 * will remain the same for the lifetime of the activity.
RoboErik55011652014-07-09 15:05:53 -07006689 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 * @return Task identifier, an opaque integer.
6691 */
6692 public int getTaskId() {
6693 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006694 return ActivityTaskManager.getService().getTaskForActivity(mToken, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 } catch (RemoteException e) {
6696 return -1;
6697 }
6698 }
6699
6700 /**
6701 * Return whether this activity is the root of a task. The root is the
6702 * first activity in a task.
RoboErik55011652014-07-09 15:05:53 -07006703 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 * @return True if this is the root activity, else false.
6705 */
6706 public boolean isTaskRoot() {
Mathew Inwoodd6973862019-12-05 10:15:19 +00006707 return mWindowControllerCallback.isTaskRoot();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 }
6709
6710 /**
6711 * Move the task containing this activity to the back of the activity
6712 * stack. The activity's order within the task is unchanged.
RoboErik55011652014-07-09 15:05:53 -07006713 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 * @param nonRoot If false then this only works if the activity is the root
6715 * of a task; if true it will work for any activity in
6716 * a task.
RoboErik55011652014-07-09 15:05:53 -07006717 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 * @return If the task was moved (or it was already at the
6719 * back) true is returned, else false.
6720 */
6721 public boolean moveTaskToBack(boolean nonRoot) {
6722 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006723 return ActivityTaskManager.getService().moveActivityTaskToBack(mToken, nonRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 } catch (RemoteException e) {
6725 // Empty
6726 }
6727 return false;
6728 }
6729
6730 /**
6731 * Returns class name for this activity with the package prefix removed.
6732 * This is the default name used to read and write settings.
RoboErik55011652014-07-09 15:05:53 -07006733 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 * @return The local class name.
6735 */
Tor Norbyed9273d62013-05-30 15:59:53 -07006736 @NonNull
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 public String getLocalClassName() {
6738 final String pkg = getPackageName();
6739 final String cls = mComponent.getClassName();
6740 int packageLen = pkg.length();
6741 if (!cls.startsWith(pkg) || cls.length() <= packageLen
6742 || cls.charAt(packageLen) != '.') {
6743 return cls;
6744 }
6745 return cls.substring(packageLen+1);
6746 }
RoboErik55011652014-07-09 15:05:53 -07006747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 /**
Felipe Leme17292d12017-10-24 14:03:10 -07006749 * Returns the complete component name of this activity.
RoboErik55011652014-07-09 15:05:53 -07006750 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 * @return Returns the complete component name for this activity
6752 */
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006753 public ComponentName getComponentName() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 return mComponent;
6755 }
6756
Svetoslav Ganov24c90452017-12-27 15:17:14 -08006757 /** @hide */
6758 @Override
6759 public final ComponentName autofillClientGetComponentName() {
6760 return getComponentName();
6761 }
6762
Felipe Lemecbf7f262019-04-17 13:57:59 -07006763 /** @hide */
6764 @Override
6765 public final ComponentName contentCaptureClientGetComponentName() {
6766 return getComponentName();
6767 }
6768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 /**
6770 * Retrieve a {@link SharedPreferences} object for accessing preferences
6771 * that are private to this activity. This simply calls the underlying
6772 * {@link #getSharedPreferences(String, int)} method by passing in this activity's
6773 * class name as the preferences name.
RoboErik55011652014-07-09 15:05:53 -07006774 *
6775 * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default
Jeff Sharkey634dc422016-01-30 17:44:15 -07006776 * operation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 *
6778 * @return Returns the single SharedPreferences instance that can be used
6779 * to retrieve and modify the preference values.
6780 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -06006781 public SharedPreferences getPreferences(@Context.PreferencesMode int mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 return getSharedPreferences(getLocalClassName(), mode);
6783 }
RoboErik55011652014-07-09 15:05:53 -07006784
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006785 private void ensureSearchManager() {
6786 if (mSearchManager != null) {
6787 return;
6788 }
RoboErik55011652014-07-09 15:05:53 -07006789
Jeff Sharkey49ca5292016-05-10 12:54:45 -06006790 try {
6791 mSearchManager = new SearchManager(this, null);
6792 } catch (ServiceNotFoundException e) {
6793 throw new IllegalStateException(e);
6794 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006795 }
Tor Norbyed9273d62013-05-30 15:59:53 -07006796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 @Override
Tor Norbyed9273d62013-05-30 15:59:53 -07006798 public Object getSystemService(@ServiceName @NonNull String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 if (getBaseContext() == null) {
6800 throw new IllegalStateException(
6801 "System services not available to Activities before onCreate()");
6802 }
6803
6804 if (WINDOW_SERVICE.equals(name)) {
6805 return mWindowManager;
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01006806 } else if (SEARCH_SERVICE.equals(name)) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006807 ensureSearchManager();
Bjorn Bringert8d17f3f2009-06-05 13:22:28 +01006808 return mSearchManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 }
6810 return super.getSystemService(name);
6811 }
6812
6813 /**
6814 * Change the title associated with this activity. If this is a
6815 * top-level activity, the title for its window will change. If it
6816 * is an embedded activity, the parent can do whatever it wants
6817 * with it.
6818 */
6819 public void setTitle(CharSequence title) {
6820 mTitle = title;
6821 onTitleChanged(title, mTitleColor);
6822
6823 if (mParent != null) {
6824 mParent.onChildTitleChanged(this, title);
6825 }
6826 }
6827
6828 /**
6829 * Change the title associated with this activity. If this is a
6830 * top-level activity, the title for its window will change. If it
6831 * is an embedded activity, the parent can do whatever it wants
6832 * with it.
6833 */
6834 public void setTitle(int titleId) {
6835 setTitle(getText(titleId));
6836 }
6837
Alan Viverette2525d9c2013-11-15 14:42:19 -08006838 /**
6839 * Change the color of the title associated with this activity.
6840 * <p>
6841 * This method is deprecated starting in API Level 11 and replaced by action
6842 * bar styles. For information on styling the Action Bar, read the <a
6843 * href="{@docRoot} guide/topics/ui/actionbar.html">Action Bar</a> developer
6844 * guide.
6845 *
6846 * @deprecated Use action bar styles instead.
6847 */
6848 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 public void setTitleColor(int textColor) {
6850 mTitleColor = textColor;
6851 onTitleChanged(mTitle, textColor);
6852 }
6853
6854 public final CharSequence getTitle() {
6855 return mTitle;
6856 }
6857
6858 public final int getTitleColor() {
6859 return mTitleColor;
6860 }
6861
6862 protected void onTitleChanged(CharSequence title, int color) {
6863 if (mTitleReady) {
6864 final Window win = getWindow();
6865 if (win != null) {
6866 win.setTitle(title);
6867 if (color != 0) {
6868 win.setTitleColor(color);
6869 }
6870 }
Adam Powellaf2d8592014-08-26 18:06:40 -07006871 if (mActionBar != null) {
6872 mActionBar.setWindowTitle(title);
6873 }
Adam Powella557fdc2014-08-21 18:05:53 -07006874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 }
6876
6877 protected void onChildTitleChanged(Activity childActivity, CharSequence title) {
6878 }
6879
6880 /**
Winson Chunga449dc02014-05-16 11:15:04 -07006881 * Sets information describing the task with this activity for presentation inside the Recents
6882 * System UI. When {@link ActivityManager#getRecentTasks} is called, the activities of each task
6883 * are traversed in order from the topmost activity to the bottommost. The traversal continues
6884 * for each property until a suitable value is found. For each task the taskDescription will be
6885 * returned in {@link android.app.ActivityManager.TaskDescription}.
Craig Mautner2fbd7542014-03-21 09:34:07 -07006886 *
6887 * @see ActivityManager#getRecentTasks
Winson Chunga449dc02014-05-16 11:15:04 -07006888 * @see android.app.ActivityManager.TaskDescription
Craig Mautner2fbd7542014-03-21 09:34:07 -07006889 *
Winson Chunga449dc02014-05-16 11:15:04 -07006890 * @param taskDescription The TaskDescription properties that describe the task with this activity
Craig Mautner2fbd7542014-03-21 09:34:07 -07006891 */
Winson Chunga449dc02014-05-16 11:15:04 -07006892 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
Winsonb6403152016-02-23 13:32:09 -08006893 if (mTaskDescription != taskDescription) {
Jorim Jaggif4156ea2017-04-10 18:39:04 -07006894 mTaskDescription.copyFromPreserveHiddenFields(taskDescription);
Winsonb6403152016-02-23 13:32:09 -08006895 // Scale the icon down to something reasonable if it is provided
6896 if (taskDescription.getIconFilename() == null && taskDescription.getIcon() != null) {
6897 final int size = ActivityManager.getLauncherLargeIconSizeInner(this);
6898 final Bitmap icon = Bitmap.createScaledBitmap(taskDescription.getIcon(), size, size,
6899 true);
Winson Chungd6722032020-02-18 15:16:08 -08006900 mTaskDescription.setIcon(Icon.createWithBitmap(icon));
Winsonb6403152016-02-23 13:32:09 -08006901 }
Craig Mautner2fbd7542014-03-21 09:34:07 -07006902 }
6903 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07006904 ActivityTaskManager.getService().setTaskDescription(mToken, mTaskDescription);
Craig Mautner2fbd7542014-03-21 09:34:07 -07006905 } catch (RemoteException e) {
6906 }
6907 }
6908
6909 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006910 * Sets the visibility of the progress bar in the title.
6911 * <p>
6912 * In order for the progress bar to be shown, the feature must be requested
6913 * via {@link #requestWindowFeature(int)}.
RoboErik55011652014-07-09 15:05:53 -07006914 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 * @param visible Whether to show the progress bars in the title.
Alan Viverette4aef7c82015-09-04 14:14:50 -04006916 * @deprecated No longer supported starting in API 21.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 */
Alan Viverette4aef7c82015-09-04 14:14:50 -04006918 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 public final void setProgressBarVisibility(boolean visible) {
6920 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON :
6921 Window.PROGRESS_VISIBILITY_OFF);
6922 }
6923
6924 /**
6925 * Sets the visibility of the indeterminate progress bar in the title.
6926 * <p>
6927 * In order for the progress bar to be shown, the feature must be requested
6928 * via {@link #requestWindowFeature(int)}.
6929 *
6930 * @param visible Whether to show the progress bars in the title.
Alan Viverette4aef7c82015-09-04 14:14:50 -04006931 * @deprecated No longer supported starting in API 21.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 */
Alan Viverette4aef7c82015-09-04 14:14:50 -04006933 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 public final void setProgressBarIndeterminateVisibility(boolean visible) {
6935 getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
6936 visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF);
6937 }
RoboErik55011652014-07-09 15:05:53 -07006938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 /**
6940 * Sets whether the horizontal progress bar in the title should be indeterminate (the circular
6941 * is always indeterminate).
6942 * <p>
6943 * In order for the progress bar to be shown, the feature must be requested
6944 * via {@link #requestWindowFeature(int)}.
RoboErik55011652014-07-09 15:05:53 -07006945 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 * @param indeterminate Whether the horizontal progress bar should be indeterminate.
Alan Viverette4aef7c82015-09-04 14:14:50 -04006947 * @deprecated No longer supported starting in API 21.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 */
Alan Viverette4aef7c82015-09-04 14:14:50 -04006949 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 public final void setProgressBarIndeterminate(boolean indeterminate) {
6951 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
George Mounte1803372014-02-26 19:00:52 +00006952 indeterminate ? Window.PROGRESS_INDETERMINATE_ON
6953 : Window.PROGRESS_INDETERMINATE_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 }
RoboErik55011652014-07-09 15:05:53 -07006955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 /**
6957 * Sets the progress for the progress bars in the title.
6958 * <p>
6959 * In order for the progress bar to be shown, the feature must be requested
6960 * via {@link #requestWindowFeature(int)}.
RoboErik55011652014-07-09 15:05:53 -07006961 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 * @param progress The progress for the progress bar. Valid ranges are from
6963 * 0 to 10000 (both inclusive). If 10000 is given, the progress
6964 * bar will be completely filled and will fade out.
Alan Viverette4aef7c82015-09-04 14:14:50 -04006965 * @deprecated No longer supported starting in API 21.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 */
Alan Viverette4aef7c82015-09-04 14:14:50 -04006967 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 public final void setProgress(int progress) {
6969 getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START);
6970 }
RoboErik55011652014-07-09 15:05:53 -07006971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 /**
6973 * Sets the secondary progress for the progress bar in the title. This
6974 * progress is drawn between the primary progress (set via
6975 * {@link #setProgress(int)} and the background. It can be ideal for media
6976 * scenarios such as showing the buffering progress while the default
6977 * progress shows the play progress.
6978 * <p>
6979 * In order for the progress bar to be shown, the feature must be requested
6980 * via {@link #requestWindowFeature(int)}.
RoboErik55011652014-07-09 15:05:53 -07006981 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
6983 * 0 to 10000 (both inclusive).
Alan Viverette4aef7c82015-09-04 14:14:50 -04006984 * @deprecated No longer supported starting in API 21.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 */
Alan Viverette4aef7c82015-09-04 14:14:50 -04006986 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 public final void setSecondaryProgress(int secondaryProgress) {
6988 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
6989 secondaryProgress + Window.PROGRESS_SECONDARY_START);
6990 }
6991
6992 /**
6993 * Suggests an audio stream whose volume should be changed by the hardware
6994 * volume controls.
6995 * <p>
6996 * The suggested audio stream will be tied to the window of this Activity.
RoboErik55011652014-07-09 15:05:53 -07006997 * Volume requests which are received while the Activity is in the
6998 * foreground will affect this stream.
6999 * <p>
7000 * It is not guaranteed that the hardware volume controls will always change
7001 * this stream's volume (for example, if a call is in progress, its stream's
7002 * volume may be changed instead). To reset back to the default, use
7003 * {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
7004 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 * @param streamType The type of the audio stream whose volume should be
RoboErik55011652014-07-09 15:05:53 -07007006 * changed by the hardware volume controls.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007007 */
7008 public final void setVolumeControlStream(int streamType) {
7009 getWindow().setVolumeControlStream(streamType);
7010 }
7011
7012 /**
7013 * Gets the suggested audio stream whose volume should be changed by the
Tor Norbyed9273d62013-05-30 15:59:53 -07007014 * hardware volume controls.
RoboErik55011652014-07-09 15:05:53 -07007015 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 * @return The suggested audio stream type whose volume should be changed by
7017 * the hardware volume controls.
7018 * @see #setVolumeControlStream(int)
7019 */
7020 public final int getVolumeControlStream() {
7021 return getWindow().getVolumeControlStream();
7022 }
RoboErik55011652014-07-09 15:05:53 -07007023
7024 /**
7025 * Sets a {@link MediaController} to send media keys and volume changes to.
7026 * <p>
7027 * The controller will be tied to the window of this Activity. Media key and
7028 * volume events which are received while the Activity is in the foreground
7029 * will be forwarded to the controller and used to invoke transport controls
7030 * or adjust the volume. This may be used instead of or in addition to
7031 * {@link #setVolumeControlStream} to affect a specific session instead of a
7032 * specific stream.
7033 * <p>
7034 * It is not guaranteed that the hardware volume controls will always change
7035 * this session's volume (for example, if a call is in progress, its
7036 * stream's volume may be changed instead). To reset back to the default use
7037 * null as the controller.
7038 *
7039 * @param controller The controller for the session which should receive
7040 * media keys and volume changes.
7041 */
7042 public final void setMediaController(MediaController controller) {
7043 getWindow().setMediaController(controller);
7044 }
7045
7046 /**
7047 * Gets the controller which should be receiving media key and volume events
7048 * while this activity is in the foreground.
7049 *
7050 * @return The controller which should receive events.
7051 * @see #setMediaController(android.media.session.MediaController)
7052 */
7053 public final MediaController getMediaController() {
7054 return getWindow().getMediaController();
7055 }
7056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 /**
7058 * Runs the specified action on the UI thread. If the current thread is the UI
7059 * thread, then the action is executed immediately. If the current thread is
7060 * not the UI thread, the action is posted to the event queue of the UI thread.
7061 *
7062 * @param action the action to run on the UI thread
7063 */
7064 public final void runOnUiThread(Runnable action) {
7065 if (Thread.currentThread() != mUiThread) {
7066 mHandler.post(action);
7067 } else {
7068 action.run();
7069 }
7070 }
7071
Svetoslav Ganov24c90452017-12-27 15:17:14 -08007072 /** @hide */
7073 @Override
7074 public final void autofillClientRunOnUiThread(Runnable action) {
7075 runOnUiThread(action);
7076 }
7077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 /**
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07007079 * Standard implementation of
7080 * {@link android.view.LayoutInflater.Factory#onCreateView} used when
7081 * inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackborn625ac272010-09-17 18:29:22 -07007082 * This implementation does nothing and is for
7083 * pre-{@link android.os.Build.VERSION_CODES#HONEYCOMB} apps. Newer apps
7084 * should use {@link #onCreateView(View, String, Context, AttributeSet)}.
7085 *
7086 * @see android.view.LayoutInflater#createView
7087 * @see android.view.Window#getLayoutInflater
7088 */
Tor Norbyed9273d62013-05-30 15:59:53 -07007089 @Nullable
Ian Lake0c807f42018-09-12 14:03:27 -07007090 public View onCreateView(@NonNull String name, @NonNull Context context,
7091 @NonNull AttributeSet attrs) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07007092 return null;
7093 }
7094
7095 /**
7096 * Standard implementation of
7097 * {@link android.view.LayoutInflater.Factory2#onCreateView(View, String, Context, AttributeSet)}
7098 * used when inflating with the LayoutInflater returned by {@link #getSystemService}.
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07007099 * This implementation handles <fragment> tags to embed fragments inside
7100 * of the activity.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 *
7102 * @see android.view.LayoutInflater#createView
7103 * @see android.view.Window#getLayoutInflater
7104 */
Ian Lake0c807f42018-09-12 14:03:27 -07007105 @Nullable
7106 public View onCreateView(@Nullable View parent, @NonNull String name,
7107 @NonNull Context context, @NonNull AttributeSet attrs) {
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07007108 if (!"fragment".equals(name)) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07007109 return onCreateView(name, context, attrs);
Dianne Hackbornba51c3d2010-05-05 18:49:48 -07007110 }
RoboErik55011652014-07-09 15:05:53 -07007111
Adam Powell371a8092014-06-20 12:51:12 -07007112 return mFragments.onCreateView(parent, name, context, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 }
7114
Daniel Sandler69a48172010-06-23 16:29:36 -04007115 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -07007116 * Print the Activity's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07007117 * you run "adb shell dumpsys activity &lt;activity_component_name&gt;".
Dianne Hackborn625ac272010-09-17 18:29:22 -07007118 *
Dianne Hackborn30d71892010-12-11 10:37:55 -08007119 * @param prefix Desired prefix to prepend at each line of output.
Dianne Hackborn625ac272010-09-17 18:29:22 -07007120 * @param fd The raw file descriptor that the dump is being sent to.
7121 * @param writer The PrintWriter to which you should dump your state. This will be
7122 * closed for you after you return.
7123 * @param args additional arguments to the dump request.
7124 */
Ian Lake140fe122018-09-13 14:59:38 -07007125 public void dump(@NonNull String prefix, @Nullable FileDescriptor fd,
7126 @NonNull PrintWriter writer, @Nullable String[] args) {
Dianne Hackborn62bea2f2012-09-04 18:48:15 -07007127 dumpInner(prefix, fd, writer, args);
7128 }
7129
Ian Lake140fe122018-09-13 14:59:38 -07007130 void dumpInner(@NonNull String prefix, @Nullable FileDescriptor fd,
7131 @NonNull PrintWriter writer, @Nullable String[] args) {
Felipe Lemee348dc32018-11-05 12:35:29 -08007132 if (args != null && args.length > 0) {
7133 // Handle special cases
7134 switch (args[0]) {
7135 case "--autofill":
7136 dumpAutofillManager(prefix, writer);
7137 return;
Felipe Lemeb718e032018-12-10 09:44:23 -08007138 case "--contentcapture":
7139 dumpContentCaptureManager(prefix, writer);
Felipe Lemee348dc32018-11-05 12:35:29 -08007140 return;
7141 }
Felipe Lemeb546ca72018-08-15 08:44:12 -07007142 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08007143 writer.print(prefix); writer.print("Local Activity ");
7144 writer.print(Integer.toHexString(System.identityHashCode(this)));
7145 writer.println(" State:");
7146 String innerPrefix = prefix + " ";
7147 writer.print(innerPrefix); writer.print("mResumed=");
7148 writer.print(mResumed); writer.print(" mStopped=");
7149 writer.print(mStopped); writer.print(" mFinished=");
7150 writer.println(mFinished);
Hongwei Wangf7e5a232020-05-06 15:49:44 -07007151 writer.print(innerPrefix); writer.print("mIsInMultiWindowMode=");
7152 writer.print(mIsInMultiWindowMode);
7153 writer.print(" mIsInPictureInPictureMode=");
7154 writer.println(mIsInPictureInPictureMode);
Dianne Hackborn30d71892010-12-11 10:37:55 -08007155 writer.print(innerPrefix); writer.print("mChangingConfigurations=");
7156 writer.println(mChangingConfigurations);
7157 writer.print(innerPrefix); writer.print("mCurrentConfig=");
7158 writer.println(mCurrentConfig);
Riddle Hsud490c572020-04-17 01:39:27 +08007159 if (getResources().hasOverrideDisplayAdjustments()) {
7160 writer.print(innerPrefix);
7161 writer.print("FixedRotationAdjustments=");
7162 writer.println(getResources().getDisplayAdjustments().getFixedRotationAdjustments());
7163 }
Jeff Brown5182c782013-10-15 20:31:52 -07007164
Todd Kennedya5fc6f02015-04-14 18:22:54 -07007165 mFragments.dumpLoaders(innerPrefix, fd, writer, args);
7166 mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
Dianne Hackborn57dd7372015-07-27 18:11:14 -07007167 if (mVoiceInteractor != null) {
7168 mVoiceInteractor.dump(innerPrefix, fd, writer, args);
7169 }
Jeff Brown5182c782013-10-15 20:31:52 -07007170
Michael Wright5f48dc72013-11-01 12:42:49 -07007171 if (getWindow() != null &&
7172 getWindow().peekDecorView() != null &&
7173 getWindow().peekDecorView().getViewRootImpl() != null) {
7174 getWindow().peekDecorView().getViewRootImpl().dump(prefix, fd, writer, args);
7175 }
Jeff Brown5182c782013-10-15 20:31:52 -07007176
7177 mHandler.getLooper().dump(new PrintWriterPrinter(writer), prefix);
Felipe Lemec24a56a2017-08-03 14:27:57 -07007178
Felipe Lemeb546ca72018-08-15 08:44:12 -07007179 dumpAutofillManager(prefix, writer);
Felipe Lemeb718e032018-12-10 09:44:23 -08007180 dumpContentCaptureManager(prefix, writer);
Felipe Lemeb546ca72018-08-15 08:44:12 -07007181
7182 ResourcesManager.getInstance().dump(prefix, writer);
7183 }
7184
7185 void dumpAutofillManager(String prefix, PrintWriter writer) {
Felipe Leme9d16dff2018-01-29 18:12:43 -08007186 final AutofillManager afm = getAutofillManager();
Felipe Lemec24a56a2017-08-03 14:27:57 -07007187 if (afm != null) {
Felipe Lemeb546ca72018-08-15 08:44:12 -07007188 afm.dump(prefix, writer);
Svet Ganov47b37aa2018-02-16 00:11:39 -08007189 writer.print(prefix); writer.print("Autofill Compat Mode: ");
7190 writer.println(isAutofillCompatibilityEnabled());
Felipe Leme686128e2017-10-17 14:02:20 -07007191 } else {
7192 writer.print(prefix); writer.println("No AutofillManager");
Felipe Lemec24a56a2017-08-03 14:27:57 -07007193 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07007194 }
7195
Felipe Lemeb718e032018-12-10 09:44:23 -08007196 void dumpContentCaptureManager(String prefix, PrintWriter writer) {
7197 final ContentCaptureManager cm = getContentCaptureManager();
7198 if (cm != null) {
7199 cm.dump(prefix, writer);
Felipe Lemee348dc32018-11-05 12:35:29 -08007200 } else {
Felipe Lemeb718e032018-12-10 09:44:23 -08007201 writer.print(prefix); writer.println("No ContentCaptureManager");
Felipe Lemee348dc32018-11-05 12:35:29 -08007202 }
7203 }
7204
Dianne Hackborn625ac272010-09-17 18:29:22 -07007205 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04007206 * Bit indicating that this activity is "immersive" and should not be
7207 * interrupted by notifications if possible.
7208 *
7209 * This value is initially set by the manifest property
7210 * <code>android:immersive</code> but may be changed at runtime by
7211 * {@link #setImmersive}.
7212 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07007213 * @see #setImmersive(boolean)
Daniel Sandler69a48172010-06-23 16:29:36 -04007214 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7215 */
7216 public boolean isImmersive() {
7217 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007218 return ActivityTaskManager.getService().isImmersive(mToken);
Daniel Sandler69a48172010-06-23 16:29:36 -04007219 } catch (RemoteException e) {
7220 return false;
7221 }
7222 }
7223
7224 /**
Craig Mautnerd61dc202014-07-07 11:09:11 -07007225 * Indication of whether this is the highest level activity in this task. Can be used to
7226 * determine whether an activity launched by this activity was placed in the same task or
7227 * another task.
7228 *
7229 * @return true if this is the topmost, non-finishing activity in its task.
Craig Mautnerd61dc202014-07-07 11:09:11 -07007230 */
Sunny Goyald85bed52018-09-25 12:01:01 -07007231 final boolean isTopOfTask() {
George Mountf43ea5d2016-05-26 09:52:53 -07007232 if (mToken == null || mWindow == null) {
George Mountd0ca0e02016-03-29 10:32:56 -07007233 return false;
7234 }
Craig Mautnerd61dc202014-07-07 11:09:11 -07007235 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007236 return ActivityTaskManager.getService().isTopOfTask(getActivityToken());
Craig Mautnerd61dc202014-07-07 11:09:11 -07007237 } catch (RemoteException e) {
7238 return false;
7239 }
7240 }
7241
7242 /**
Louis Chang65b486e2019-06-05 16:00:03 +08007243 * Convert an activity, which particularly with {@link android.R.attr#windowIsTranslucent} or
7244 * {@link android.R.attr#windowIsFloating} attribute, to a fullscreen opaque activity, or
7245 * convert it from opaque back to translucent.
7246 *
7247 * @param translucent {@code true} convert from opaque to translucent.
7248 * {@code false} convert from translucent to opaque.
7249 * @return The result of setting translucency. Return {@code true} if set successfully,
7250 * {@code false} otherwise.
7251 */
7252 public boolean setTranslucent(boolean translucent) {
7253 if (translucent) {
7254 return convertToTranslucent(null /* callback */, null /* options */);
7255 } else {
7256 return convertFromTranslucentInternal();
7257 }
7258 }
7259
7260 /**
7261 * Convert an activity to a fullscreen opaque activity.
Craig Mautner5eda9b32013-07-02 11:58:16 -07007262 * <p>
Louis Chang65b486e2019-06-05 16:00:03 +08007263 * Call this whenever the background of a translucent activity has changed to become opaque.
7264 * Doing so will allow the {@link android.view.Surface} of the activity behind to be released.
Craig Mautner5eda9b32013-07-02 11:58:16 -07007265 *
George Mount62ab9b72014-05-02 13:51:17 -07007266 * @see #convertToTranslucent(android.app.Activity.TranslucentConversionListener,
7267 * ActivityOptions)
Craig Mautner5eda9b32013-07-02 11:58:16 -07007268 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07007269 *
7270 * @hide
Craig Mautner4addfc52013-06-25 08:05:45 -07007271 */
Jose Lima4b6c6692014-08-12 17:41:12 -07007272 @SystemApi
Craig Mautner5eda9b32013-07-02 11:58:16 -07007273 public void convertFromTranslucent() {
Louis Chang65b486e2019-06-05 16:00:03 +08007274 convertFromTranslucentInternal();
7275 }
7276
7277 private boolean convertFromTranslucentInternal() {
Craig Mautner4addfc52013-06-25 08:05:45 -07007278 try {
Craig Mautner5eda9b32013-07-02 11:58:16 -07007279 mTranslucentCallback = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007280 if (ActivityTaskManager.getService().convertFromTranslucent(mToken)) {
Craig Mautnerbc57cd12013-08-19 15:47:42 -07007281 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, true);
Louis Chang65b486e2019-06-05 16:00:03 +08007282 return true;
Craig Mautnerbc57cd12013-08-19 15:47:42 -07007283 }
Craig Mautner4addfc52013-06-25 08:05:45 -07007284 } catch (RemoteException e) {
7285 // pass
7286 }
Louis Chang65b486e2019-06-05 16:00:03 +08007287 return false;
Craig Mautner4addfc52013-06-25 08:05:45 -07007288 }
7289
7290 /**
Louis Chang65b486e2019-06-05 16:00:03 +08007291 * Convert an activity to a translucent activity.
Craig Mautner5eda9b32013-07-02 11:58:16 -07007292 * <p>
Louis Chang65b486e2019-06-05 16:00:03 +08007293 * Calling this allows the activity behind this one to be seen again. Once all such activities
Craig Mautner5eda9b32013-07-02 11:58:16 -07007294 * have been redrawn {@link TranslucentConversionListener#onTranslucentConversionComplete} will
7295 * be called indicating that it is safe to make this activity translucent again. Until
7296 * {@link TranslucentConversionListener#onTranslucentConversionComplete} is called the image
Louis Chang65b486e2019-06-05 16:00:03 +08007297 * behind the frontmost activity will be indeterminate.
Craig Mautner5eda9b32013-07-02 11:58:16 -07007298 *
Louis Chang65b486e2019-06-05 16:00:03 +08007299 * @param callback the method to call when all visible activities behind this one have been
7300 * drawn and it is safe to make this activity translucent again.
Craig Mautner233ceee2014-05-09 17:05:11 -07007301 * @param options activity options delivered to the activity below this one. The options
7302 * are retrieved using {@link #getActivityOptions}.
George Mount3cc716c2014-06-12 16:35:35 -07007303 * @return <code>true</code> if Window was opaque and will become translucent or
7304 * <code>false</code> if window was translucent and no change needed to be made.
Craig Mautner5eda9b32013-07-02 11:58:16 -07007305 *
7306 * @see #convertFromTranslucent()
7307 * @see TranslucentConversionListener
Chet Haaseabd3d772013-09-11 14:33:05 -07007308 *
7309 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07007310 */
Jose Lima4b6c6692014-08-12 17:41:12 -07007311 @SystemApi
George Mount3cc716c2014-06-12 16:35:35 -07007312 public boolean convertToTranslucent(TranslucentConversionListener callback,
Jose Lima5517ea72014-06-10 12:31:43 -07007313 ActivityOptions options) {
Craig Mautner233ceee2014-05-09 17:05:11 -07007314 boolean drawComplete;
Craig Mautner5eda9b32013-07-02 11:58:16 -07007315 try {
7316 mTranslucentCallback = callback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007317 mChangeCanvasToTranslucent = ActivityTaskManager.getService().convertToTranslucent(
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007318 mToken, options == null ? null : options.toBundle());
George Mount9e183972014-09-03 12:35:09 -07007319 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
Craig Mautner233ceee2014-05-09 17:05:11 -07007320 drawComplete = true;
Craig Mautner5eda9b32013-07-02 11:58:16 -07007321 } catch (RemoteException e) {
Craig Mautner233ceee2014-05-09 17:05:11 -07007322 // Make callback return as though it timed out.
7323 mChangeCanvasToTranslucent = false;
7324 drawComplete = false;
7325 }
7326 if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
7327 // Window is already translucent.
7328 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
Craig Mautner5eda9b32013-07-02 11:58:16 -07007329 }
George Mount3cc716c2014-06-12 16:35:35 -07007330 return mChangeCanvasToTranslucent;
Craig Mautner5eda9b32013-07-02 11:58:16 -07007331 }
7332
7333 /** @hide */
7334 void onTranslucentConversionComplete(boolean drawComplete) {
7335 if (mTranslucentCallback != null) {
7336 mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
7337 mTranslucentCallback = null;
7338 }
Craig Mautnerbc57cd12013-08-19 15:47:42 -07007339 if (mChangeCanvasToTranslucent) {
7340 WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
7341 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07007342 }
7343
Craig Mautnereb8abf72014-07-02 15:04:09 -07007344 /** @hide */
7345 public void onNewActivityOptions(ActivityOptions options) {
7346 mActivityTransitionState.setEnterActivityOptions(this, options);
7347 if (!mStopped) {
7348 mActivityTransitionState.enterReady(this);
7349 }
7350 }
7351
Craig Mautner5eda9b32013-07-02 11:58:16 -07007352 /**
Craig Mautner233ceee2014-05-09 17:05:11 -07007353 * Retrieve the ActivityOptions passed in from the launching activity or passed back
7354 * from an activity launched by this activity in its call to {@link
7355 * #convertToTranslucent(TranslucentConversionListener, ActivityOptions)}
7356 *
7357 * @return The ActivityOptions passed to {@link #convertToTranslucent}.
7358 * @hide
7359 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007360 @UnsupportedAppUsage
Craig Mautner233ceee2014-05-09 17:05:11 -07007361 ActivityOptions getActivityOptions() {
7362 try {
Sudheer Shankafc46e9b2016-10-21 17:55:27 -07007363 return ActivityOptions.fromBundle(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007364 ActivityTaskManager.getService().getActivityOptions(mToken));
Craig Mautner233ceee2014-05-09 17:05:11 -07007365 } catch (RemoteException e) {
7366 }
7367 return null;
7368 }
7369
7370 /**
Jose Lima4b6c6692014-08-12 17:41:12 -07007371 * Activities that want to remain visible behind a translucent activity above them must call
Craig Mautner64ccb702014-10-01 09:38:40 -07007372 * this method anytime between the start of {@link #onResume()} and the return from
7373 * {@link #onPause()}. If this call is successful then the activity will remain visible after
7374 * {@link #onPause()} is called, and is allowed to continue playing media in the background.
7375 *
7376 * <p>The actions of this call are reset each time that this activity is brought to the
7377 * front. That is, every time {@link #onResume()} is called the activity will be assumed
7378 * to not have requested visible behind. Therefore, if you want this activity to continue to
7379 * be visible in the background you must call this method again.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007380 *
7381 * <p>Only fullscreen opaque activities may make this call. I.e. this call is a nop
7382 * for dialog and translucent activities.
7383 *
Craig Mautner64ccb702014-10-01 09:38:40 -07007384 * <p>Under all circumstances, the activity must stop playing and release resources prior to or
7385 * within a call to {@link #onVisibleBehindCanceled()} or if this call returns false.
7386 *
7387 * <p>False will be returned any time this method is called between the return of onPause and
Craig Mautneree2e45a2014-06-27 12:10:03 -07007388 * the next call to onResume.
7389 *
Bryce Leed59629e2017-04-18 14:35:29 -07007390 * @deprecated This method's functionality is no longer supported as of
7391 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7392 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007393 * @param visible true to notify the system that the activity wishes to be visible behind other
7394 * translucent activities, false to indicate otherwise. Resources must be
7395 * released when passing false to this method.
Bryce Leed59629e2017-04-18 14:35:29 -07007396 *
Craig Mautner64ccb702014-10-01 09:38:40 -07007397 * @return the resulting visibiity state. If true the activity will remain visible beyond
7398 * {@link #onPause()} if the next activity is translucent or not fullscreen. If false
7399 * then the activity may not count on being visible behind other translucent activities,
7400 * and must stop any media playback and release resources.
7401 * Returning false may occur in lieu of a call to {@link #onVisibleBehindCanceled()} so
7402 * the return value must be checked.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007403 *
Jose Limafcf70832014-08-27 23:09:05 -07007404 * @see #onVisibleBehindCanceled()
Craig Mautneree2e45a2014-06-27 12:10:03 -07007405 */
Bryce Leed59629e2017-04-18 14:35:29 -07007406 @Deprecated
Jose Lima4b6c6692014-08-12 17:41:12 -07007407 public boolean requestVisibleBehind(boolean visible) {
Robert Carr8661c5e2017-06-27 13:46:14 -07007408 return false;
Craig Mautneree2e45a2014-06-27 12:10:03 -07007409 }
7410
7411 /**
Jose Lima4b6c6692014-08-12 17:41:12 -07007412 * Called when a translucent activity over this activity is becoming opaque or another
7413 * activity is being launched. Activities that override this method must call
Jose Limafcf70832014-08-27 23:09:05 -07007414 * <code>super.onVisibleBehindCanceled()</code> or a SuperNotCalledException will be thrown.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007415 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007416 * <p>When this method is called the activity has 500 msec to release any resources it may be
7417 * using while visible in the background.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007418 * If the activity has not returned from this method in 500 msec the system will destroy
Jose Lima4b6c6692014-08-12 17:41:12 -07007419 * the activity and kill the process in order to recover the resources for another
Craig Mautneree2e45a2014-06-27 12:10:03 -07007420 * process. Otherwise {@link #onStop()} will be called following return.
7421 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007422 * @see #requestVisibleBehind(boolean)
Bryce Leed59629e2017-04-18 14:35:29 -07007423 *
7424 * @deprecated This method's functionality is no longer supported as of
7425 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007426 */
Bryce Leed59629e2017-04-18 14:35:29 -07007427 @Deprecated
Tor Norbyec615c6f2015-03-02 10:11:44 -08007428 @CallSuper
Jose Limafcf70832014-08-27 23:09:05 -07007429 public void onVisibleBehindCanceled() {
Craig Mautneree2e45a2014-06-27 12:10:03 -07007430 mCalled = true;
7431 }
7432
7433 /**
Jose Lima4b6c6692014-08-12 17:41:12 -07007434 * Translucent activities may call this to determine if there is an activity below them that
7435 * is currently set to be visible in the background.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007436 *
Bryce Leed59629e2017-04-18 14:35:29 -07007437 * @deprecated This method's functionality is no longer supported as of
7438 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7439 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007440 * @return true if an activity below is set to visible according to the most recent call to
7441 * {@link #requestVisibleBehind(boolean)}, false otherwise.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007442 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007443 * @see #requestVisibleBehind(boolean)
Jose Limafcf70832014-08-27 23:09:05 -07007444 * @see #onVisibleBehindCanceled()
Jose Lima4b6c6692014-08-12 17:41:12 -07007445 * @see #onBackgroundVisibleBehindChanged(boolean)
Craig Mautneree2e45a2014-06-27 12:10:03 -07007446 * @hide
7447 */
Bryce Leed59629e2017-04-18 14:35:29 -07007448 @Deprecated
Jose Lima4b6c6692014-08-12 17:41:12 -07007449 @SystemApi
7450 public boolean isBackgroundVisibleBehind() {
Craig Mautneree2e45a2014-06-27 12:10:03 -07007451 return false;
7452 }
7453
7454 /**
Jose Lima4b6c6692014-08-12 17:41:12 -07007455 * The topmost foreground activity will receive this call when the background visibility state
7456 * of the activity below it changes.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007457 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007458 * This call may be a consequence of {@link #requestVisibleBehind(boolean)} or might be
Craig Mautneree2e45a2014-06-27 12:10:03 -07007459 * due to a background activity finishing itself.
7460 *
Bryce Leed59629e2017-04-18 14:35:29 -07007461 * @deprecated This method's functionality is no longer supported as of
7462 * {@link android.os.Build.VERSION_CODES#O} and will be removed in a future release.
7463 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007464 * @param visible true if a background activity is visible, false otherwise.
Craig Mautneree2e45a2014-06-27 12:10:03 -07007465 *
Jose Lima4b6c6692014-08-12 17:41:12 -07007466 * @see #requestVisibleBehind(boolean)
Jose Limafcf70832014-08-27 23:09:05 -07007467 * @see #onVisibleBehindCanceled()
Jose Lima4b6c6692014-08-12 17:41:12 -07007468 * @hide
Craig Mautneree2e45a2014-06-27 12:10:03 -07007469 */
Bryce Leed59629e2017-04-18 14:35:29 -07007470 @Deprecated
Jose Lima4b6c6692014-08-12 17:41:12 -07007471 @SystemApi
7472 public void onBackgroundVisibleBehindChanged(boolean visible) {
Craig Mautneree2e45a2014-06-27 12:10:03 -07007473 }
7474
7475 /**
Craig Mautner8746a472014-07-24 15:12:54 -07007476 * Activities cannot draw during the period that their windows are animating in. In order
7477 * to know when it is safe to begin drawing they can override this method which will be
7478 * called when the entering animation has completed.
7479 */
7480 public void onEnterAnimationComplete() {
7481 }
7482
7483 /**
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08007484 * @hide
7485 */
7486 public void dispatchEnterAnimationComplete() {
chaviwfeb2e1e2018-12-19 17:24:11 -08007487 mEnterAnimationComplete = true;
7488 mInstrumentation.onEnterAnimationComplete();
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08007489 onEnterAnimationComplete();
7490 if (getWindow() != null && getWindow().getDecorView() != null) {
Felipe Leme01297692019-01-29 18:16:23 -08007491 View decorView = getWindow().getDecorView();
7492 decorView.getViewTreeObserver().dispatchOnEnterAnimationComplete();
Filip Gruszczynski6eafa902014-11-14 14:24:37 -08007493 }
7494 }
7495
7496 /**
Daniel Sandler69a48172010-06-23 16:29:36 -04007497 * Adjust the current immersive mode setting.
Christopher Tate73c2aee2012-03-15 16:27:14 -07007498 *
Daniel Sandler69a48172010-06-23 16:29:36 -04007499 * Note that changing this value will have no effect on the activity's
7500 * {@link android.content.pm.ActivityInfo} structure; that is, if
7501 * <code>android:immersive</code> is set to <code>true</code>
7502 * in the application's manifest entry for this activity, the {@link
7503 * android.content.pm.ActivityInfo#flags ActivityInfo.flags} member will
7504 * always have its {@link android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7505 * FLAG_IMMERSIVE} bit set.
7506 *
Christopher Tate73c2aee2012-03-15 16:27:14 -07007507 * @see #isImmersive()
Daniel Sandler69a48172010-06-23 16:29:36 -04007508 * @see android.content.pm.ActivityInfo#FLAG_IMMERSIVE
7509 */
7510 public void setImmersive(boolean i) {
7511 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007512 ActivityTaskManager.getService().setImmersive(mToken, i);
Daniel Sandler69a48172010-06-23 16:29:36 -04007513 } catch (RemoteException e) {
7514 // pass
7515 }
7516 }
7517
Adam Powell6e346362010-07-23 10:18:23 -07007518 /**
Ruben Brunk927d3452016-05-02 19:30:51 -07007519 * Enable or disable virtual reality (VR) mode for this Activity.
Ruben Brunkdd18a0b2015-12-04 16:16:31 -08007520 *
Ruben Brunk927d3452016-05-02 19:30:51 -07007521 * <p>VR mode is a hint to Android system to switch to a mode optimized for VR applications
7522 * while this Activity has user focus.</p>
7523 *
7524 * <p>It is recommended that applications additionally declare
7525 * {@link android.R.attr#enableVrMode} in their manifest to allow for smooth activity
7526 * transitions when switching between VR activities.</p>
7527 *
7528 * <p>If the requested {@link android.service.vr.VrListenerService} component is not available,
7529 * VR mode will not be started. Developers can handle this case as follows:</p>
7530 *
7531 * <pre>
7532 * String servicePackage = "com.whatever.app";
7533 * String serviceClass = "com.whatever.app.MyVrListenerService";
7534 *
7535 * // Name of the component of the VrListenerService to start.
7536 * ComponentName serviceComponent = new ComponentName(servicePackage, serviceClass);
7537 *
7538 * try {
7539 * setVrModeEnabled(true, myComponentName);
7540 * } catch (PackageManager.NameNotFoundException e) {
7541 * List&lt;ApplicationInfo> installed = getPackageManager().getInstalledApplications(0);
7542 * boolean isInstalled = false;
7543 * for (ApplicationInfo app : installed) {
7544 * if (app.packageName.equals(servicePackage)) {
7545 * isInstalled = true;
7546 * break;
7547 * }
7548 * }
7549 * if (isInstalled) {
7550 * // Package is installed, but not enabled in Settings. Let user enable it.
7551 * startActivity(new Intent(Settings.ACTION_VR_LISTENER_SETTINGS));
7552 * } else {
7553 * // Package is not installed. Send an intent to download this.
7554 * sentIntentToLaunchAppStore(servicePackage);
7555 * }
7556 * }
7557 * </pre>
Ruben Brunkdd18a0b2015-12-04 16:16:31 -08007558 *
7559 * @param enabled {@code true} to enable this mode.
Ruben Brunke24b9a62016-02-16 21:38:24 -08007560 * @param requestedComponent the name of the component to use as a
7561 * {@link android.service.vr.VrListenerService} while VR mode is enabled.
7562 *
Ruben Brunk927d3452016-05-02 19:30:51 -07007563 * @throws android.content.pm.PackageManager.NameNotFoundException if the given component
7564 * to run as a {@link android.service.vr.VrListenerService} is not installed, or has
7565 * not been enabled in user settings.
7566 *
Ruben Brunk927d3452016-05-02 19:30:51 -07007567 * @see android.content.pm.PackageManager#FEATURE_VR_MODE_HIGH_PERFORMANCE
7568 * @see android.service.vr.VrListenerService
7569 * @see android.provider.Settings#ACTION_VR_LISTENER_SETTINGS
7570 * @see android.R.attr#enableVrMode
Ruben Brunkdd18a0b2015-12-04 16:16:31 -08007571 */
Ruben Brunke24b9a62016-02-16 21:38:24 -08007572 public void setVrModeEnabled(boolean enabled, @NonNull ComponentName requestedComponent)
7573 throws PackageManager.NameNotFoundException {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -08007574 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007575 if (ActivityTaskManager.getService().setVrMode(mToken, enabled, requestedComponent)
Ruben Brunke24b9a62016-02-16 21:38:24 -08007576 != 0) {
7577 throw new PackageManager.NameNotFoundException(
7578 requestedComponent.flattenToString());
7579 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -08007580 } catch (RemoteException e) {
7581 // pass
7582 }
7583 }
7584
7585 /**
Clara Bayarri4423d912015-03-02 19:42:48 +00007586 * Start an action mode of the default type {@link ActionMode#TYPE_PRIMARY}.
Adam Powell6e346362010-07-23 10:18:23 -07007587 *
Clara Bayarri4423d912015-03-02 19:42:48 +00007588 * @param callback Callback that will manage lifecycle events for this action mode
7589 * @return The ActionMode that was started, or null if it was canceled
Adam Powell6e346362010-07-23 10:18:23 -07007590 *
7591 * @see ActionMode
7592 */
Tor Norbyed9273d62013-05-30 15:59:53 -07007593 @Nullable
Adam Powell5d279772010-07-27 16:34:07 -07007594 public ActionMode startActionMode(ActionMode.Callback callback) {
Adam Powell6e346362010-07-23 10:18:23 -07007595 return mWindow.getDecorView().startActionMode(callback);
7596 }
7597
Adam Powelldebf3be2010-11-15 18:58:48 -08007598 /**
Clara Bayarri4423d912015-03-02 19:42:48 +00007599 * Start an action mode of the given type.
7600 *
7601 * @param callback Callback that will manage lifecycle events for this action mode
7602 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
7603 * @return The ActionMode that was started, or null if it was canceled
7604 *
7605 * @see ActionMode
7606 */
7607 @Nullable
7608 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
7609 return mWindow.getDecorView().startActionMode(callback, type);
7610 }
7611
7612 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08007613 * Give the Activity a chance to control the UI for an action mode requested
7614 * by the system.
7615 *
7616 * <p>Note: If you are looking for a notification callback that an action mode
7617 * has been started for this activity, see {@link #onActionModeStarted(ActionMode)}.</p>
7618 *
7619 * @param callback The callback that should control the new action mode
7620 * @return The new action mode, or <code>null</code> if the activity does not want to
7621 * provide special handling for this action mode. (It will be handled by the system.)
7622 */
Tor Norbyed9273d62013-05-30 15:59:53 -07007623 @Nullable
Craig Mautner5eda9b32013-07-02 11:58:16 -07007624 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08007625 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
Clara Bayarri4423d912015-03-02 19:42:48 +00007626 // Only Primary ActionModes are represented in the ActionBar.
7627 if (mActionModeTypeStarting == ActionMode.TYPE_PRIMARY) {
7628 initWindowDecorActionBar();
7629 if (mActionBar != null) {
7630 return mActionBar.startActionMode(callback);
7631 }
Adam Powell6e346362010-07-23 10:18:23 -07007632 }
7633 return null;
7634 }
7635
Adam Powelldebf3be2010-11-15 18:58:48 -08007636 /**
Clara Bayarri4423d912015-03-02 19:42:48 +00007637 * {@inheritDoc}
7638 */
7639 @Nullable
7640 @Override
7641 public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
7642 try {
7643 mActionModeTypeStarting = type;
7644 return onWindowStartingActionMode(callback);
7645 } finally {
7646 mActionModeTypeStarting = ActionMode.TYPE_PRIMARY;
7647 }
7648 }
7649
7650 /**
Adam Powelldebf3be2010-11-15 18:58:48 -08007651 * Notifies the Activity that an action mode has been started.
7652 * Activity subclasses overriding this method should call the superclass implementation.
7653 *
7654 * @param mode The new action mode.
7655 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08007656 @CallSuper
Craig Mautner5eda9b32013-07-02 11:58:16 -07007657 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08007658 public void onActionModeStarted(ActionMode mode) {
7659 }
7660
7661 /**
7662 * Notifies the activity that an action mode has finished.
7663 * Activity subclasses overriding this method should call the superclass implementation.
7664 *
7665 * @param mode The action mode that just finished.
7666 */
Tor Norbyec615c6f2015-03-02 10:11:44 -08007667 @CallSuper
Craig Mautner5eda9b32013-07-02 11:58:16 -07007668 @Override
Adam Powelldebf3be2010-11-15 18:58:48 -08007669 public void onActionModeFinished(ActionMode mode) {
7670 }
7671
Adam Powelldd8fab22012-03-22 17:47:27 -07007672 /**
7673 * Returns true if the app should recreate the task when navigating 'up' from this activity
7674 * by using targetIntent.
7675 *
7676 * <p>If this method returns false the app can trivially call
7677 * {@link #navigateUpTo(Intent)} using the same parameters to correctly perform
7678 * up navigation. If this method returns false, the app should synthesize a new task stack
7679 * by using {@link TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
7680 *
7681 * @param targetIntent An intent representing the target destination for up navigation
7682 * @return true if navigating up should recreate a new task stack, false if the same task
7683 * should be used for the destination
7684 */
7685 public boolean shouldUpRecreateTask(Intent targetIntent) {
7686 try {
7687 PackageManager pm = getPackageManager();
7688 ComponentName cn = targetIntent.getComponent();
7689 if (cn == null) {
7690 cn = targetIntent.resolveActivity(pm);
7691 }
7692 ActivityInfo info = pm.getActivityInfo(cn, 0);
7693 if (info.taskAffinity == null) {
7694 return false;
7695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007696 return ActivityTaskManager.getService().shouldUpRecreateTask(mToken, info.taskAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -07007697 } catch (RemoteException e) {
7698 return false;
7699 } catch (NameNotFoundException e) {
7700 return false;
7701 }
7702 }
7703
7704 /**
7705 * Navigate from this activity to the activity specified by upIntent, finishing this activity
7706 * in the process. If the activity indicated by upIntent already exists in the task's history,
7707 * this activity and all others before the indicated activity in the history stack will be
Adam Powell35c064b2012-05-02 11:37:15 -07007708 * finished.
7709 *
7710 * <p>If the indicated activity does not appear in the history stack, this will finish
7711 * each activity in this task until the root activity of the task is reached, resulting in
7712 * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy
7713 * when an activity may be reached by a path not passing through a canonical parent
7714 * activity.</p>
Adam Powelldd8fab22012-03-22 17:47:27 -07007715 *
7716 * <p>This method should be used when performing up navigation from within the same task
7717 * as the destination. If up navigation should cross tasks in some cases, see
7718 * {@link #shouldUpRecreateTask(Intent)}.</p>
7719 *
7720 * @param upIntent An intent representing the target destination for up navigation
7721 *
7722 * @return true if up navigation successfully reached the activity indicated by upIntent and
7723 * upIntent was delivered to it. false if an instance of the indicated activity could
7724 * not be found and this activity was simply finished normally.
7725 */
7726 public boolean navigateUpTo(Intent upIntent) {
7727 if (mParent == null) {
7728 ComponentName destInfo = upIntent.getComponent();
7729 if (destInfo == null) {
7730 destInfo = upIntent.resolveActivity(getPackageManager());
7731 if (destInfo == null) {
7732 return false;
7733 }
7734 upIntent = new Intent(upIntent);
7735 upIntent.setComponent(destInfo);
7736 }
7737 int resultCode;
7738 Intent resultData;
7739 synchronized (this) {
7740 resultCode = mResultCode;
7741 resultData = mResultData;
7742 }
7743 if (resultData != null) {
Jeff Sharkey344744b2016-01-28 19:03:30 -07007744 resultData.prepareToLeaveProcess(this);
Adam Powelldd8fab22012-03-22 17:47:27 -07007745 }
7746 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07007747 upIntent.prepareToLeaveProcess(this);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07007748 return ActivityTaskManager.getService().navigateUpTo(mToken, upIntent,
Adam Powelldd8fab22012-03-22 17:47:27 -07007749 resultCode, resultData);
7750 } catch (RemoteException e) {
7751 return false;
7752 }
7753 } else {
7754 return mParent.navigateUpToFromChild(this, upIntent);
7755 }
7756 }
7757
7758 /**
7759 * This is called when a child activity of this one calls its
7760 * {@link #navigateUpTo} method. The default implementation simply calls
7761 * navigateUpTo(upIntent) on this activity (the parent).
7762 *
7763 * @param child The activity making the call.
7764 * @param upIntent An intent representing the target destination for up navigation
7765 *
7766 * @return true if up navigation successfully reached the activity indicated by upIntent and
7767 * upIntent was delivered to it. false if an instance of the indicated activity could
7768 * not be found and this activity was simply finished normally.
Charles Chenc380f022019-08-13 18:39:17 +08007769 * @deprecated Use {@link #navigateUpTo(Intent)} instead.
Adam Powelldd8fab22012-03-22 17:47:27 -07007770 */
Charles Chenc380f022019-08-13 18:39:17 +08007771 @Deprecated
Adam Powelldd8fab22012-03-22 17:47:27 -07007772 public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
7773 return navigateUpTo(upIntent);
7774 }
7775
7776 /**
7777 * Obtain an {@link Intent} that will launch an explicit target activity specified by
7778 * this activity's logical parent. The logical parent is named in the application's manifest
7779 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
Adam Powell04d58112012-04-09 10:22:12 -07007780 * Activity subclasses may override this method to modify the Intent returned by
7781 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
7782 * the parent intent entirely.
Adam Powelldd8fab22012-03-22 17:47:27 -07007783 *
Adam Powell04d58112012-04-09 10:22:12 -07007784 * @return a new Intent targeting the defined parent of this activity or null if
7785 * there is no valid parent.
Adam Powelldd8fab22012-03-22 17:47:27 -07007786 */
Tor Norbyed9273d62013-05-30 15:59:53 -07007787 @Nullable
Adam Powelldd8fab22012-03-22 17:47:27 -07007788 public Intent getParentActivityIntent() {
Adam Powell04d58112012-04-09 10:22:12 -07007789 final String parentName = mActivityInfo.parentActivityName;
7790 if (TextUtils.isEmpty(parentName)) {
7791 return null;
7792 }
Adam Powell5a4010c2012-09-16 15:14:05 -07007793
7794 // If the parent itself has no parent, generate a main activity intent.
7795 final ComponentName target = new ComponentName(this, parentName);
7796 try {
7797 final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
7798 final String parentActivity = parentInfo.parentActivityName;
7799 final Intent parentIntent = parentActivity == null
7800 ? Intent.makeMainActivity(target)
7801 : new Intent().setComponent(target);
7802 return parentIntent;
7803 } catch (NameNotFoundException e) {
7804 Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
7805 "' in manifest");
7806 return null;
7807 }
Adam Powelldd8fab22012-03-22 17:47:27 -07007808 }
7809
George Mount31a21722014-03-24 17:44:36 -07007810 /**
George Mount62ab9b72014-05-02 13:51:17 -07007811 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
George Mount65580562014-08-29 08:15:48 -07007812 * android.view.View, String)} was used to start an Activity, <var>callback</var>
George Mount800d72b2014-05-19 07:09:00 -07007813 * will be called to handle shared elements on the <i>launched</i> Activity. This requires
George Mount9826f632014-09-11 08:50:09 -07007814 * {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
George Mount31a21722014-03-24 17:44:36 -07007815 *
George Mount65580562014-08-29 08:15:48 -07007816 * @param callback Used to manipulate shared element transitions on the launched Activity.
George Mount31a21722014-03-24 17:44:36 -07007817 */
George Mount65580562014-08-29 08:15:48 -07007818 public void setEnterSharedElementCallback(SharedElementCallback callback) {
7819 if (callback == null) {
7820 callback = SharedElementCallback.NULL_CALLBACK;
George Mount31a21722014-03-24 17:44:36 -07007821 }
George Mount65580562014-08-29 08:15:48 -07007822 mEnterTransitionListener = callback;
George Mount800d72b2014-05-19 07:09:00 -07007823 }
7824
7825 /**
7826 * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
George Mount65580562014-08-29 08:15:48 -07007827 * android.view.View, String)} was used to start an Activity, <var>callback</var>
George Mount800d72b2014-05-19 07:09:00 -07007828 * will be called to handle shared elements on the <i>launching</i> Activity. Most
7829 * calls will only come when returning from the started Activity.
George Mount9826f632014-09-11 08:50:09 -07007830 * This requires {@link Window#FEATURE_ACTIVITY_TRANSITIONS}.
George Mount800d72b2014-05-19 07:09:00 -07007831 *
George Mount65580562014-08-29 08:15:48 -07007832 * @param callback Used to manipulate shared element transitions on the launching Activity.
George Mount800d72b2014-05-19 07:09:00 -07007833 */
George Mount65580562014-08-29 08:15:48 -07007834 public void setExitSharedElementCallback(SharedElementCallback callback) {
7835 if (callback == null) {
7836 callback = SharedElementCallback.NULL_CALLBACK;
George Mount800d72b2014-05-19 07:09:00 -07007837 }
George Mount65580562014-08-29 08:15:48 -07007838 mExitTransitionListener = callback;
George Mount31a21722014-03-24 17:44:36 -07007839 }
7840
George Mount8c2614c2014-06-10 11:12:01 -07007841 /**
7842 * Postpone the entering activity transition when Activity was started with
7843 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7844 * android.util.Pair[])}.
7845 * <p>This method gives the Activity the ability to delay starting the entering and
7846 * shared element transitions until all data is loaded. Until then, the Activity won't
7847 * draw into its window, leaving the window transparent. This may also cause the
7848 * returning animation to be delayed until data is ready. This method should be
7849 * called in {@link #onCreate(android.os.Bundle)} or in
7850 * {@link #onActivityReenter(int, android.content.Intent)}.
7851 * {@link #startPostponedEnterTransition()} must be called to allow the Activity to
7852 * start the transitions. If the Activity did not use
7853 * {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
7854 * android.util.Pair[])}, then this method does nothing.</p>
7855 */
7856 public void postponeEnterTransition() {
7857 mActivityTransitionState.postponeEnterTransition();
7858 }
7859
7860 /**
7861 * Begin postponed transitions after {@link #postponeEnterTransition()} was called.
7862 * If postponeEnterTransition() was called, you must call startPostponedEnterTransition()
7863 * to have your Activity start drawing.
7864 */
7865 public void startPostponedEnterTransition() {
7866 mActivityTransitionState.startPostponedEnterTransition();
7867 }
7868
Vladislav Kaznacheevb23a7572015-12-18 12:23:43 -08007869 /**
Vladislav Kaznacheev377c3282016-04-20 14:22:23 -07007870 * Create {@link DragAndDropPermissions} object bound to this activity and controlling the
7871 * access permissions for content URIs associated with the {@link DragEvent}.
Vladislav Kaznacheevb23a7572015-12-18 12:23:43 -08007872 * @param event Drag event
Vladislav Kaznacheev377c3282016-04-20 14:22:23 -07007873 * @return The {@link DragAndDropPermissions} object used to control access to the content URIs.
7874 * Null if no content URIs are associated with the event or if permissions could not be granted.
Vladislav Kaznacheevb23a7572015-12-18 12:23:43 -08007875 */
Vladislav Kaznacheev377c3282016-04-20 14:22:23 -07007876 public DragAndDropPermissions requestDragAndDropPermissions(DragEvent event) {
7877 DragAndDropPermissions dragAndDropPermissions = DragAndDropPermissions.obtain(event);
7878 if (dragAndDropPermissions != null && dragAndDropPermissions.take(getActivityToken())) {
7879 return dragAndDropPermissions;
Vladislav Kaznacheevb23a7572015-12-18 12:23:43 -08007880 }
7881 return null;
7882 }
7883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 // ------------------ Internal API ------------------
RoboErik55011652014-07-09 15:05:53 -07007885
Mathew Inwood8c854f82018-09-14 12:35:36 +01007886 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 final void setParent(Activity parent) {
7888 mParent = parent;
7889 }
7890
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007891 @UnsupportedAppUsage
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007892 final void attach(Context context, ActivityThread aThread,
7893 Instrumentation instr, IBinder token, int ident,
7894 Application application, Intent intent, ActivityInfo info,
7895 CharSequence title, Activity parent, String id,
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07007896 NonConfigurationInstances lastNonConfigurationInstances,
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07007897 Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Sunny Goyald40c3452019-03-20 12:46:55 -07007898 Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 attachBaseContext(context);
7900
Todd Kennedya5fc6f02015-04-14 18:22:54 -07007901 mFragments.attachHost(null /*parent*/);
RoboErik55011652014-07-09 15:05:53 -07007902
Andrii Kulian51c1b672017-04-07 18:39:32 -07007903 mWindow = new PhoneWindow(this, window, activityConfigCallback);
Mathew Inwoodd6973862019-12-05 10:15:19 +00007904 mWindow.setWindowControllerCallback(mWindowControllerCallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 mWindow.setCallback(this);
Adam Powell117b6952014-05-05 18:14:56 -07007906 mWindow.setOnWindowDismissedCallback(this);
Dianne Hackborn420829e2011-01-28 11:30:35 -08007907 mWindow.getLayoutInflater().setPrivateFactory(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
7909 mWindow.setSoftInputMode(info.softInputMode);
7910 }
Adam Powell269248d2011-08-02 10:26:54 -07007911 if (info.uiOptions != 0) {
7912 mWindow.setUiOptions(info.uiOptions);
7913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 mUiThread = Thread.currentThread();
George Mount0a778ed2013-12-13 13:35:36 -08007915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 mMainThread = aThread;
7917 mInstrumentation = instr;
7918 mToken = token;
Sunny Goyald40c3452019-03-20 12:46:55 -07007919 mAssistToken = assistToken;
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007920 mIdent = ident;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 mApplication = application;
7922 mIntent = intent;
Dianne Hackborn85d558c2014-11-04 10:31:54 -08007923 mReferrer = referrer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 mComponent = intent.getComponent();
7925 mActivityInfo = info;
7926 mTitle = title;
7927 mParent = parent;
7928 mEmbeddedID = id;
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07007929 mLastNonConfigurationInstances = lastNonConfigurationInstances;
Dianne Hackborn20d94742014-05-29 18:35:45 -07007930 if (voiceInteractor != null) {
7931 if (lastNonConfigurationInstances != null) {
7932 mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
7933 } else {
7934 mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
7935 Looper.myLooper());
7936 }
7937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938
Jeff Brown98365d72012-08-19 20:30:52 -07007939 mWindow.setWindowManager(
7940 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
7941 mToken, mComponent.flattenToString(),
Romain Guy529b60a2010-08-03 18:05:47 -07007942 (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 if (mParent != null) {
7944 mWindow.setContainer(mParent.getWindow());
7945 }
7946 mWindowManager = mWindow.getWindowManager();
7947 mCurrentConfig = config;
Romain Guy48327452017-01-23 17:03:35 -08007948
7949 mWindow.setColorMode(info.colorMode);
Galia Peychevabdd66e32020-02-27 19:16:28 +01007950 mWindow.setPreferMinimalPostProcessing(
7951 (info.flags & ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING) != 0);
Svetoslav Ganov24c90452017-12-27 15:17:14 -08007952
Felipe Lemea4f39cd2019-02-19 15:08:59 -08007953 setAutofillOptions(application.getAutofillOptions());
Felipe Leme326f15a2019-02-19 09:42:24 -08007954 setContentCaptureOptions(application.getContentCaptureOptions());
Svetoslav Ganov24c90452017-12-27 15:17:14 -08007955 }
7956
7957 private void enableAutofillCompatibilityIfNeeded() {
7958 if (isAutofillCompatibilityEnabled()) {
7959 final AutofillManager afm = getSystemService(AutofillManager.class);
7960 if (afm != null) {
7961 afm.enableCompatibilityMode();
7962 }
7963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 }
7965
Dianne Hackborn5320eb82012-05-18 12:05:04 -07007966 /** @hide */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007967 @UnsupportedAppUsage
Dianne Hackborn5320eb82012-05-18 12:05:04 -07007968 public final IBinder getActivityToken() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 return mParent != null ? mParent.getActivityToken() : mToken;
7970 }
7971
Andrii Kuliandfbf9712018-03-08 15:42:24 -08007972 /** @hide */
Sunny Goyald40c3452019-03-20 12:46:55 -07007973 public final IBinder getAssistToken() {
7974 return mParent != null ? mParent.getAssistToken() : mAssistToken;
7975 }
7976
7977 /** @hide */
Andrii Kuliandfbf9712018-03-08 15:42:24 -08007978 @VisibleForTesting
7979 public final ActivityThread getActivityThread() {
7980 return mMainThread;
7981 }
7982
Winson Chung298f95b2017-08-10 15:57:18 -07007983 final void performCreate(Bundle icicle) {
7984 performCreate(icicle, null);
7985 }
7986
Mathew Inwood61e8ae62018-08-14 14:17:44 +01007987 @UnsupportedAppUsage
Winson Chung298f95b2017-08-10 15:57:18 -07007988 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
Ian Lake8a88cd62018-09-28 13:25:20 -07007989 dispatchActivityPreCreated(icicle);
Winson Chung298f95b2017-08-10 15:57:18 -07007990 mCanEnterPictureInPicture = true;
Hongwei Wangf7e5a232020-05-06 15:49:44 -07007991 // initialize mIsInMultiWindowMode and mIsInPictureInPictureMode before onCreate
7992 final int windowingMode = getResources().getConfiguration().windowConfiguration
7993 .getWindowingMode();
7994 mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
7995 mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
Winson Chung298f95b2017-08-10 15:57:18 -07007996 restoreHasCurrentPermissionRequest(icicle);
7997 if (persistentState != null) {
7998 onCreate(icicle, persistentState);
7999 } else {
8000 onCreate(icicle);
8001 }
Jeff Changd136e772019-11-05 20:33:52 +08008002 EventLogTags.writeWmOnCreateCalled(mIdent, getComponentName().getClassName(),
8003 "performCreate");
Winson Chung298f95b2017-08-10 15:57:18 -07008004 mActivityTransitionState.readState(icicle);
8005
Dianne Hackborn30c9bd82010-12-01 16:07:40 -08008006 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
8007 com.android.internal.R.styleable.Window_windowNoDisplay, false);
Dianne Hackbornc8017682010-07-06 13:34:38 -07008008 mFragments.dispatchActivityCreated();
Eino-Ville Talvala563df3b2016-06-06 22:04:54 +00008009 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
Ian Lake8a88cd62018-09-28 13:25:20 -07008010 dispatchActivityPostCreated(icicle);
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008011 }
George Mount0a778ed2013-12-13 13:35:36 -08008012
Ian Lake0b71b8e2018-09-13 13:56:26 -07008013 final void performNewIntent(@NonNull Intent intent) {
Winson Chung298f95b2017-08-10 15:57:18 -07008014 mCanEnterPictureInPicture = true;
8015 onNewIntent(intent);
Craig Mautnera0026042014-04-23 11:45:37 -07008016 }
8017
Andrii Kuliand25680c2018-02-21 15:16:58 -08008018 final void performStart(String reason) {
Ian Lake8a88cd62018-09-28 13:25:20 -07008019 dispatchActivityPreStarted();
George Mount62ab9b72014-05-02 13:51:17 -07008020 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07008021 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 mCalled = false;
Dianne Hackborn445646c2010-06-25 15:52:59 -07008023 mFragments.execPendingActions();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 mInstrumentation.callActivityOnStart(this);
Jeff Changd136e772019-11-05 20:33:52 +08008025 EventLogTags.writeWmOnStartCalled(mIdent, getComponentName().getClassName(), reason);
Andrii Kuliand25680c2018-02-21 15:16:58 -08008026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 if (!mCalled) {
8028 throw new SuperNotCalledException(
8029 "Activity " + mComponent.toShortString() +
8030 " did not call through to super.onStart()");
8031 }
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008032 mFragments.dispatchStart();
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008033 mFragments.reportLoaderStart();
Dimitry Ivanov4449ef52016-02-25 17:41:13 -08008034
Elliott Hughese14fa972019-10-02 11:35:53 -07008035 // Warn app developers if the dynamic linker logged anything during startup.
Dimitry Ivanov4449ef52016-02-25 17:41:13 -08008036 boolean isAppDebuggable =
8037 (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
Elliott Hughese14fa972019-10-02 11:35:53 -07008038 if (isAppDebuggable) {
Dimitry Ivanov4449ef52016-02-25 17:41:13 -08008039 String dlwarning = getDlWarning();
8040 if (dlwarning != null) {
Adam Powelld93f3b12016-03-03 08:43:37 -08008041 String appName = getApplicationInfo().loadLabel(getPackageManager())
8042 .toString();
Dimitry Ivanov4449ef52016-02-25 17:41:13 -08008043 String warning = "Detected problems with app native libraries\n" +
8044 "(please consult log for detail):\n" + dlwarning;
8045 if (isAppDebuggable) {
8046 new AlertDialog.Builder(this).
8047 setTitle(appName).
8048 setMessage(warning).
8049 setPositiveButton(android.R.string.ok, null).
8050 setCancelable(false).
8051 show();
8052 } else {
8053 Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
8054 }
8055 }
8056 }
8057
Tim Van Pattenddc43912018-12-18 17:47:52 -07008058 GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
8059
George Mount62ab9b72014-05-02 13:51:17 -07008060 mActivityTransitionState.enterReady(this);
Ian Lake8a88cd62018-09-28 13:25:20 -07008061 dispatchActivityPostStarted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 }
RoboErik55011652014-07-09 15:05:53 -07008063
Andrii Kulian88e05cb2017-12-05 17:21:10 -08008064 /**
8065 * Restart the activity.
8066 * @param start Indicates whether the activity should also be started after restart.
8067 * The option to not start immediately is needed in case a transaction with
8068 * multiple lifecycle transitions is in progress.
8069 */
Andrii Kuliand25680c2018-02-21 15:16:58 -08008070 final void performRestart(boolean start, String reason) {
Winson Chungf7e03e12017-08-22 11:32:16 -07008071 mCanEnterPictureInPicture = true;
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07008072 mFragments.noteStateNotSaved();
Dianne Hackborna21e3da2010-09-12 19:27:46 -07008073
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07008074 if (mToken != null && mParent == null) {
Chong Zhang7687f252016-02-26 12:03:33 -08008075 // No need to check mStopped, the roots will check if they were actually stopped.
Filip Gruszczynskia59ac9c2015-09-10 18:28:48 -07008076 WindowManagerGlobal.getInstance().setStoppedState(mToken, false /* stopped */);
8077 }
8078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 if (mStopped) {
8080 mStopped = false;
Dianne Hackborn185e3e22011-06-03 15:26:01 -07008081
8082 synchronized (mManagedCursors) {
8083 final int N = mManagedCursors.size();
8084 for (int i=0; i<N; i++) {
8085 ManagedCursor mc = mManagedCursors.get(i);
8086 if (mc.mReleased || mc.mUpdated) {
8087 if (!mc.mCursor.requery()) {
Dianne Hackborna5445d32011-09-01 14:38:24 -07008088 if (getApplicationInfo().targetSdkVersion
8089 >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
8090 throw new IllegalStateException(
8091 "trying to requery an already closed cursor "
8092 + mc.mCursor);
8093 }
Dianne Hackborn185e3e22011-06-03 15:26:01 -07008094 }
8095 mc.mReleased = false;
8096 mc.mUpdated = false;
8097 }
8098 }
8099 }
8100
8101 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 mInstrumentation.callActivityOnRestart(this);
Jeff Changd136e772019-11-05 20:33:52 +08008103 EventLogTags.writeWmOnRestartCalled(mIdent, getComponentName().getClassName(), reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 if (!mCalled) {
8105 throw new SuperNotCalledException(
8106 "Activity " + mComponent.toShortString() +
8107 " did not call through to super.onRestart()");
8108 }
Andrii Kulian88e05cb2017-12-05 17:21:10 -08008109 if (start) {
Andrii Kuliand25680c2018-02-21 15:16:58 -08008110 performStart(reason);
Andrii Kulian88e05cb2017-12-05 17:21:10 -08008111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 }
8113 }
RoboErik55011652014-07-09 15:05:53 -07008114
Andrii Kuliand25680c2018-02-21 15:16:58 -08008115 final void performResume(boolean followedByPause, String reason) {
Ian Lake8a88cd62018-09-28 13:25:20 -07008116 dispatchActivityPreResumed();
Andrii Kuliand25680c2018-02-21 15:16:58 -08008117 performRestart(true /* start */, reason);
RoboErik55011652014-07-09 15:05:53 -07008118
Dianne Hackborn445646c2010-06-25 15:52:59 -07008119 mFragments.execPendingActions();
RoboErik55011652014-07-09 15:05:53 -07008120
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07008121 mLastNonConfigurationInstances = null;
RoboErik55011652014-07-09 15:05:53 -07008122
Dake Gu67decfa2017-12-27 11:48:08 -08008123 if (mAutoFillResetNeeded) {
8124 // When Activity is destroyed in paused state, and relaunch activity, there will be
8125 // extra onResume and onPause event, ignore the first onResume and onPause.
8126 // see ActivityThread.handleRelaunchActivity()
8127 mAutoFillIgnoreFirstResumePause = followedByPause;
8128 if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
8129 Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
8130 }
8131 }
8132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 mCalled = false;
Jeff Hamilton52d32032011-01-08 15:31:26 -06008134 // mResumed is set by the instrumentation
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 mInstrumentation.callActivityOnResume(this);
Jeff Changd136e772019-11-05 20:33:52 +08008136 EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 if (!mCalled) {
8138 throw new SuperNotCalledException(
8139 "Activity " + mComponent.toShortString() +
8140 " did not call through to super.onResume()");
8141 }
8142
Todd Kennedyee8c9c62014-12-10 14:22:59 -08008143 // invisible activities must be finished before onResume() completes
8144 if (!mVisibleFromClient && !mFinished) {
8145 Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
8146 if (getApplicationInfo().targetSdkVersion
8147 > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
8148 throw new IllegalStateException(
8149 "Activity " + mComponent.toShortString() +
8150 " did not call finish() prior to onResume() completing");
8151 }
8152 }
8153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 // Now really resume, and install the current status bar and menu.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 mCalled = false;
RoboErik55011652014-07-09 15:05:53 -07008156
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008157 mFragments.dispatchResume();
Dianne Hackborn445646c2010-06-25 15:52:59 -07008158 mFragments.execPendingActions();
Narayan Kamathff5659f2017-02-02 13:31:33 +00008159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 onPostResume();
8161 if (!mCalled) {
8162 throw new SuperNotCalledException(
8163 "Activity " + mComponent.toShortString() +
8164 " did not call through to super.onPostResume()");
8165 }
Ian Lake8a88cd62018-09-28 13:25:20 -07008166 dispatchActivityPostResumed();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 }
8168
8169 final void performPause() {
Ian Lake8a88cd62018-09-28 13:25:20 -07008170 dispatchActivityPrePaused();
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07008171 mDoReportFullyDrawn = false;
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008172 mFragments.dispatchPause();
Dianne Hackborne794e9f2010-08-24 12:32:10 -07008173 mCalled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 onPause();
Jeff Changd136e772019-11-05 20:33:52 +08008175 EventLogTags.writeWmOnPausedCalled(mIdent, getComponentName().getClassName(),
8176 "performPause");
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008177 mResumed = false;
Dianne Hackborne794e9f2010-08-24 12:32:10 -07008178 if (!mCalled && getApplicationInfo().targetSdkVersion
8179 >= android.os.Build.VERSION_CODES.GINGERBREAD) {
8180 throw new SuperNotCalledException(
8181 "Activity " + mComponent.toShortString() +
8182 " did not call through to super.onPause()");
8183 }
Ian Lake8a88cd62018-09-28 13:25:20 -07008184 dispatchActivityPostPaused();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 }
RoboErik55011652014-07-09 15:05:53 -07008186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 final void performUserLeaving() {
8188 onUserInteraction();
8189 onUserLeaveHint();
8190 }
RoboErik55011652014-07-09 15:05:53 -07008191
Andrii Kuliand25680c2018-02-21 15:16:58 -08008192 final void performStop(boolean preserveWindow, String reason) {
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07008193 mDoReportFullyDrawn = false;
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008194 mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
Narayan Kamathff5659f2017-02-02 13:31:33 +00008195
Winson Chung298f95b2017-08-10 15:57:18 -07008196 // Disallow entering picture-in-picture after the activity has been stopped
8197 mCanEnterPictureInPicture = false;
8198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 if (!mStopped) {
Ian Lake8a88cd62018-09-28 13:25:20 -07008200 dispatchActivityPreStopped();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 if (mWindow != null) {
8202 mWindow.closeAllPanels();
8203 }
8204
Chong Zhang7687f252016-02-26 12:03:33 -08008205 // If we're preserving the window, don't setStoppedState to true, since we
8206 // need the window started immediately again. Stopping the window will
8207 // destroys hardware resources and causes flicker.
8208 if (!preserveWindow && mToken != null && mParent == null) {
Jeff Brown98365d72012-08-19 20:30:52 -07008209 WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
Dianne Hackbornce418e62011-03-01 14:31:38 -08008210 }
RoboErik55011652014-07-09 15:05:53 -07008211
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008212 mFragments.dispatchStop();
RoboErik55011652014-07-09 15:05:53 -07008213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 mCalled = false;
8215 mInstrumentation.callActivityOnStop(this);
Jeff Changd136e772019-11-05 20:33:52 +08008216 EventLogTags.writeWmOnStopCalled(mIdent, getComponentName().getClassName(), reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 if (!mCalled) {
8218 throw new SuperNotCalledException(
8219 "Activity " + mComponent.toShortString() +
8220 " did not call through to super.onStop()");
8221 }
RoboErik55011652014-07-09 15:05:53 -07008222
Makoto Onuki2f6a0182010-02-22 13:26:59 -08008223 synchronized (mManagedCursors) {
8224 final int N = mManagedCursors.size();
8225 for (int i=0; i<N; i++) {
8226 ManagedCursor mc = mManagedCursors.get(i);
8227 if (!mc.mReleased) {
8228 mc.mCursor.deactivate();
8229 mc.mReleased = true;
8230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 }
8232 }
George Mount0a778ed2013-12-13 13:35:36 -08008233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 mStopped = true;
Ian Lake8a88cd62018-09-28 13:25:20 -07008235 dispatchActivityPostStopped();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 }
8237 mResumed = false;
8238 }
8239
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008240 final void performDestroy() {
Ian Lake8a88cd62018-09-28 13:25:20 -07008241 dispatchActivityPreDestroyed();
Dianne Hackborn6d9dcbc2012-10-02 17:51:13 -07008242 mDestroyed = true;
Dianne Hackborn291905e2010-08-17 15:17:15 -07008243 mWindow.destroy();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008244 mFragments.dispatchDestroy();
8245 onDestroy();
Jeff Changd136e772019-11-05 20:33:52 +08008246 EventLogTags.writeWmOnDestroyCalled(mIdent, getComponentName().getClassName(),
8247 "performDestroy");
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008248 mFragments.doLoaderDestroy();
Dianne Hackborn20d94742014-05-29 18:35:45 -07008249 if (mVoiceInteractor != null) {
8250 mVoiceInteractor.detachActivity();
8251 }
Ian Lake8a88cd62018-09-28 13:25:20 -07008252 dispatchActivityPostDestroyed();
Dianne Hackborn2dedce62010-04-15 14:45:25 -07008253 }
George Mount0a778ed2013-12-13 13:35:36 -08008254
Winson Chung5af42fc2017-03-24 17:11:33 -07008255 final void dispatchMultiWindowModeChanged(boolean isInMultiWindowMode,
8256 Configuration newConfig) {
Adam Powell858cf032016-05-09 15:45:37 -07008257 if (DEBUG_LIFECYCLE) Slog.v(TAG,
Winson Chung5af42fc2017-03-24 17:11:33 -07008258 "dispatchMultiWindowModeChanged " + this + ": " + isInMultiWindowMode
8259 + " " + newConfig);
8260 mFragments.dispatchMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Adam Powell858cf032016-05-09 15:45:37 -07008261 if (mWindow != null) {
8262 mWindow.onMultiWindowModeChanged();
8263 }
Hongwei Wangf7e5a232020-05-06 15:49:44 -07008264 mIsInMultiWindowMode = isInMultiWindowMode;
Winson Chung5af42fc2017-03-24 17:11:33 -07008265 onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
Adam Powell858cf032016-05-09 15:45:37 -07008266 }
8267
Winson Chung5af42fc2017-03-24 17:11:33 -07008268 final void dispatchPictureInPictureModeChanged(boolean isInPictureInPictureMode,
8269 Configuration newConfig) {
Adam Powell858cf032016-05-09 15:45:37 -07008270 if (DEBUG_LIFECYCLE) Slog.v(TAG,
Winson Chung5af42fc2017-03-24 17:11:33 -07008271 "dispatchPictureInPictureModeChanged " + this + ": " + isInPictureInPictureMode
8272 + " " + newConfig);
8273 mFragments.dispatchPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
Winson Chung4d8681f2017-05-23 16:22:08 -07008274 if (mWindow != null) {
8275 mWindow.onPictureInPictureModeChanged(isInPictureInPictureMode);
8276 }
Hongwei Wangf7e5a232020-05-06 15:49:44 -07008277 mIsInPictureInPictureMode = isInPictureInPictureMode;
Winson Chung5af42fc2017-03-24 17:11:33 -07008278 onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
Adam Powell858cf032016-05-09 15:45:37 -07008279 }
8280
George Mount0a778ed2013-12-13 13:35:36 -08008281 /**
Jeff Hamilton52d32032011-01-08 15:31:26 -06008282 * @hide
8283 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01008284 @UnsupportedAppUsage
Jeff Hamilton52d32032011-01-08 15:31:26 -06008285 public final boolean isResumed() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008286 return mResumed;
8287 }
8288
Svetoslavffb32b12015-10-15 16:54:00 -07008289 private void storeHasCurrentPermissionRequest(Bundle bundle) {
8290 if (bundle != null && mHasCurrentPermissionsRequest) {
8291 bundle.putBoolean(HAS_CURENT_PERMISSIONS_REQUEST_KEY, true);
8292 }
8293 }
8294
8295 private void restoreHasCurrentPermissionRequest(Bundle bundle) {
8296 if (bundle != null) {
8297 mHasCurrentPermissionsRequest = bundle.getBoolean(
8298 HAS_CURENT_PERMISSIONS_REQUEST_KEY, false);
8299 }
8300 }
8301
Mathew Inwood61e8ae62018-08-14 14:17:44 +01008302 @UnsupportedAppUsage
Andrii Kuliane55b0092018-04-19 15:29:22 -07008303 void dispatchActivityResult(String who, int requestCode, int resultCode, Intent data,
8304 String reason) {
Joe Onorato43a17652011-04-06 19:22:23 -07008305 if (false) Log.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode
8307 + ", resCode=" + resultCode + ", data=" + data);
Dianne Hackbornfb3cffe2010-10-25 17:08:56 -07008308 mFragments.noteStateNotSaved();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 if (who == null) {
Svetoslav970b59c2015-06-09 16:05:21 -07008310 onActivityResult(requestCode, resultCode, data);
8311 } else if (who.startsWith(REQUEST_PERMISSIONS_WHO_PREFIX)) {
8312 who = who.substring(REQUEST_PERMISSIONS_WHO_PREFIX.length());
8313 if (TextUtils.isEmpty(who)) {
Svetoslavc6d1c342015-02-26 14:44:43 -08008314 dispatchRequestPermissionsResult(requestCode, data);
8315 } else {
Clara Bayarrid5bf3ed2015-03-27 17:32:45 +00008316 Fragment frag = mFragments.findFragmentByWho(who);
8317 if (frag != null) {
Svetoslav970b59c2015-06-09 16:05:21 -07008318 dispatchRequestPermissionsResultToFragment(requestCode, data, frag);
Svetoslavc6d1c342015-02-26 14:44:43 -08008319 }
Dianne Hackborn6e8304e2010-05-14 00:42:53 -07008320 }
Svetoslav970b59c2015-06-09 16:05:21 -07008321 } else if (who.startsWith("@android:view:")) {
8322 ArrayList<ViewRootImpl> views = WindowManagerGlobal.getInstance().getRootViews(
8323 getActivityToken());
8324 for (ViewRootImpl viewRoot : views) {
8325 if (viewRoot.getView() != null
8326 && viewRoot.getView().dispatchActivityResult(
8327 who, requestCode, resultCode, data)) {
8328 return;
8329 }
8330 }
Svet Ganov782043c2017-02-11 00:52:02 +00008331 } else if (who.startsWith(AUTO_FILL_AUTH_WHO_PREFIX)) {
Svet Ganov00c771dc2017-02-19 00:06:22 -08008332 Intent resultData = (resultCode == Activity.RESULT_OK) ? data : null;
Dake Gu67decfa2017-12-27 11:48:08 -08008333 getAutofillManager().onAuthenticationResult(requestCode, resultData, getCurrentFocus());
Svetoslav970b59c2015-06-09 16:05:21 -07008334 } else {
8335 Fragment frag = mFragments.findFragmentByWho(who);
8336 if (frag != null) {
8337 frag.onActivityResult(requestCode, resultCode, data);
8338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 }
Jeff Changd136e772019-11-05 20:33:52 +08008340
8341 EventLogTags.writeWmOnActivityResultCalled(mIdent, getComponentName().getClassName(),
8342 reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008343 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07008344
Jason Monka57e5e02014-05-07 10:06:48 -04008345 /**
Charles Heff9b4dff2017-09-22 10:18:37 +01008346 * Request to put this activity in a mode where the user is locked to a restricted set of
8347 * applications.
Jason Monka57e5e02014-05-07 10:06:48 -04008348 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008349 * <p>If {@link DevicePolicyManager#isLockTaskPermitted(String)} returns {@code true}
8350 * for this component, the current task will be launched directly into LockTask mode. Only apps
8351 * whitelisted by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])} can
8352 * be launched while LockTask mode is active. The user will not be able to leave this mode
8353 * until this activity calls {@link #stopLockTask()}. Calling this method while the device is
8354 * already in LockTask mode has no effect.
Jason Monka57e5e02014-05-07 10:06:48 -04008355 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008356 * <p>Otherwise, the current task will be launched into screen pinning mode. In this case, the
8357 * system will prompt the user with a dialog requesting permission to use this mode.
8358 * The user can exit at any time through instructions shown on the request dialog. Calling
8359 * {@link #stopLockTask()} will also terminate this mode.
Jason Monk62515be2014-05-21 16:06:19 -04008360 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008361 * <p><strong>Note:</strong> this method can only be called when the activity is foreground.
8362 * That is, between {@link #onResume()} and {@link #onPause()}.
Craig Mautner15df08a2015-04-01 12:17:18 -07008363 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008364 * @see #stopLockTask()
Craig Mautner15df08a2015-04-01 12:17:18 -07008365 * @see android.R.attr#lockTaskMode
Jason Monka57e5e02014-05-07 10:06:48 -04008366 */
Craig Mautneraea74a52014-03-08 14:23:10 -08008367 public void startLockTask() {
8368 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008369 ActivityTaskManager.getService().startLockTaskModeByToken(mToken);
Craig Mautneraea74a52014-03-08 14:23:10 -08008370 } catch (RemoteException e) {
8371 }
8372 }
8373
Jason Monka57e5e02014-05-07 10:06:48 -04008374 /**
Charles Heff9b4dff2017-09-22 10:18:37 +01008375 * Stop the current task from being locked.
Jason Monka57e5e02014-05-07 10:06:48 -04008376 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008377 * <p>Called to end the LockTask or screen pinning mode started by {@link #startLockTask()}.
8378 * This can only be called by activities that have called {@link #startLockTask()} previously.
Jason Monka57e5e02014-05-07 10:06:48 -04008379 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008380 * <p><strong>Note:</strong> If the device is in LockTask mode that is not initially started
8381 * by this activity, then calling this method will not terminate the LockTask mode, but only
8382 * finish its own task. The device will remain in LockTask mode, until the activity which
8383 * started the LockTask mode calls this method, or until its whitelist authorization is revoked
8384 * by {@link DevicePolicyManager#setLockTaskPackages(ComponentName, String[])}.
Craig Mautner15df08a2015-04-01 12:17:18 -07008385 *
Charles Heff9b4dff2017-09-22 10:18:37 +01008386 * @see #startLockTask()
Craig Mautner15df08a2015-04-01 12:17:18 -07008387 * @see android.R.attr#lockTaskMode
8388 * @see ActivityManager#getLockTaskModeState()
Jason Monka57e5e02014-05-07 10:06:48 -04008389 */
Craig Mautneraea74a52014-03-08 14:23:10 -08008390 public void stopLockTask() {
8391 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008392 ActivityTaskManager.getService().stopLockTaskModeByToken(mToken);
Craig Mautneraea74a52014-03-08 14:23:10 -08008393 } catch (RemoteException e) {
8394 }
8395 }
8396
Craig Mautner5eda9b32013-07-02 11:58:16 -07008397 /**
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07008398 * Shows the user the system defined message for telling the user how to exit
8399 * lock task mode. The task containing this activity must be in lock task mode at the time
8400 * of this call for the message to be displayed.
8401 */
8402 public void showLockTaskEscapeMessage() {
8403 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008404 ActivityTaskManager.getService().showLockTaskEscapeMessage(mToken);
Craig Mautnerc21ae9e2015-04-15 09:45:42 -07008405 } catch (RemoteException e) {
8406 }
8407 }
8408
8409 /**
Andrii Kulian933076d2016-03-29 17:04:42 -07008410 * Check whether the caption on freeform windows is displayed directly on the content.
8411 *
8412 * @return True if caption is displayed on content, false if it pushes the content down.
8413 *
Elliot Waited5ed3bc2017-01-25 15:22:55 -08008414 * @see #setOverlayWithDecorCaptionEnabled(boolean)
Wale Ogunwale724ca142017-04-24 13:40:34 -07008415 * @hide
Andrii Kulian933076d2016-03-29 17:04:42 -07008416 */
8417 public boolean isOverlayWithDecorCaptionEnabled() {
8418 return mWindow.isOverlayWithDecorCaptionEnabled();
8419 }
8420
8421 /**
Filip Gruszczynski63250652015-11-18 14:43:01 -08008422 * Set whether the caption should displayed directly on the content rather than push it down.
8423 *
8424 * This affects only freeform windows since they display the caption and only the main
8425 * window of the activity. The caption is used to drag the window around and also shows
8426 * maximize and close action buttons.
Wale Ogunwale724ca142017-04-24 13:40:34 -07008427 * @hide
Filip Gruszczynski63250652015-11-18 14:43:01 -08008428 */
Andrii Kulian933076d2016-03-29 17:04:42 -07008429 public void setOverlayWithDecorCaptionEnabled(boolean enabled) {
8430 mWindow.setOverlayWithDecorCaptionEnabled(enabled);
Filip Gruszczynski63250652015-11-18 14:43:01 -08008431 }
8432
8433 /**
Craig Mautner5eda9b32013-07-02 11:58:16 -07008434 * Interface for informing a translucent {@link Activity} once all visible activities below it
8435 * have completed drawing. This is necessary only after an {@link Activity} has been made
8436 * opaque using {@link Activity#convertFromTranslucent()} and before it has been drawn
8437 * translucent again following a call to {@link
George Mount800d72b2014-05-19 07:09:00 -07008438 * Activity#convertToTranslucent(android.app.Activity.TranslucentConversionListener,
8439 * ActivityOptions)}
Chet Haaseabd3d772013-09-11 14:33:05 -07008440 *
8441 * @hide
Craig Mautner5eda9b32013-07-02 11:58:16 -07008442 */
Jose Lima14914852014-08-14 09:14:12 -07008443 @SystemApi
Craig Mautner5eda9b32013-07-02 11:58:16 -07008444 public interface TranslucentConversionListener {
8445 /**
8446 * Callback made following {@link Activity#convertToTranslucent} once all visible Activities
8447 * below the top one have been redrawn. Following this callback it is safe to make the top
8448 * Activity translucent because the underlying Activity has been drawn.
8449 *
8450 * @param drawComplete True if the background Activity has drawn itself. False if a timeout
8451 * occurred waiting for the Activity to complete drawing.
8452 *
8453 * @see Activity#convertFromTranslucent()
Craig Mautner233ceee2014-05-09 17:05:11 -07008454 * @see Activity#convertToTranslucent(TranslucentConversionListener, ActivityOptions)
Craig Mautner5eda9b32013-07-02 11:58:16 -07008455 */
8456 public void onTranslucentConversionComplete(boolean drawComplete);
8457 }
Svetoslavc6d1c342015-02-26 14:44:43 -08008458
8459 private void dispatchRequestPermissionsResult(int requestCode, Intent data) {
Svetoslavffb32b12015-10-15 16:54:00 -07008460 mHasCurrentPermissionsRequest = false;
Svet Ganov6a166af2015-06-30 10:15:44 -07008461 // If the package installer crashed we may have not data - best effort.
8462 String[] permissions = (data != null) ? data.getStringArrayExtra(
8463 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8464 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8465 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
Svetoslavc6d1c342015-02-26 14:44:43 -08008466 onRequestPermissionsResult(requestCode, permissions, grantResults);
8467 }
8468
8469 private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
Svet Ganov6a166af2015-06-30 10:15:44 -07008470 Fragment fragment) {
8471 // If the package installer crashed we may have not data - best effort.
8472 String[] permissions = (data != null) ? data.getStringArrayExtra(
8473 PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
8474 final int[] grantResults = (data != null) ? data.getIntArrayExtra(
8475 PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
8476 fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
Svetoslavc6d1c342015-02-26 14:44:43 -08008477 }
8478
Svet Ganov782043c2017-02-11 00:52:02 +00008479 /** @hide */
8480 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008481 public final void autofillClientAuthenticate(int authenticationId, IntentSender intent,
Adam He5be0f152020-02-03 15:53:32 -08008482 Intent fillInIntent, boolean authenticateInline) {
Svet Ganov782043c2017-02-11 00:52:02 +00008483 try {
8484 startIntentSenderForResultInner(intent, AUTO_FILL_AUTH_WHO_PREFIX,
Svetoslav Ganova9379d02017-05-09 17:40:24 -07008485 authenticationId, fillInIntent, 0, 0, null);
Svet Ganov782043c2017-02-11 00:52:02 +00008486 } catch (IntentSender.SendIntentException e) {
8487 Log.e(TAG, "authenticate() failed for intent:" + intent, e);
8488 }
8489 }
8490
Svet Ganov17db9dc2017-02-21 19:54:31 -08008491 /** @hide */
8492 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008493 public final void autofillClientResetableStateAvailable() {
Svet Ganov17db9dc2017-02-21 19:54:31 -08008494 mAutoFillResetNeeded = true;
8495 }
8496
Felipe Leme4753bb02017-03-22 20:24:00 -07008497 /** @hide */
8498 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008499 public final boolean autofillClientRequestShowFillUi(@NonNull View anchor, int width,
Felipe Leme4753bb02017-03-22 20:24:00 -07008500 int height, @Nullable Rect anchorBounds, IAutofillWindowPresenter presenter) {
Felipe Leme4753bb02017-03-22 20:24:00 -07008501 final boolean wasShowing;
8502
8503 if (mAutofillPopupWindow == null) {
8504 wasShowing = false;
8505 mAutofillPopupWindow = new AutofillPopupWindow(presenter);
8506 } else {
8507 wasShowing = mAutofillPopupWindow.isShowing();
8508 }
Svet Ganov374cae12017-05-10 13:42:33 -07008509 mAutofillPopupWindow.update(anchor, 0, 0, width, height, anchorBounds);
Felipe Leme4753bb02017-03-22 20:24:00 -07008510
8511 return !wasShowing && mAutofillPopupWindow.isShowing();
8512 }
8513
8514 /** @hide */
8515 @Override
Dake Gu6a20a192018-02-08 12:09:30 -08008516 public final void autofillClientDispatchUnhandledKey(@NonNull View anchor,
8517 @NonNull KeyEvent keyEvent) {
8518 ViewRootImpl rootImpl = anchor.getViewRootImpl();
8519 if (rootImpl != null) {
8520 // dont care if anchorView is current focus, for example a custom view may only receive
8521 // touchEvent, not focusable but can still trigger autofill window. The Key handling
8522 // might be inside parent of the custom view.
8523 rootImpl.dispatchKeyFromAutofill(keyEvent);
8524 }
8525 }
8526
8527 /** @hide */
8528 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008529 public final boolean autofillClientRequestHideFillUi() {
Felipe Leme4753bb02017-03-22 20:24:00 -07008530 if (mAutofillPopupWindow == null) {
8531 return false;
8532 }
8533 mAutofillPopupWindow.dismiss();
8534 mAutofillPopupWindow = null;
8535 return true;
8536 }
8537
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008538 /** @hide */
Felipe Leme27e20222017-05-18 15:24:11 -07008539 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008540 public final boolean autofillClientIsFillUiShowing() {
8541 return mAutofillPopupWindow != null && mAutofillPopupWindow.isShowing();
8542 }
8543
8544 /** @hide */
8545 @Override
8546 @NonNull
8547 public final View[] autofillClientFindViewsByAutofillIdTraversal(
8548 @NonNull AutofillId[] autofillId) {
8549 final View[] views = new View[autofillId.length];
Philip P. Moltmann134cee22017-05-06 11:28:38 -07008550 final ArrayList<ViewRootImpl> roots =
8551 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
8552
8553 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8554 final View rootView = roots.get(rootNum).getView();
8555
8556 if (rootView != null) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008557 final int viewCount = autofillId.length;
8558 for (int viewNum = 0; viewNum < viewCount; viewNum++) {
Philip P. Moltmann134cee22017-05-06 11:28:38 -07008559 if (views[viewNum] == null) {
Phil Weaver846cda932017-06-15 10:10:06 -07008560 views[viewNum] = rootView.findViewByAutofillIdTraversal(
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008561 autofillId[viewNum].getViewId());
Philip P. Moltmann134cee22017-05-06 11:28:38 -07008562 }
8563 }
8564 }
8565 }
8566
8567 return views;
8568 }
8569
8570 /** @hide */
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008571 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008572 @Nullable
8573 public final View autofillClientFindViewByAutofillIdTraversal(AutofillId autofillId) {
Felipe Leme27e20222017-05-18 15:24:11 -07008574 final ArrayList<ViewRootImpl> roots =
8575 WindowManagerGlobal.getInstance().getRootViews(getActivityToken());
8576 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8577 final View rootView = roots.get(rootNum).getView();
8578
8579 if (rootView != null) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008580 final View view = rootView.findViewByAutofillIdTraversal(autofillId.getViewId());
Felipe Leme27e20222017-05-18 15:24:11 -07008581 if (view != null) {
8582 return view;
8583 }
8584 }
8585 }
8586
8587 return null;
8588 }
8589
8590 /** @hide */
8591 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008592 public final @NonNull boolean[] autofillClientGetViewVisibility(
8593 @NonNull AutofillId[] autofillIds) {
8594 final int autofillIdCount = autofillIds.length;
8595 final boolean[] visible = new boolean[autofillIdCount];
8596 for (int i = 0; i < autofillIdCount; i++) {
8597 final AutofillId autofillId = autofillIds[i];
8598 final View view = autofillClientFindViewByAutofillIdTraversal(autofillId);
8599 if (view != null) {
Felipe Lemea75333c2019-01-22 15:45:32 -08008600 if (!autofillId.isVirtualInt()) {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008601 visible[i] = view.isVisibleToUser();
Philip P. Moltmann134cee22017-05-06 11:28:38 -07008602 } else {
Felipe Lemea75333c2019-01-22 15:45:32 -08008603 visible[i] = view.isVisibleToUserForAutofill(autofillId.getVirtualChildIntId());
Philip P. Moltmann134cee22017-05-06 11:28:38 -07008604 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008605 }
8606 }
Felipe Leme5b32ebe2018-02-15 12:52:19 -08008607 if (android.view.autofill.Helper.sVerbose) {
8608 Log.v(TAG, "autofillClientGetViewVisibility(): " + Arrays.toString(visible));
8609 }
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008610 return visible;
8611 }
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008612
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008613 /** @hide */
8614 public final @Nullable View autofillClientFindViewByAccessibilityIdTraversal(int viewId,
8615 int windowId) {
8616 final ArrayList<ViewRootImpl> roots = WindowManagerGlobal.getInstance()
8617 .getRootViews(getActivityToken());
8618 for (int rootNum = 0; rootNum < roots.size(); rootNum++) {
8619 final View rootView = roots.get(rootNum).getView();
8620 if (rootView != null && rootView.getAccessibilityWindowId() == windowId) {
8621 final View view = rootView.findViewByAccessibilityIdTraversal(viewId);
8622 if (view != null) {
8623 return view;
8624 }
8625 }
8626 }
8627 return null;
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008628 }
8629
8630 /** @hide */
8631 @Override
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008632 public final @Nullable IBinder autofillClientGetActivityToken() {
8633 return getActivityToken();
8634 }
8635
8636 /** @hide */
8637 @Override
8638 public final boolean autofillClientIsVisibleForAutofill() {
Philip P. Moltmann494c3f52017-04-11 10:13:33 -07008639 return !mStopped;
8640 }
8641
Dake Gu67decfa2017-12-27 11:48:08 -08008642 /** @hide */
8643 @Override
Felipe Leme42b97932018-02-20 13:04:31 -08008644 public final boolean autofillClientIsCompatibilityModeEnabled() {
Svetoslav Ganov24c90452017-12-27 15:17:14 -08008645 return isAutofillCompatibilityEnabled();
8646 }
8647
8648 /** @hide */
8649 @Override
8650 public final boolean isDisablingEnterExitEventForAutofill() {
Dake Gu67decfa2017-12-27 11:48:08 -08008651 return mAutoFillIgnoreFirstResumePause || !mResumed;
8652 }
8653
Jorim Jaggi0fe7ce962017-02-22 16:45:48 +01008654 /**
8655 * If set to true, this indicates to the system that it should never take a
8656 * screenshot of the activity to be used as a representation while it is not in a started state.
8657 * <p>
8658 * Note that the system may use the window background of the theme instead to represent
8659 * the window when it is not running.
8660 * <p>
8661 * Also note that in comparison to {@link android.view.WindowManager.LayoutParams#FLAG_SECURE},
8662 * this only affects the behavior when the activity's screenshot would be used as a
8663 * representation when the activity is not in a started state, i.e. in Overview. The system may
8664 * still take screenshots of the activity in other contexts; for example, when the user takes a
8665 * screenshot of the entire screen, or when the active
8666 * {@link android.service.voice.VoiceInteractionService} requests a screenshot via
8667 * {@link android.service.voice.VoiceInteractionSession#SHOW_WITH_SCREENSHOT}.
8668 *
8669 * @param disable {@code true} to disable preview screenshots; {@code false} otherwise.
8670 * @hide
8671 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01008672 @UnsupportedAppUsage
Jorim Jaggi0fe7ce962017-02-22 16:45:48 +01008673 public void setDisablePreviewScreenshots(boolean disable) {
8674 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008675 ActivityTaskManager.getService().setDisablePreviewScreenshots(mToken, disable);
Jorim Jaggi0fe7ce962017-02-22 16:45:48 +01008676 } catch (RemoteException e) {
Issei Suzukiae7b4932019-03-12 10:03:21 -07008677 throw e.rethrowFromSystemServer();
Jorim Jaggi0fe7ce962017-02-22 16:45:48 +01008678 }
8679 }
8680
chaviw59b98852017-06-13 12:05:44 -07008681 /**
koprivaa1a78482018-10-09 10:09:23 -07008682 * Specifies whether an {@link Activity} should be shown on top of the lock screen whenever
chaviw59b98852017-06-13 12:05:44 -07008683 * the lockscreen is up and the activity is resumed. Normally an activity will be transitioned
8684 * to the stopped state if it is started while the lockscreen is up, but with this flag set the
8685 * activity will remain in the resumed state visible on-top of the lock screen. This value can
8686 * be set as a manifest attribute using {@link android.R.attr#showWhenLocked}.
8687 *
8688 * @param showWhenLocked {@code true} to show the {@link Activity} on top of the lock screen;
8689 * {@code false} otherwise.
8690 * @see #setTurnScreenOn(boolean)
8691 * @see android.R.attr#turnScreenOn
8692 * @see android.R.attr#showWhenLocked
8693 */
8694 public void setShowWhenLocked(boolean showWhenLocked) {
8695 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008696 ActivityTaskManager.getService().setShowWhenLocked(mToken, showWhenLocked);
chaviw59b98852017-06-13 12:05:44 -07008697 } catch (RemoteException e) {
Issei Suzukiae7b4932019-03-12 10:03:21 -07008698 throw e.rethrowFromSystemServer();
chaviw59b98852017-06-13 12:05:44 -07008699 }
8700 }
8701
8702 /**
Issei Suzuki74e1eb22018-12-20 17:42:52 +01008703 * Specifies whether this {@link Activity} should be shown on top of the lock screen whenever
8704 * the lockscreen is up and this activity has another activity behind it with the showWhenLock
8705 * attribute set. That is, this activity is only visible on the lock screen if there is another
8706 * activity with the showWhenLock attribute visible at the same time on the lock screen. A use
8707 * case for this is permission dialogs, that should only be visible on the lock screen if their
8708 * requesting activity is also visible. This value can be set as a manifest attribute using
8709 * android.R.attr#inheritShowWhenLocked.
8710 *
8711 * @param inheritShowWhenLocked {@code true} to show the {@link Activity} on top of the lock
8712 * screen when this activity has another activity behind it with
8713 * the showWhenLock attribute set; {@code false} otherwise.
8714 * @see #setShowWhenLocked(boolean)
Issei Suzuki7c09f0b2019-02-28 14:45:50 +01008715 * @see android.R.attr#inheritShowWhenLocked
Issei Suzuki74e1eb22018-12-20 17:42:52 +01008716 */
Issei Suzuki74e1eb22018-12-20 17:42:52 +01008717 public void setInheritShowWhenLocked(boolean inheritShowWhenLocked) {
8718 try {
8719 ActivityTaskManager.getService().setInheritShowWhenLocked(
8720 mToken, inheritShowWhenLocked);
8721 } catch (RemoteException e) {
Issei Suzukiae7b4932019-03-12 10:03:21 -07008722 throw e.rethrowFromSystemServer();
Issei Suzuki74e1eb22018-12-20 17:42:52 +01008723 }
8724 }
8725
8726 /**
chaviw59b98852017-06-13 12:05:44 -07008727 * Specifies whether the screen should be turned on when the {@link Activity} is resumed.
8728 * Normally an activity will be transitioned to the stopped state if it is started while the
8729 * screen if off, but with this flag set the activity will cause the screen to turn on if the
8730 * activity will be visible and resumed due to the screen coming on. The screen will not be
8731 * turned on if the activity won't be visible after the screen is turned on. This flag is
8732 * normally used in conjunction with the {@link android.R.attr#showWhenLocked} flag to make sure
8733 * the activity is visible after the screen is turned on when the lockscreen is up. In addition,
8734 * if this flag is set and the activity calls {@link
8735 * KeyguardManager#requestDismissKeyguard(Activity, KeyguardManager.KeyguardDismissCallback)}
8736 * the screen will turn on.
8737 *
8738 * @param turnScreenOn {@code true} to turn on the screen; {@code false} otherwise.
8739 *
8740 * @see #setShowWhenLocked(boolean)
8741 * @see android.R.attr#turnScreenOn
8742 * @see android.R.attr#showWhenLocked
8743 */
8744 public void setTurnScreenOn(boolean turnScreenOn) {
8745 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008746 ActivityTaskManager.getService().setTurnScreenOn(mToken, turnScreenOn);
chaviw59b98852017-06-13 12:05:44 -07008747 } catch (RemoteException e) {
Issei Suzukiae7b4932019-03-12 10:03:21 -07008748 throw e.rethrowFromSystemServer();
chaviw59b98852017-06-13 12:05:44 -07008749 }
8750 }
8751
Jorim Jaggif84e2f62018-01-16 14:17:59 +01008752 /**
8753 * Registers remote animations per transition type for this activity.
8754 *
8755 * @param definition The remote animation definition that defines which transition whould run
8756 * which remote animation.
8757 * @hide
8758 */
8759 @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
8760 public void registerRemoteAnimations(RemoteAnimationDefinition definition) {
8761 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07008762 ActivityTaskManager.getService().registerRemoteAnimations(mToken, definition);
Jorim Jaggif84e2f62018-01-16 14:17:59 +01008763 } catch (RemoteException e) {
Issei Suzukiae7b4932019-03-12 10:03:21 -07008764 throw e.rethrowFromSystemServer();
Jorim Jaggif84e2f62018-01-16 14:17:59 +01008765 }
8766 }
8767
Winson Chung10fc25d2019-12-10 14:13:56 -08008768 /**
8769 * Unregisters all remote animations for this activity.
8770 *
8771 * @hide
8772 */
8773 @RequiresPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS)
8774 public void unregisterRemoteAnimations() {
8775 try {
8776 ActivityTaskManager.getService().unregisterRemoteAnimations(mToken);
8777 } catch (RemoteException e) {
8778 throw e.rethrowFromSystemServer();
8779 }
8780 }
8781
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008782 class HostCallbacks extends FragmentHostCallback<Activity> {
8783 public HostCallbacks() {
8784 super(Activity.this /*activity*/);
8785 }
8786
8787 @Override
8788 public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
8789 Activity.this.dump(prefix, fd, writer, args);
8790 }
8791
8792 @Override
8793 public boolean onShouldSaveFragmentState(Fragment fragment) {
8794 return !isFinishing();
8795 }
8796
8797 @Override
8798 public LayoutInflater onGetLayoutInflater() {
8799 final LayoutInflater result = Activity.this.getLayoutInflater();
8800 if (onUseFragmentManagerInflaterFactory()) {
8801 return result.cloneInContext(Activity.this);
8802 }
8803 return result;
8804 }
8805
8806 @Override
8807 public boolean onUseFragmentManagerInflaterFactory() {
8808 // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
8809 return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
8810 }
8811
8812 @Override
8813 public Activity onGetHost() {
8814 return Activity.this;
8815 }
8816
8817 @Override
8818 public void onInvalidateOptionsMenu() {
8819 Activity.this.invalidateOptionsMenu();
8820 }
8821
8822 @Override
8823 public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
8824 Bundle options) {
8825 Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
8826 }
8827
8828 @Override
Tony Mak96d26fe2017-04-11 20:05:39 +01008829 public void onStartActivityAsUserFromFragment(
8830 Fragment fragment, Intent intent, int requestCode, Bundle options,
8831 UserHandle user) {
8832 Activity.this.startActivityAsUserFromFragment(
8833 fragment, intent, requestCode, options, user);
8834 }
8835
8836 @Override
Clara Bayarria0c2dc32016-04-12 12:00:15 +01008837 public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent,
8838 int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues,
8839 int extraFlags, Bundle options) throws IntentSender.SendIntentException {
8840 if (mParent == null) {
8841 startIntentSenderForResultInner(intent, fragment.mWho, requestCode, fillInIntent,
8842 flagsMask, flagsValues, options);
8843 } else if (options != null) {
Charles Chenc380f022019-08-13 18:39:17 +08008844 mParent.startIntentSenderFromFragment(fragment, intent, requestCode,
8845 fillInIntent, flagsMask, flagsValues, options);
Clara Bayarria0c2dc32016-04-12 12:00:15 +01008846 }
8847 }
8848
8849 @Override
Svetoslav970b59c2015-06-09 16:05:21 -07008850 public void onRequestPermissionsFromFragment(Fragment fragment, String[] permissions,
8851 int requestCode) {
8852 String who = REQUEST_PERMISSIONS_WHO_PREFIX + fragment.mWho;
8853 Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
8854 startActivityForResult(who, intent, requestCode, null);
8855 }
8856
8857 @Override
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008858 public boolean onHasWindowAnimations() {
8859 return getWindow() != null;
8860 }
8861
8862 @Override
8863 public int onGetWindowAnimations() {
8864 final Window w = getWindow();
8865 return (w == null) ? 0 : w.getAttributes().windowAnimations;
8866 }
8867
Todd Kennedy434bd652015-05-04 12:29:50 -07008868 @Override
8869 public void onAttachFragment(Fragment fragment) {
8870 Activity.this.onAttachFragment(fragment);
8871 }
8872
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008873 @Nullable
8874 @Override
Alan Viverette04fd4702017-04-13 16:37:06 -04008875 public <T extends View> T onFindViewById(int id) {
Todd Kennedya5fc6f02015-04-14 18:22:54 -07008876 return Activity.this.findViewById(id);
8877 }
8878
8879 @Override
8880 public boolean onHasView() {
8881 final Window w = getWindow();
8882 return (w != null && w.peekDecorView() != null);
8883 }
8884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885}