blob: b79d9e9691cbac876414c1a1430bd7b1c736e633 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 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 com.android.server.am;
18
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalef6733932018-06-27 05:14:34 -070029import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
30import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
31import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070032import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef6733932018-06-27 05:14:34 -070033import static com.android.server.am.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
34import static com.android.server.am.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070035import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
36import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
37import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
38import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.ActivityTaskManager.INVALID_STACK_ID;
40import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070042import static android.app.AppOpsManager.OP_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070044import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070045import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
46import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
47import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070048import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
49import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070050import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070051import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070052import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070053import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
54import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070056import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
58import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070059import static android.os.Process.SYSTEM_UID;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070060import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
63import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
65import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070067import static android.view.WindowManager.TRANSIT_ACTIVITY_OPEN;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070070import static android.view.WindowManager.TRANSIT_TASK_OPEN;
71import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070072import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070073import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
74import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOCUS;
75import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_IMMERSIVE;
76import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LOCKTASK;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070077import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070078import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070079import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070080import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070081import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_VISIBILITY;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070082import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CONFIGURATION;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070083import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_FOCUS;
84import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_IMMERSIVE;
85import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LOCKTASK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070086import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070087import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
88import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_VISIBILITY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070089import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
90import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070091import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070092import static com.android.server.am.ActivityManagerService.ANIMATE;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070093import static com.android.server.am.ActivityManagerService.MY_PID;
94import static com.android.server.am.ActivityManagerService.SEND_LOCALE_TO_MOUNT_DAEMON_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070095import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070096import static com.android.server.am.ActivityManagerService.UPDATE_CONFIGURATION_MSG;
97import static com.android.server.am.ActivityManagerService.checkComponentPermission;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070098import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070099import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700100import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
101import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
102import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
103import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
104import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
105import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
106import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700107import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700108import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
109import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
110import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700111
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700112import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700113import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700114import android.annotation.Nullable;
115import android.annotation.UserIdInt;
116import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700117import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700118import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700119import android.app.ActivityOptions;
120import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700121import android.app.ActivityThread;
122import android.app.AlertDialog;
123import android.app.Dialog;
124import android.content.DialogInterface;
125import android.database.ContentObserver;
126import android.os.IUserManager;
127import android.os.PowerManager;
128import android.os.ServiceManager;
129import android.os.Trace;
130import android.os.UserManager;
131import android.os.WorkSource;
132import android.view.WindowManager;
133import com.android.internal.R;
134import com.android.internal.annotations.GuardedBy;
135import com.android.internal.app.IAppOpsService;
136import com.android.server.AppOpsService;
137import com.android.server.pm.UserManagerService;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700138import com.android.server.wm.ActivityTaskManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.AppGlobals;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
144import android.app.ITaskStackListener;
145import android.app.PictureInPictureParams;
146import android.app.ProfilerInfo;
147import android.app.RemoteAction;
148import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700149import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.admin.DevicePolicyCache;
151import android.app.assist.AssistContent;
152import android.app.assist.AssistStructure;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700153import android.app.servertransaction.ConfigurationChangeItem;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.usage.UsageEvents;
155import android.content.ActivityNotFoundException;
156import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700157import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700158import android.content.Context;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.IIntentSender;
160import android.content.Intent;
161import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.pm.ApplicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.pm.PackageManager;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.ResolveInfo;
166import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.res.Resources;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.graphics.Bitmap;
169import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700170import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.metrics.LogMaker;
172import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700173import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700174import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.os.Bundle;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700176import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700177import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.os.IBinder;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700179import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700180import android.os.Looper;
181import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.PersistableBundle;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700183import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.RemoteException;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700186import android.os.SystemClock;
187import android.os.SystemProperties;
188import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.UserHandle;
190import android.provider.Settings;
191import android.service.voice.IVoiceInteractionSession;
192import android.service.voice.VoiceInteractionManagerInternal;
193import android.telecom.TelecomManager;
194import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700195import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700196import android.util.ArrayMap;
197import android.util.EventLog;
198import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700199import android.util.Slog;
200
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700202import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700205import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700206import android.view.IRecentsAnimationRunner;
207import android.view.RemoteAnimationAdapter;
208import android.view.RemoteAnimationDefinition;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700209
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700210import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import com.android.internal.app.AssistUtils;
212import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import com.android.internal.logging.MetricsLogger;
215import com.android.internal.os.logging.MetricsLoggerWrapper;
216import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
217import com.android.internal.policy.IKeyguardDismissCallback;
218import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import com.android.internal.util.Preconditions;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700221import com.android.server.LocalServices;
222import com.android.server.SystemService;
223import com.android.server.Watchdog;
224import com.android.server.vr.VrManagerInternal;
225import com.android.server.wm.PinnedStackWindowController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import com.android.server.wm.WindowManagerService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227
228import java.io.File;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700229import java.io.FileOutputStream;
230import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700231import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import java.io.StringWriter;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233import java.util.ArrayList;
234import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import java.util.Locale;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700236
237/**
238 * System service for managing activities and their containers (task, stacks, displays,... ).
239 *
240 * {@hide}
241 */
242public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
243 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_AM;
244 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
246 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
247 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
248 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
249 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700251
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700252 Context mContext;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700253 /**
254 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
255 * change at runtime. Use mContext for non-UI purposes.
256 */
257 final Context mUiContext;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700258 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700259 UiHandler mUiHandler;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700260 ActivityManagerService mAm;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700261 ActivityManagerInternal mAmInternal;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700262 /* Global service lock used by the package the owns this service. */
263 Object mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700264 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700265 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700266 private UserManagerService mUserManager;
267 private AppOpsService mAppOpsService;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700268 /** All processes currently running that might have a window organized by name. */
269 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
270 /** This is the process holding what we currently consider to be the "home" activity. */
271 WindowProcessController mHomeProcess;
272 /**
273 * This is the process holding the activity the user last visited that is in a different process
274 * from the one they are currently in.
275 */
276 WindowProcessController mPreviousProcess;
277 /** The time at which the previous process was last visible. */
278 long mPreviousProcessVisibleTime;
279
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700280 /** List of intents that were used to start the most recent tasks. */
281 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700282 /** State of external calls telling us if the device is awake or asleep. */
283 private boolean mKeyguardShown = false;
284
285 // Wrapper around VoiceInteractionServiceManager
286 private AssistUtils mAssistUtils;
287
288 // VoiceInteraction session ID that changes for each new request except when
289 // being called for multi-window assist in a single session.
290 private int mViSessionId = 1000;
291
292 // How long to wait in getAssistContextExtras for the activity and foreground services
293 // to respond with the result.
294 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
295
296 // How long top wait when going through the modern assist (which doesn't need to block
297 // on getting this result before starting to launch its UI).
298 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
299
300 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
301 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
302
303 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
304
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700305 // Keeps track of the active voice interaction service component, notified from
306 // VoiceInteractionManagerService
307 ComponentName mActiveVoiceInteractionServiceComponent;
308
309 private VrController mVrController;
310 KeyguardController mKeyguardController;
311 private final ClientLifecycleManager mLifecycleManager;
312 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700313 /** The controller for all operations related to locktask. */
314 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700315 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700316
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700317 boolean mSuppressResizeConfigChanges;
318
319 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
320 new UpdateConfigurationResult();
321
322 static final class UpdateConfigurationResult {
323 // Configuration changes that were updated.
324 int changes;
325 // If the activity was relaunched to match the new configuration.
326 boolean activityRelaunched;
327
328 void reset() {
329 changes = 0;
330 activityRelaunched = false;
331 }
332 }
333
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700334 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700335 private int mConfigurationSeq;
336 // To cache the list of supported system locales
337 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700338
339 /**
340 * Temp object used when global and/or display override configuration is updated. It is also
341 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
342 * anyone...
343 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 private Configuration mTempConfig = new Configuration();
345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /** Temporary to avoid allocations. */
347 final StringBuilder mStringBuilder = new StringBuilder(256);
348
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 // Amount of time after a call to stopAppSwitches() during which we will
350 // prevent further untrusted switches from happening.
351 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
352
353 /**
354 * The time at which we will allow normal application switches again,
355 * after a call to {@link #stopAppSwitches()}.
356 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700357 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700358 /**
359 * This is set to true after the first switch after mAppSwitchesAllowedTime
360 * is set; any switches after that will clear the time.
361 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700362 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700363
364 IActivityController mController = null;
365 boolean mControllerIsAMonkey = false;
366
367 /**
368 * Used to retain an update lock when the foreground activity is in
369 * immersive mode.
370 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700372
373 /**
374 * Packages that are being allowed to perform unrestricted app switches. Mapping is
375 * User -> Type -> uid.
376 */
377 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
378
379 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private int mThumbnailWidth;
381 private int mThumbnailHeight;
382 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700383
384 /**
385 * Flag that indicates if multi-window is enabled.
386 *
387 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
388 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
389 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
390 * At least one of the forms of multi-window must be enabled in order for this flag to be
391 * initialized to 'true'.
392 *
393 * @see #mSupportsSplitScreenMultiWindow
394 * @see #mSupportsFreeformWindowManagement
395 * @see #mSupportsPictureInPicture
396 * @see #mSupportsMultiDisplay
397 */
398 boolean mSupportsMultiWindow;
399 boolean mSupportsSplitScreenMultiWindow;
400 boolean mSupportsFreeformWindowManagement;
401 boolean mSupportsPictureInPicture;
402 boolean mSupportsMultiDisplay;
403 boolean mForceResizableActivities;
404
405 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
406
407 // VR Vr2d Display Id.
408 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700409
Wale Ogunwalef6733932018-06-27 05:14:34 -0700410 /**
411 * Set while we are wanting to sleep, to prevent any
412 * activities from being started/resumed.
413 *
414 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
415 *
416 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
417 * while in the sleep state until there is a pending transition out of sleep, in which case
418 * mSleeping is set to false, and remains false while awake.
419 *
420 * Whether mSleeping can quickly toggled between true/false without the device actually
421 * display changing states is undefined.
422 */
423 private boolean mSleeping = false;
424
425 /**
426 * The process state used for processes that are running the top activities.
427 * This changes between TOP and TOP_SLEEPING to following mSleeping.
428 */
429 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
430
431 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
432 // automatically. Important for devices without direct input devices.
433 private boolean mShowDialogs = true;
434
435 /** Set if we are shutting down the system, similar to sleeping. */
436 boolean mShuttingDown = false;
437
438 /**
439 * We want to hold a wake lock while running a voice interaction session, since
440 * this may happen with the screen off and we need to keep the CPU running to
441 * be able to continue to interact with the user.
442 */
443 PowerManager.WakeLock mVoiceWakeLock;
444
445 /**
446 * Set while we are running a voice interaction. This overrides sleeping while it is active.
447 */
448 IVoiceInteractionSession mRunningVoice;
449
450 /**
451 * The last resumed activity. This is identical to the current resumed activity most
452 * of the time but could be different when we're pausing one activity before we resume
453 * another activity.
454 */
455 ActivityRecord mLastResumedActivity;
456
457 /**
458 * The activity that is currently being traced as the active resumed activity.
459 *
460 * @see #updateResumedAppTrace
461 */
462 private @Nullable ActivityRecord mTracedResumedActivity;
463
464 /** If non-null, we are tracking the time the user spends in the currently focused app. */
465 AppTimeTracker mCurAppTimeTracker;
466
467 private FontScaleSettingObserver mFontScaleSettingObserver;
468
469 private final class FontScaleSettingObserver extends ContentObserver {
470 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
471 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
472
473 public FontScaleSettingObserver() {
474 super(mH);
475 final ContentResolver resolver = mContext.getContentResolver();
476 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
477 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
478 UserHandle.USER_ALL);
479 }
480
481 @Override
482 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
483 if (mFontScaleUri.equals(uri)) {
484 updateFontScaleIfNeeded(userId);
485 } else if (mHideErrorDialogsUri.equals(uri)) {
486 synchronized (mGlobalLock) {
487 updateShouldShowDialogsLocked(getGlobalConfiguration());
488 }
489 }
490 }
491 }
492
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700493 ActivityTaskManagerService(Context context) {
494 mContext = context;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 mUiContext = ActivityThread.currentActivityThread().getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700496 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700497 }
498
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700499 void onSystemReady() {
500 mAssistUtils = new AssistUtils(mContext);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700501 mVrController.onSystemReady();
502 mRecentTasks.onSystemReadyLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700503 }
504
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 void onInitPowerManagement() {
506 mStackSupervisor.initPowerManagement();
507 final PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
508 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
509 mVoiceWakeLock.setReferenceCounted(false);
510 }
511
512 void installSystemProviders() {
513 mFontScaleSettingObserver = new FontScaleSettingObserver();
514 }
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 void retrieveSettings(ContentResolver resolver) {
517 final boolean freeformWindowManagement =
518 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
519 || Settings.Global.getInt(
520 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
521
522 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
523 final boolean supportsPictureInPicture = supportsMultiWindow &&
524 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
525 final boolean supportsSplitScreenMultiWindow =
526 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
527 final boolean supportsMultiDisplay = mContext.getPackageManager()
528 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
529 final boolean alwaysFinishActivities =
530 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
531 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
532 final boolean forceResizable = Settings.Global.getInt(
533 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
534
535 // Transfer any global setting for forcing RTL layout, into a System Property
536 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
537
538 final Configuration configuration = new Configuration();
539 Settings.System.getConfiguration(resolver, configuration);
540 if (forceRtl) {
541 // This will take care of setting the correct layout direction flags
542 configuration.setLayoutDirection(configuration.locale);
543 }
544
545 synchronized (mGlobalLock) {
546 mForceResizableActivities = forceResizable;
547 final boolean multiWindowFormEnabled = freeformWindowManagement
548 || supportsSplitScreenMultiWindow
549 || supportsPictureInPicture
550 || supportsMultiDisplay;
551 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
552 mSupportsMultiWindow = true;
553 mSupportsFreeformWindowManagement = freeformWindowManagement;
554 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
555 mSupportsPictureInPicture = supportsPictureInPicture;
556 mSupportsMultiDisplay = supportsMultiDisplay;
557 } else {
558 mSupportsMultiWindow = false;
559 mSupportsFreeformWindowManagement = false;
560 mSupportsSplitScreenMultiWindow = false;
561 mSupportsPictureInPicture = false;
562 mSupportsMultiDisplay = false;
563 }
564 mWindowManager.setForceResizableTasks(mForceResizableActivities);
565 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
566 // This happens before any activities are started, so we can change global configuration
567 // in-place.
568 updateConfigurationLocked(configuration, null, true);
569 final Configuration globalConfig = getGlobalConfiguration();
570 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
571
572 // Load resources only after the current configuration has been set.
573 final Resources res = mContext.getResources();
574 mThumbnailWidth = res.getDimensionPixelSize(
575 com.android.internal.R.dimen.thumbnail_width);
576 mThumbnailHeight = res.getDimensionPixelSize(
577 com.android.internal.R.dimen.thumbnail_height);
578
579 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
580 mFullscreenThumbnailScale = (float) res
581 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
582 (float) globalConfig.screenWidthDp;
583 } else {
584 mFullscreenThumbnailScale = res.getFraction(
585 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
586 }
587 }
588 }
589
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700590 // TODO: Will be converted to WM lock once transition is complete.
591 void setActivityManagerService(ActivityManagerService am) {
592 mAm = am;
593 mGlobalLock = mAm;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700594 mH = new H(mAm.mHandlerThread.getLooper());
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700595 mUiHandler = new UiHandler();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700596
597 mTempConfig.setToDefaults();
598 mTempConfig.setLocales(LocaleList.getDefault());
599 mConfigurationSeq = mTempConfig.seq = 1;
600 mStackSupervisor = createStackSupervisor();
601 mStackSupervisor.onConfigurationChanged(mTempConfig);
602
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700603 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700604 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700605 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700606 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700607 mRecentTasks = createRecentTasks();
608 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700609 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700610 mKeyguardController = mStackSupervisor.getKeyguardController();
611 }
612
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700613 void onActivityManagerInternalAdded() {
614 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
615 }
616
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700617 protected ActivityStackSupervisor createStackSupervisor() {
618 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
619 supervisor.initialize();
620 return supervisor;
621 }
622
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700623 void setWindowManager(WindowManagerService wm) {
624 mWindowManager = wm;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700625 mLockTaskController.setWindowManager(wm);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700626 }
627
Wale Ogunwalef6733932018-06-27 05:14:34 -0700628 UserManagerService getUserManager() {
629 if (mUserManager == null) {
630 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
631 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
632 }
633 return mUserManager;
634 }
635
636 AppOpsService getAppOpsService() {
637 if (mAppOpsService == null) {
638 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
639 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
640 }
641 return mAppOpsService;
642 }
643
644 boolean hasUserRestriction(String restriction, int userId) {
645 return getUserManager().hasUserRestriction(restriction, userId);
646 }
647
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700648 protected RecentTasks createRecentTasks() {
649 return new RecentTasks(this, mStackSupervisor);
650 }
651
652 RecentTasks getRecentTasks() {
653 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700654 }
655
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 ClientLifecycleManager getLifecycleManager() {
657 return mLifecycleManager;
658 }
659
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700660 ActivityStartController getActivityStartController() {
661 return mActivityStartController;
662 }
663
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700664 TaskChangeNotificationController getTaskChangeNotificationController() {
665 return mTaskChangeNotificationController;
666 }
667
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700668 LockTaskController getLockTaskController() {
669 return mLockTaskController;
670 }
671
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700672 private void start() {
673 LocalServices.addService(ActivityTaskManagerInternal.class, new LocalService());
674 }
675
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700676 public static final class Lifecycle extends SystemService {
677 private final ActivityTaskManagerService mService;
678
679 public Lifecycle(Context context) {
680 super(context);
681 mService = new ActivityTaskManagerService(context);
682 }
683
684 @Override
685 public void onStart() {
686 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700687 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700688 }
689
690 public ActivityTaskManagerService getService() {
691 return mService;
692 }
693 }
694
695 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700696 public final int startActivity(IApplicationThread caller, String callingPackage,
697 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
698 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
699 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
700 resultWho, requestCode, startFlags, profilerInfo, bOptions,
701 UserHandle.getCallingUserId());
702 }
703
704 @Override
705 public final int startActivities(IApplicationThread caller, String callingPackage,
706 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
707 int userId) {
708 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700709 enforceNotIsolatedCaller(reason);
710 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700711 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700712 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700713 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason);
714 }
715
716 @Override
717 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
718 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
719 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
720 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
721 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
722 true /*validateIncomingUser*/);
723 }
724
725 int startActivityAsUser(IApplicationThread caller, String callingPackage,
726 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
727 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
728 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700730
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700731 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
733
734 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700735 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700736 .setCaller(caller)
737 .setCallingPackage(callingPackage)
738 .setResolvedType(resolvedType)
739 .setResultTo(resultTo)
740 .setResultWho(resultWho)
741 .setRequestCode(requestCode)
742 .setStartFlags(startFlags)
743 .setProfilerInfo(profilerInfo)
744 .setActivityOptions(bOptions)
745 .setMayWait(userId)
746 .execute();
747
748 }
749
750 @Override
751 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
752 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
754 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700755 // Refuse possible leaked file descriptors
756 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
757 throw new IllegalArgumentException("File descriptors passed in Intent");
758 }
759
760 if (!(target instanceof PendingIntentRecord)) {
761 throw new IllegalArgumentException("Bad PendingIntent object");
762 }
763
764 PendingIntentRecord pir = (PendingIntentRecord)target;
765
766 synchronized (mGlobalLock) {
767 // If this is coming from the currently resumed activity, it is
768 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700769 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700770 if (stack.mResumedActivity != null &&
771 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700773 }
774 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700776 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700777 }
778
779 @Override
780 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
781 Bundle bOptions) {
782 // Refuse possible leaked file descriptors
783 if (intent != null && intent.hasFileDescriptors()) {
784 throw new IllegalArgumentException("File descriptors passed in Intent");
785 }
786 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
787
788 synchronized (mGlobalLock) {
789 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
790 if (r == null) {
791 SafeActivityOptions.abort(options);
792 return false;
793 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700794 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700795 // The caller is not running... d'oh!
796 SafeActivityOptions.abort(options);
797 return false;
798 }
799 intent = new Intent(intent);
800 // The caller is not allowed to change the data.
801 intent.setDataAndType(r.intent.getData(), r.intent.getType());
802 // And we are resetting to find the next component...
803 intent.setComponent(null);
804
805 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
806
807 ActivityInfo aInfo = null;
808 try {
809 List<ResolveInfo> resolves =
810 AppGlobals.getPackageManager().queryIntentActivities(
811 intent, r.resolvedType,
812 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
813 UserHandle.getCallingUserId()).getList();
814
815 // Look for the original activity in the list...
816 final int N = resolves != null ? resolves.size() : 0;
817 for (int i=0; i<N; i++) {
818 ResolveInfo rInfo = resolves.get(i);
819 if (rInfo.activityInfo.packageName.equals(r.packageName)
820 && rInfo.activityInfo.name.equals(r.info.name)) {
821 // We found the current one... the next matching is
822 // after it.
823 i++;
824 if (i<N) {
825 aInfo = resolves.get(i).activityInfo;
826 }
827 if (debug) {
828 Slog.v(TAG, "Next matching activity: found current " + r.packageName
829 + "/" + r.info.name);
830 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
831 ? "null" : aInfo.packageName + "/" + aInfo.name));
832 }
833 break;
834 }
835 }
836 } catch (RemoteException e) {
837 }
838
839 if (aInfo == null) {
840 // Nobody who is next!
841 SafeActivityOptions.abort(options);
842 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
843 return false;
844 }
845
846 intent.setComponent(new ComponentName(
847 aInfo.applicationInfo.packageName, aInfo.name));
848 intent.setFlags(intent.getFlags()&~(
849 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
850 Intent.FLAG_ACTIVITY_CLEAR_TOP|
851 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
852 FLAG_ACTIVITY_NEW_TASK));
853
854 // Okay now we need to start the new activity, replacing the currently running activity.
855 // This is a little tricky because we want to start the new one as if the current one is
856 // finished, but not finish the current one first so that there is no flicker.
857 // And thus...
858 final boolean wasFinishing = r.finishing;
859 r.finishing = true;
860
861 // Propagate reply information over to the new activity.
862 final ActivityRecord resultTo = r.resultTo;
863 final String resultWho = r.resultWho;
864 final int requestCode = r.requestCode;
865 r.resultTo = null;
866 if (resultTo != null) {
867 resultTo.removeResultsLocked(r, resultWho, requestCode);
868 }
869
870 final long origId = Binder.clearCallingIdentity();
871 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700872 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700873 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700874 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700875 .setResolvedType(r.resolvedType)
876 .setActivityInfo(aInfo)
877 .setResultTo(resultTo != null ? resultTo.appToken : null)
878 .setResultWho(resultWho)
879 .setRequestCode(requestCode)
880 .setCallingPid(-1)
881 .setCallingUid(r.launchedFromUid)
882 .setCallingPackage(r.launchedFromPackage)
883 .setRealCallingPid(-1)
884 .setRealCallingUid(r.launchedFromUid)
885 .setActivityOptions(options)
886 .execute();
887 Binder.restoreCallingIdentity(origId);
888
889 r.finishing = wasFinishing;
890 if (res != ActivityManager.START_SUCCESS) {
891 return false;
892 }
893 return true;
894 }
895 }
896
897 @Override
898 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
899 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
900 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
901 final WaitResult res = new WaitResult();
902 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700903 enforceNotIsolatedCaller("startActivityAndWait");
904 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
905 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700906 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700907 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700908 .setCaller(caller)
909 .setCallingPackage(callingPackage)
910 .setResolvedType(resolvedType)
911 .setResultTo(resultTo)
912 .setResultWho(resultWho)
913 .setRequestCode(requestCode)
914 .setStartFlags(startFlags)
915 .setActivityOptions(bOptions)
916 .setMayWait(userId)
917 .setProfilerInfo(profilerInfo)
918 .setWaitResult(res)
919 .execute();
920 }
921 return res;
922 }
923
924 @Override
925 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
926 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
927 int startFlags, Configuration config, Bundle bOptions, int userId) {
928 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700929 enforceNotIsolatedCaller("startActivityWithConfig");
930 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
931 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700932 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700933 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700934 .setCaller(caller)
935 .setCallingPackage(callingPackage)
936 .setResolvedType(resolvedType)
937 .setResultTo(resultTo)
938 .setResultWho(resultWho)
939 .setRequestCode(requestCode)
940 .setStartFlags(startFlags)
941 .setGlobalConfiguration(config)
942 .setActivityOptions(bOptions)
943 .setMayWait(userId)
944 .execute();
945 }
946 }
947
948 @Override
949 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
950 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
951 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
952 int userId) {
953
954 // This is very dangerous -- it allows you to perform a start activity (including
955 // permission grants) as any app that may launch one of your own activities. So
956 // we will only allow this to be done from activities that are part of the core framework,
957 // and then only when they are running as the system.
958 final ActivityRecord sourceRecord;
959 final int targetUid;
960 final String targetPackage;
961 final boolean isResolver;
962 synchronized (mGlobalLock) {
963 if (resultTo == null) {
964 throw new SecurityException("Must be called from an activity");
965 }
966 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
967 if (sourceRecord == null) {
968 throw new SecurityException("Called with bad activity token: " + resultTo);
969 }
970 if (!sourceRecord.info.packageName.equals("android")) {
971 throw new SecurityException(
972 "Must be called from an activity that is declared in the android package");
973 }
974 if (sourceRecord.app == null) {
975 throw new SecurityException("Called without a process attached to activity");
976 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700977 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700978 // This is still okay, as long as this activity is running under the
979 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700980 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700982 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700983 + " must be system uid or original calling uid "
984 + sourceRecord.launchedFromUid);
985 }
986 }
987 if (ignoreTargetSecurity) {
988 if (intent.getComponent() == null) {
989 throw new SecurityException(
990 "Component must be specified with ignoreTargetSecurity");
991 }
992 if (intent.getSelector() != null) {
993 throw new SecurityException(
994 "Selector not allowed with ignoreTargetSecurity");
995 }
996 }
997 targetUid = sourceRecord.launchedFromUid;
998 targetPackage = sourceRecord.launchedFromPackage;
999 isResolver = sourceRecord.isResolverOrChildActivity();
1000 }
1001
1002 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001003 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 }
1005
1006 // TODO: Switch to user app stacks here.
1007 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001008 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001009 .setCallingUid(targetUid)
1010 .setCallingPackage(targetPackage)
1011 .setResolvedType(resolvedType)
1012 .setResultTo(resultTo)
1013 .setResultWho(resultWho)
1014 .setRequestCode(requestCode)
1015 .setStartFlags(startFlags)
1016 .setActivityOptions(bOptions)
1017 .setMayWait(userId)
1018 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1019 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1020 .execute();
1021 } catch (SecurityException e) {
1022 // XXX need to figure out how to propagate to original app.
1023 // A SecurityException here is generally actually a fault of the original
1024 // calling activity (such as a fairly granting permissions), so propagate it
1025 // back to them.
1026 /*
1027 StringBuilder msg = new StringBuilder();
1028 msg.append("While launching");
1029 msg.append(intent.toString());
1030 msg.append(": ");
1031 msg.append(e.getMessage());
1032 */
1033 throw e;
1034 }
1035 }
1036
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1038 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1039 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1040 }
1041
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 @Override
1043 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1044 Intent intent, String resolvedType, IVoiceInteractionSession session,
1045 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1046 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001047 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 if (session == null || interactor == null) {
1049 throw new NullPointerException("null session or interactor");
1050 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001051 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001053 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 .setCallingUid(callingUid)
1055 .setCallingPackage(callingPackage)
1056 .setResolvedType(resolvedType)
1057 .setVoiceSession(session)
1058 .setVoiceInteractor(interactor)
1059 .setStartFlags(startFlags)
1060 .setProfilerInfo(profilerInfo)
1061 .setActivityOptions(bOptions)
1062 .setMayWait(userId)
1063 .execute();
1064 }
1065
1066 @Override
1067 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1068 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001069 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1070 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001072 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 .setCallingUid(callingUid)
1074 .setCallingPackage(callingPackage)
1075 .setResolvedType(resolvedType)
1076 .setActivityOptions(bOptions)
1077 .setMayWait(userId)
1078 .execute();
1079 }
1080
1081 @Override
1082 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1083 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001084 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 final int callingPid = Binder.getCallingPid();
1086 final long origId = Binder.clearCallingIdentity();
1087 try {
1088 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001089 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1090 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091
1092 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1094 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1096 recentsUid, assistDataReceiver);
1097 }
1098 } finally {
1099 Binder.restoreCallingIdentity(origId);
1100 }
1101 }
1102
1103 @Override
1104 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001105 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 "startActivityFromRecents()");
1107
1108 final int callingPid = Binder.getCallingPid();
1109 final int callingUid = Binder.getCallingUid();
1110 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1111 final long origId = Binder.clearCallingIdentity();
1112 try {
1113 synchronized (mGlobalLock) {
1114 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1115 safeOptions);
1116 }
1117 } finally {
1118 Binder.restoreCallingIdentity(origId);
1119 }
1120 }
1121
1122 /**
1123 * This is the internal entry point for handling Activity.finish().
1124 *
1125 * @param token The Binder token referencing the Activity we want to finish.
1126 * @param resultCode Result code, if any, from this Activity.
1127 * @param resultData Result data (Intent), if any, from this Activity.
1128 * @param finishTask Whether to finish the task associated with this Activity.
1129 *
1130 * @return Returns true if the activity successfully finished, or false if it is still running.
1131 */
1132 @Override
1133 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1134 int finishTask) {
1135 // Refuse possible leaked file descriptors
1136 if (resultData != null && resultData.hasFileDescriptors()) {
1137 throw new IllegalArgumentException("File descriptors passed in Intent");
1138 }
1139
1140 synchronized (mGlobalLock) {
1141 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1142 if (r == null) {
1143 return true;
1144 }
1145 // Keep track of the root activity of the task before we finish it
1146 TaskRecord tr = r.getTask();
1147 ActivityRecord rootR = tr.getRootActivity();
1148 if (rootR == null) {
1149 Slog.w(TAG, "Finishing task with all activities already finished");
1150 }
1151 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1152 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001153 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001154 return false;
1155 }
1156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001157 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1158 // We should consolidate.
1159 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001160 // Find the first activity that is not finishing.
1161 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1162 if (next != null) {
1163 // ask watcher if this is allowed
1164 boolean resumeOK = true;
1165 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001166 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001167 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001168 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001169 Watchdog.getInstance().setActivityController(null);
1170 }
1171
1172 if (!resumeOK) {
1173 Slog.i(TAG, "Not finishing activity because controller resumed");
1174 return false;
1175 }
1176 }
1177 }
1178 final long origId = Binder.clearCallingIdentity();
1179 try {
1180 boolean res;
1181 final boolean finishWithRootActivity =
1182 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1183 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1184 || (finishWithRootActivity && r == rootR)) {
1185 // If requested, remove the task that is associated to this activity only if it
1186 // was the root activity in the task. The result code and data is ignored
1187 // because we don't support returning them across task boundaries. Also, to
1188 // keep backwards compatibility we remove the task from recents when finishing
1189 // task with root activity.
1190 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1191 finishWithRootActivity, "finish-activity");
1192 if (!res) {
1193 Slog.i(TAG, "Removing task failed to finish activity");
1194 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001195 // Explicitly dismissing the activity so reset its relaunch flag.
1196 r.mRelaunchReason = ActivityRecord.RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001197 } else {
1198 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1199 resultData, "app-request", true);
1200 if (!res) {
1201 Slog.i(TAG, "Failed to finish by app-request");
1202 }
1203 }
1204 return res;
1205 } finally {
1206 Binder.restoreCallingIdentity(origId);
1207 }
1208 }
1209 }
1210
1211 @Override
1212 public boolean finishActivityAffinity(IBinder token) {
1213 synchronized (mGlobalLock) {
1214 final long origId = Binder.clearCallingIdentity();
1215 try {
1216 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1217 if (r == null) {
1218 return false;
1219 }
1220
1221 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1222 // can finish.
1223 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001224 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 return false;
1226 }
1227 return task.getStack().finishActivityAffinityLocked(r);
1228 } finally {
1229 Binder.restoreCallingIdentity(origId);
1230 }
1231 }
1232 }
1233
1234 @Override
1235 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1236 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001237 try {
1238 WindowProcessController proc = null;
1239 synchronized (mGlobalLock) {
1240 ActivityStack stack = ActivityRecord.getStackLocked(token);
1241 if (stack == null) {
1242 return;
1243 }
1244 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1245 false /* fromTimeout */, false /* processPausingActivities */, config);
1246 if (r != null) {
1247 proc = r.app;
1248 }
1249 if (stopProfiling && proc != null) {
1250 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001251 }
1252 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001253 } finally {
1254 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001256 }
1257
1258 @Override
1259 public final void activityResumed(IBinder token) {
1260 final long origId = Binder.clearCallingIdentity();
1261 synchronized (mGlobalLock) {
1262 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001263 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 }
1265 Binder.restoreCallingIdentity(origId);
1266 }
1267
1268 @Override
1269 public final void activityPaused(IBinder token) {
1270 final long origId = Binder.clearCallingIdentity();
1271 synchronized (mGlobalLock) {
1272 ActivityStack stack = ActivityRecord.getStackLocked(token);
1273 if (stack != null) {
1274 stack.activityPausedLocked(token, false);
1275 }
1276 }
1277 Binder.restoreCallingIdentity(origId);
1278 }
1279
1280 @Override
1281 public final void activityStopped(IBinder token, Bundle icicle,
1282 PersistableBundle persistentState, CharSequence description) {
1283 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1284
1285 // Refuse possible leaked file descriptors
1286 if (icicle != null && icicle.hasFileDescriptors()) {
1287 throw new IllegalArgumentException("File descriptors passed in Bundle");
1288 }
1289
1290 final long origId = Binder.clearCallingIdentity();
1291
1292 synchronized (mGlobalLock) {
1293 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1294 if (r != null) {
1295 r.activityStoppedLocked(icicle, persistentState, description);
1296 }
1297 }
1298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001299 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001300
1301 Binder.restoreCallingIdentity(origId);
1302 }
1303
1304 @Override
1305 public final void activityDestroyed(IBinder token) {
1306 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1307 synchronized (mGlobalLock) {
1308 ActivityStack stack = ActivityRecord.getStackLocked(token);
1309 if (stack != null) {
1310 stack.activityDestroyedLocked(token, "activityDestroyed");
1311 }
1312 }
1313 }
1314
1315 @Override
1316 public final void activityRelaunched(IBinder token) {
1317 final long origId = Binder.clearCallingIdentity();
1318 synchronized (mGlobalLock) {
1319 mStackSupervisor.activityRelaunchedLocked(token);
1320 }
1321 Binder.restoreCallingIdentity(origId);
1322 }
1323
1324 public final void activitySlept(IBinder token) {
1325 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1326
1327 final long origId = Binder.clearCallingIdentity();
1328
1329 synchronized (mGlobalLock) {
1330 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1331 if (r != null) {
1332 mStackSupervisor.activitySleptLocked(r);
1333 }
1334 }
1335
1336 Binder.restoreCallingIdentity(origId);
1337 }
1338
1339 @Override
1340 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1341 synchronized (mGlobalLock) {
1342 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1343 if (r == null) {
1344 return;
1345 }
1346 final long origId = Binder.clearCallingIdentity();
1347 try {
1348 r.setRequestedOrientation(requestedOrientation);
1349 } finally {
1350 Binder.restoreCallingIdentity(origId);
1351 }
1352 }
1353 }
1354
1355 @Override
1356 public int getRequestedOrientation(IBinder token) {
1357 synchronized (mGlobalLock) {
1358 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1359 if (r == null) {
1360 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1361 }
1362 return r.getRequestedOrientation();
1363 }
1364 }
1365
1366 @Override
1367 public void setImmersive(IBinder token, boolean immersive) {
1368 synchronized (mGlobalLock) {
1369 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1370 if (r == null) {
1371 throw new IllegalArgumentException();
1372 }
1373 r.immersive = immersive;
1374
1375 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001376 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001378 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 }
1380 }
1381 }
1382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 void applyUpdateLockStateLocked(ActivityRecord r) {
1384 // Modifications to the UpdateLock state are done on our handler, outside
1385 // the activity manager's locks. The new state is determined based on the
1386 // state *now* of the relevant activity record. The object is passed to
1387 // the handler solely for logging detail, not to be consulted/modified.
1388 final boolean nextState = r != null && r.immersive;
1389 mH.post(() -> {
1390 if (mUpdateLock.isHeld() != nextState) {
1391 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1392 "Applying new update lock state '" + nextState + "' for " + r);
1393 if (nextState) {
1394 mUpdateLock.acquire();
1395 } else {
1396 mUpdateLock.release();
1397 }
1398 }
1399 });
1400 }
1401
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 @Override
1403 public boolean isImmersive(IBinder token) {
1404 synchronized (mGlobalLock) {
1405 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1406 if (r == null) {
1407 throw new IllegalArgumentException();
1408 }
1409 return r.immersive;
1410 }
1411 }
1412
1413 @Override
1414 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001415 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001417 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 return (r != null) ? r.immersive : false;
1419 }
1420 }
1421
1422 @Override
1423 public void overridePendingTransition(IBinder token, String packageName,
1424 int enterAnim, int exitAnim) {
1425 synchronized (mGlobalLock) {
1426 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1427 if (self == null) {
1428 return;
1429 }
1430
1431 final long origId = Binder.clearCallingIdentity();
1432
1433 if (self.isState(
1434 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 mWindowManager.overridePendingAppTransition(packageName,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 enterAnim, exitAnim, null);
1437 }
1438
1439 Binder.restoreCallingIdentity(origId);
1440 }
1441 }
1442
1443 @Override
1444 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001445 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
1446 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001448 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 if (r == null) {
1450 return ActivityManager.COMPAT_MODE_UNKNOWN;
1451 }
1452 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454
1455 return mAmInternal.getPackageScreenCompatMode(ai);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 }
1457
1458 @Override
1459 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001460 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001461 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001462 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001464 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 if (r == null) {
1466 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1467 return;
1468 }
1469 ai = r.info.applicationInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001470 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001471
1472 mAmInternal.setPackageScreenCompatMode(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 }
1474
1475 @Override
1476 public int getLaunchedFromUid(IBinder activityToken) {
1477 ActivityRecord srec;
1478 synchronized (mGlobalLock) {
1479 srec = ActivityRecord.forTokenLocked(activityToken);
1480 }
1481 if (srec == null) {
1482 return -1;
1483 }
1484 return srec.launchedFromUid;
1485 }
1486
1487 @Override
1488 public String getLaunchedFromPackage(IBinder activityToken) {
1489 ActivityRecord srec;
1490 synchronized (mGlobalLock) {
1491 srec = ActivityRecord.forTokenLocked(activityToken);
1492 }
1493 if (srec == null) {
1494 return null;
1495 }
1496 return srec.launchedFromPackage;
1497 }
1498
1499 @Override
1500 public boolean convertFromTranslucent(IBinder token) {
1501 final long origId = Binder.clearCallingIdentity();
1502 try {
1503 synchronized (mGlobalLock) {
1504 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1505 if (r == null) {
1506 return false;
1507 }
1508 final boolean translucentChanged = r.changeWindowTranslucency(true);
1509 if (translucentChanged) {
1510 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1511 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 return translucentChanged;
1514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(origId);
1517 }
1518 }
1519
1520 @Override
1521 public boolean convertToTranslucent(IBinder token, Bundle options) {
1522 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1523 final long origId = Binder.clearCallingIdentity();
1524 try {
1525 synchronized (mGlobalLock) {
1526 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1527 if (r == null) {
1528 return false;
1529 }
1530 final TaskRecord task = r.getTask();
1531 int index = task.mActivities.lastIndexOf(r);
1532 if (index > 0) {
1533 ActivityRecord under = task.mActivities.get(index - 1);
1534 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1535 }
1536 final boolean translucentChanged = r.changeWindowTranslucency(false);
1537 if (translucentChanged) {
1538 r.getStack().convertActivityToTranslucent(r);
1539 }
1540 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001541 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 return translucentChanged;
1543 }
1544 } finally {
1545 Binder.restoreCallingIdentity(origId);
1546 }
1547 }
1548
1549 @Override
1550 public void notifyActivityDrawn(IBinder token) {
1551 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1552 synchronized (mGlobalLock) {
1553 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1554 if (r != null) {
1555 r.getStack().notifyActivityDrawnLocked(r);
1556 }
1557 }
1558 }
1559
1560 @Override
1561 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1562 synchronized (mGlobalLock) {
1563 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1564 if (r == null) {
1565 return;
1566 }
1567 r.reportFullyDrawnLocked(restoredFromBundle);
1568 }
1569 }
1570
1571 @Override
1572 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1573 synchronized (mGlobalLock) {
1574 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1575 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1576 return stack.mDisplayId;
1577 }
1578 return DEFAULT_DISPLAY;
1579 }
1580 }
1581
1582 @Override
1583 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001584 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 long ident = Binder.clearCallingIdentity();
1586 try {
1587 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001588 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 if (focusedStack != null) {
1590 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1591 }
1592 return null;
1593 }
1594 } finally {
1595 Binder.restoreCallingIdentity(ident);
1596 }
1597 }
1598
1599 @Override
1600 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001601 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1603 final long callingId = Binder.clearCallingIdentity();
1604 try {
1605 synchronized (mGlobalLock) {
1606 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1607 if (stack == null) {
1608 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1609 return;
1610 }
1611 final ActivityRecord r = stack.topRunningActivityLocked();
1612 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
1613 r, "setFocusedStack")) {
1614 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1615 }
1616 }
1617 } finally {
1618 Binder.restoreCallingIdentity(callingId);
1619 }
1620 }
1621
1622 @Override
1623 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001624 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1626 final long callingId = Binder.clearCallingIdentity();
1627 try {
1628 synchronized (mGlobalLock) {
1629 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1630 if (task == null) {
1631 return;
1632 }
1633 final ActivityRecord r = task.topRunningActivityLocked();
1634 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(r, "setFocusedTask")) {
1635 mStackSupervisor.resumeFocusedStackTopActivityLocked();
1636 }
1637 }
1638 } finally {
1639 Binder.restoreCallingIdentity(callingId);
1640 }
1641 }
1642
1643 @Override
1644 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001645 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 synchronized (mGlobalLock) {
1647 final long ident = Binder.clearCallingIdentity();
1648 try {
1649 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1650 "remove-task");
1651 } finally {
1652 Binder.restoreCallingIdentity(ident);
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1659 synchronized (mGlobalLock) {
1660 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1661 if (srec != null) {
1662 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1663 }
1664 }
1665 return false;
1666 }
1667
1668 @Override
1669 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1670 Intent resultData) {
1671
1672 synchronized (mGlobalLock) {
1673 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1674 if (r != null) {
1675 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1676 }
1677 return false;
1678 }
1679 }
1680
1681 /**
1682 * Attempts to move a task backwards in z-order (the order of activities within the task is
1683 * unchanged).
1684 *
1685 * There are several possible results of this call:
1686 * - if the task is locked, then we will show the lock toast
1687 * - if there is a task behind the provided task, then that task is made visible and resumed as
1688 * this task is moved to the back
1689 * - otherwise, if there are no other tasks in the stack:
1690 * - if this task is in the pinned stack, then we remove the stack completely, which will
1691 * have the effect of moving the task to the top or bottom of the fullscreen stack
1692 * (depending on whether it is visible)
1693 * - otherwise, we simply return home and hide this task
1694 *
1695 * @param token A reference to the activity we wish to move
1696 * @param nonRoot If false then this only works if the activity is the root
1697 * of a task; if true it will work for any activity in a task.
1698 * @return Returns true if the move completed, false if not.
1699 */
1700 @Override
1701 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001702 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 synchronized (mGlobalLock) {
1704 final long origId = Binder.clearCallingIdentity();
1705 try {
1706 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1707 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1708 if (task != null) {
1709 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1710 }
1711 } finally {
1712 Binder.restoreCallingIdentity(origId);
1713 }
1714 }
1715 return false;
1716 }
1717
1718 @Override
1719 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001720 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 long ident = Binder.clearCallingIdentity();
1722 Rect rect = new Rect();
1723 try {
1724 synchronized (mGlobalLock) {
1725 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1726 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1727 if (task == null) {
1728 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1729 return rect;
1730 }
1731 if (task.getStack() != null) {
1732 // Return the bounds from window manager since it will be adjusted for various
1733 // things like the presense of a docked stack for tasks that aren't resizeable.
1734 task.getWindowContainerBounds(rect);
1735 } else {
1736 // Task isn't in window manager yet since it isn't associated with a stack.
1737 // Return the persist value from activity manager
1738 if (!task.matchParentBounds()) {
1739 rect.set(task.getBounds());
1740 } else if (task.mLastNonFullscreenBounds != null) {
1741 rect.set(task.mLastNonFullscreenBounds);
1742 }
1743 }
1744 }
1745 } finally {
1746 Binder.restoreCallingIdentity(ident);
1747 }
1748 return rect;
1749 }
1750
1751 @Override
1752 public ActivityManager.TaskDescription getTaskDescription(int id) {
1753 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001754 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1756 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1757 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1758 if (tr != null) {
1759 return tr.lastTaskDescription;
1760 }
1761 }
1762 return null;
1763 }
1764
1765 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001766 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1767 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1768 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1769 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1770 return;
1771 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001773 synchronized (mGlobalLock) {
1774 final long ident = Binder.clearCallingIdentity();
1775 try {
1776 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1777 if (task == null) {
1778 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
1779 return;
1780 }
1781
1782 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
1783 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
1784
1785 if (!task.isActivityTypeStandardOrUndefined()) {
1786 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
1787 + " non-standard task " + taskId + " to windowing mode="
1788 + windowingMode);
1789 }
1790
1791 final ActivityStack stack = task.getStack();
1792 if (toTop) {
1793 stack.moveToFront("setTaskWindowingMode", task);
1794 }
1795 stack.setWindowingMode(windowingMode);
1796 } finally {
1797 Binder.restoreCallingIdentity(ident);
1798 }
1799 }
1800 }
1801
1802 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 ActivityRecord r = getCallingRecordLocked(token);
1806 return r != null ? r.info.packageName : null;
1807 }
1808 }
1809
1810 @Override
1811 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001812 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001813 ActivityRecord r = getCallingRecordLocked(token);
1814 return r != null ? r.intent.getComponent() : null;
1815 }
1816 }
1817
1818 private ActivityRecord getCallingRecordLocked(IBinder token) {
1819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r == null) {
1821 return null;
1822 }
1823 return r.resultTo;
1824 }
1825
1826 @Override
1827 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001828 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001829
1830 synchronized (mGlobalLock) {
1831 final long origId = Binder.clearCallingIdentity();
1832 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001833 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 } finally {
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837 }
1838 }
1839
1840 /**
1841 * TODO: Add mController hook
1842 */
1843 @Override
1844 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001845 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846
1847 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
1848 synchronized (mGlobalLock) {
1849 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
1850 false /* fromRecents */);
1851 }
1852 }
1853
1854 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
1855 boolean fromRecents) {
1856
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 Binder.getCallingUid(), -1, -1, "Task to front")) {
1859 SafeActivityOptions.abort(options);
1860 return;
1861 }
1862 final long origId = Binder.clearCallingIdentity();
1863 try {
1864 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1865 if (task == null) {
1866 Slog.d(TAG, "Could not find task for id: "+ taskId);
1867 return;
1868 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001869 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
1871 return;
1872 }
1873 ActivityOptions realOptions = options != null
1874 ? options.getOptions(mStackSupervisor)
1875 : null;
1876 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
1877 false /* forceNonResizable */);
1878
1879 final ActivityRecord topActivity = task.getTopActivity();
1880 if (topActivity != null) {
1881
1882 // We are reshowing a task, use a starting window to hide the initial draw delay
1883 // so the transition can start earlier.
1884 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
1885 true /* taskSwitch */, fromRecents);
1886 }
1887 } finally {
1888 Binder.restoreCallingIdentity(origId);
1889 }
1890 SafeActivityOptions.abort(options);
1891 }
1892
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001893 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
1894 int callingPid, int callingUid, String name) {
1895 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
1896 return true;
1897 }
1898
1899 if (getRecentTasks().isCallerRecents(sourceUid)) {
1900 return true;
1901 }
1902
1903 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
1904 if (perm == PackageManager.PERMISSION_GRANTED) {
1905 return true;
1906 }
1907 if (checkAllowAppSwitchUid(sourceUid)) {
1908 return true;
1909 }
1910
1911 // If the actual IPC caller is different from the logical source, then
1912 // also see if they are allowed to control app switches.
1913 if (callingUid != -1 && callingUid != sourceUid) {
1914 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
1915 if (perm == PackageManager.PERMISSION_GRANTED) {
1916 return true;
1917 }
1918 if (checkAllowAppSwitchUid(callingUid)) {
1919 return true;
1920 }
1921 }
1922
1923 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
1924 return false;
1925 }
1926
1927 private boolean checkAllowAppSwitchUid(int uid) {
1928 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
1929 if (types != null) {
1930 for (int i = types.size() - 1; i >= 0; i--) {
1931 if (types.valueAt(i).intValue() == uid) {
1932 return true;
1933 }
1934 }
1935 }
1936 return false;
1937 }
1938
1939 @Override
1940 public void setActivityController(IActivityController controller, boolean imAMonkey) {
1941 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
1942 "setActivityController()");
1943 synchronized (mGlobalLock) {
1944 mController = controller;
1945 mControllerIsAMonkey = imAMonkey;
1946 Watchdog.getInstance().setActivityController(controller);
1947 }
1948 }
1949
1950 boolean isControllerAMonkey() {
1951 synchronized (mGlobalLock) {
1952 return mController != null && mControllerIsAMonkey;
1953 }
1954 }
1955
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 @Override
1957 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
1958 synchronized (mGlobalLock) {
1959 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
1960 }
1961 }
1962
1963 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001964 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
1965 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
1966 }
1967
1968 @Override
1969 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
1970 @WindowConfiguration.ActivityType int ignoreActivityType,
1971 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
1972 final int callingUid = Binder.getCallingUid();
1973 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
1974
1975 synchronized (mGlobalLock) {
1976 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
1977
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001978 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001979 callingUid);
1980 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
1981 ignoreWindowingMode, callingUid, allowed);
1982 }
1983
1984 return list;
1985 }
1986
1987 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
1989 synchronized (mGlobalLock) {
1990 final long origId = Binder.clearCallingIdentity();
1991 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1992 if (r != null) {
1993 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
1994 }
1995 Binder.restoreCallingIdentity(origId);
1996 }
1997 }
1998
1999 @Override
2000 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002001 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 ActivityStack stack = ActivityRecord.getStackLocked(token);
2003 if (stack != null) {
2004 return stack.willActivityBeVisibleLocked(token);
2005 }
2006 return false;
2007 }
2008 }
2009
2010 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002011 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002013 synchronized (mGlobalLock) {
2014 final long ident = Binder.clearCallingIdentity();
2015 try {
2016 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2017 if (task == null) {
2018 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2019 return;
2020 }
2021
2022 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2023 + " to stackId=" + stackId + " toTop=" + toTop);
2024
2025 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2026 if (stack == null) {
2027 throw new IllegalStateException(
2028 "moveTaskToStack: No stack for stackId=" + stackId);
2029 }
2030 if (!stack.isActivityTypeStandardOrUndefined()) {
2031 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2032 + taskId + " to stack " + stackId);
2033 }
2034 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002035 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002036 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2037 }
2038 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2039 "moveTaskToStack");
2040 } finally {
2041 Binder.restoreCallingIdentity(ident);
2042 }
2043 }
2044 }
2045
2046 @Override
2047 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2048 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002049 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002050
2051 final long ident = Binder.clearCallingIdentity();
2052 try {
2053 synchronized (mGlobalLock) {
2054 if (animate) {
2055 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2056 if (stack == null) {
2057 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2058 return;
2059 }
2060 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2061 throw new IllegalArgumentException("Stack: " + stackId
2062 + " doesn't support animated resize.");
2063 }
2064 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2065 animationDuration, false /* fromFullscreen */);
2066 } else {
2067 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2068 if (stack == null) {
2069 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2070 return;
2071 }
2072 mStackSupervisor.resizeStackLocked(stack, destBounds,
2073 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2074 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(ident);
2079 }
2080 }
2081
2082 /**
2083 * Moves the specified task to the primary-split-screen stack.
2084 *
2085 * @param taskId Id of task to move.
2086 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2087 * exist already. See
2088 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2089 * and
2090 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2091 * @param toTop If the task and stack should be moved to the top.
2092 * @param animate Whether we should play an animation for the moving the task.
2093 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2094 * stack. Pass {@code null} to use default bounds.
2095 * @param showRecents If the recents activity should be shown on the other side of the task
2096 * going into split-screen mode.
2097 */
2098 @Override
2099 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2100 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002101 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002102 "setTaskWindowingModeSplitScreenPrimary()");
2103 synchronized (mGlobalLock) {
2104 final long ident = Binder.clearCallingIdentity();
2105 try {
2106 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2107 if (task == null) {
2108 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2109 return false;
2110 }
2111 if (DEBUG_STACK) Slog.d(TAG_STACK,
2112 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2113 + " to createMode=" + createMode + " toTop=" + toTop);
2114 if (!task.isActivityTypeStandardOrUndefined()) {
2115 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2116 + " non-standard task " + taskId + " to split-screen windowing mode");
2117 }
2118
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002119 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002120 final int windowingMode = task.getWindowingMode();
2121 final ActivityStack stack = task.getStack();
2122 if (toTop) {
2123 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2124 }
2125 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2126 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2127 return windowingMode != task.getWindowingMode();
2128 } finally {
2129 Binder.restoreCallingIdentity(ident);
2130 }
2131 }
2132 }
2133
2134 /**
2135 * Removes stacks in the input windowing modes from the system if they are of activity type
2136 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2137 */
2138 @Override
2139 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002140 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002141 "removeStacksInWindowingModes()");
2142
2143 synchronized (mGlobalLock) {
2144 final long ident = Binder.clearCallingIdentity();
2145 try {
2146 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2147 } finally {
2148 Binder.restoreCallingIdentity(ident);
2149 }
2150 }
2151 }
2152
2153 @Override
2154 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002155 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002156 "removeStacksWithActivityTypes()");
2157
2158 synchronized (mGlobalLock) {
2159 final long ident = Binder.clearCallingIdentity();
2160 try {
2161 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2162 } finally {
2163 Binder.restoreCallingIdentity(ident);
2164 }
2165 }
2166 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167
2168 @Override
2169 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2170 int userId) {
2171 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002172 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2173 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002175 final boolean detailed = checkGetTasksPermission(
2176 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2177 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 == PackageManager.PERMISSION_GRANTED;
2179
2180 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002181 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 callingUid);
2183 }
2184 }
2185
2186 @Override
2187 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002188 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 long ident = Binder.clearCallingIdentity();
2190 try {
2191 synchronized (mGlobalLock) {
2192 return mStackSupervisor.getAllStackInfosLocked();
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(ident);
2196 }
2197 }
2198
2199 @Override
2200 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002201 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 long ident = Binder.clearCallingIdentity();
2203 try {
2204 synchronized (mGlobalLock) {
2205 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2206 }
2207 } finally {
2208 Binder.restoreCallingIdentity(ident);
2209 }
2210 }
2211
2212 @Override
2213 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002214 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002215 final long callingUid = Binder.getCallingUid();
2216 final long origId = Binder.clearCallingIdentity();
2217 try {
2218 synchronized (mGlobalLock) {
2219 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002220 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2222 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2223 }
2224 } finally {
2225 Binder.restoreCallingIdentity(origId);
2226 }
2227 }
2228
2229 @Override
2230 public void startLockTaskModeByToken(IBinder token) {
2231 synchronized (mGlobalLock) {
2232 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2233 if (r == null) {
2234 return;
2235 }
2236 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2237 }
2238 }
2239
2240 @Override
2241 public void startSystemLockTaskMode(int taskId) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002242 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 // This makes inner call to look as if it was initiated by system.
2244 long ident = Binder.clearCallingIdentity();
2245 try {
2246 synchronized (mGlobalLock) {
2247 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2248
2249 // When starting lock task mode the stack must be in front and focused
2250 task.getStack().moveToFront("startSystemLockTaskMode");
2251 startLockTaskModeLocked(task, true /* isSystemCaller */);
2252 }
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
2256 }
2257
2258 @Override
2259 public void stopLockTaskModeByToken(IBinder token) {
2260 synchronized (mGlobalLock) {
2261 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2262 if (r == null) {
2263 return;
2264 }
2265 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2266 }
2267 }
2268
2269 /**
2270 * This API should be called by SystemUI only when user perform certain action to dismiss
2271 * lock task mode. We should only dismiss pinned lock task mode in this case.
2272 */
2273 @Override
2274 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002275 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002276 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2277 }
2278
2279 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2280 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2281 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2282 return;
2283 }
2284
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002285 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 if (stack == null || task != stack.topTask()) {
2287 throw new IllegalArgumentException("Invalid task, not in foreground");
2288 }
2289
2290 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2291 // system or a specific app.
2292 // * System-initiated requests will only start the pinned mode (screen pinning)
2293 // * App-initiated requests
2294 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2295 // - will start the pinned mode, otherwise
2296 final int callingUid = Binder.getCallingUid();
2297 long ident = Binder.clearCallingIdentity();
2298 try {
2299 // When a task is locked, dismiss the pinned stack if it exists
2300 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2301
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002302 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
2306 }
2307
2308 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2309 final int callingUid = Binder.getCallingUid();
2310 long ident = Binder.clearCallingIdentity();
2311 try {
2312 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002313 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314 }
2315 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2316 // task and jumping straight into a call in the case of emergency call back.
2317 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2318 if (tm != null) {
2319 tm.showInCallScreen(false);
2320 }
2321 } finally {
2322 Binder.restoreCallingIdentity(ident);
2323 }
2324 }
2325
2326 @Override
2327 public boolean isInLockTaskMode() {
2328 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2329 }
2330
2331 @Override
2332 public int getLockTaskModeState() {
2333 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002334 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335 }
2336 }
2337
2338 @Override
2339 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2340 synchronized (mGlobalLock) {
2341 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2342 if (r != null) {
2343 r.setTaskDescription(td);
2344 final TaskRecord task = r.getTask();
2345 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002346 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 }
2348 }
2349 }
2350
2351 @Override
2352 public Bundle getActivityOptions(IBinder token) {
2353 final long origId = Binder.clearCallingIdentity();
2354 try {
2355 synchronized (mGlobalLock) {
2356 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2357 if (r != null) {
2358 final ActivityOptions activityOptions = r.takeOptionsLocked();
2359 return activityOptions == null ? null : activityOptions.toBundle();
2360 }
2361 return null;
2362 }
2363 } finally {
2364 Binder.restoreCallingIdentity(origId);
2365 }
2366 }
2367
2368 @Override
2369 public List<IBinder> getAppTasks(String callingPackage) {
2370 int callingUid = Binder.getCallingUid();
2371 long ident = Binder.clearCallingIdentity();
2372 try {
2373 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002374 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 }
2376 } finally {
2377 Binder.restoreCallingIdentity(ident);
2378 }
2379 }
2380
2381 @Override
2382 public void finishVoiceTask(IVoiceInteractionSession session) {
2383 synchronized (mGlobalLock) {
2384 final long origId = Binder.clearCallingIdentity();
2385 try {
2386 // TODO: VI Consider treating local voice interactions and voice tasks
2387 // differently here
2388 mStackSupervisor.finishVoiceTask(session);
2389 } finally {
2390 Binder.restoreCallingIdentity(origId);
2391 }
2392 }
2393
2394 }
2395
2396 @Override
2397 public boolean isTopOfTask(IBinder token) {
2398 synchronized (mGlobalLock) {
2399 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2400 if (r == null) {
2401 throw new IllegalArgumentException();
2402 }
2403 return r.getTask().getTopActivity() == r;
2404 }
2405 }
2406
2407 @Override
2408 public void notifyLaunchTaskBehindComplete(IBinder token) {
2409 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2410 }
2411
2412 @Override
2413 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002414 mH.post(() -> {
2415 synchronized (mGlobalLock) {
2416 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002417 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002418 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002419 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002420 } catch (RemoteException e) {
2421 }
2422 }
2423 }
2424
2425 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426 }
2427
2428 /** Called from an app when assist data is ready. */
2429 @Override
2430 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2431 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002432 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 synchronized (pae) {
2434 pae.result = extras;
2435 pae.structure = structure;
2436 pae.content = content;
2437 if (referrer != null) {
2438 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2439 }
2440 if (structure != null) {
2441 structure.setHomeActivity(pae.isHome);
2442 }
2443 pae.haveResult = true;
2444 pae.notifyAll();
2445 if (pae.intent == null && pae.receiver == null) {
2446 // Caller is just waiting for the result.
2447 return;
2448 }
2449 }
2450 // We are now ready to launch the assist activity.
2451 IAssistDataReceiver sendReceiver = null;
2452 Bundle sendBundle = null;
2453 synchronized (mGlobalLock) {
2454 buildAssistBundleLocked(pae, extras);
2455 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002457 if (!exists) {
2458 // Timed out.
2459 return;
2460 }
2461
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002462 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002463 // Caller wants result sent back to them.
2464 sendBundle = new Bundle();
2465 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2466 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2467 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2468 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2469 }
2470 }
2471 if (sendReceiver != null) {
2472 try {
2473 sendReceiver.onHandleAssistData(sendBundle);
2474 } catch (RemoteException e) {
2475 }
2476 return;
2477 }
2478
2479 final long ident = Binder.clearCallingIdentity();
2480 try {
2481 if (TextUtils.equals(pae.intent.getAction(),
2482 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2483 pae.intent.putExtras(pae.extras);
2484 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2485 } else {
2486 pae.intent.replaceExtras(pae.extras);
2487 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2488 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2489 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002490 mAmInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002491
2492 try {
2493 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2494 } catch (ActivityNotFoundException e) {
2495 Slog.w(TAG, "No activity to handle assist action.", e);
2496 }
2497 }
2498 } finally {
2499 Binder.restoreCallingIdentity(ident);
2500 }
2501 }
2502
2503 @Override
2504 public int addAppTask(IBinder activityToken, Intent intent,
2505 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2506 final int callingUid = Binder.getCallingUid();
2507 final long callingIdent = Binder.clearCallingIdentity();
2508
2509 try {
2510 synchronized (mGlobalLock) {
2511 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2512 if (r == null) {
2513 throw new IllegalArgumentException("Activity does not exist; token="
2514 + activityToken);
2515 }
2516 ComponentName comp = intent.getComponent();
2517 if (comp == null) {
2518 throw new IllegalArgumentException("Intent " + intent
2519 + " must specify explicit component");
2520 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002521 if (thumbnail.getWidth() != mThumbnailWidth
2522 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523 throw new IllegalArgumentException("Bad thumbnail size: got "
2524 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002525 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002526 }
2527 if (intent.getSelector() != null) {
2528 intent.setSelector(null);
2529 }
2530 if (intent.getSourceBounds() != null) {
2531 intent.setSourceBounds(null);
2532 }
2533 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2534 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2535 // The caller has added this as an auto-remove task... that makes no
2536 // sense, so turn off auto-remove.
2537 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2538 }
2539 }
2540 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2541 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2542 if (ainfo.applicationInfo.uid != callingUid) {
2543 throw new SecurityException(
2544 "Can't add task for another application: target uid="
2545 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2546 }
2547
2548 final ActivityStack stack = r.getStack();
2549 final TaskRecord task = stack.createTaskRecord(
2550 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2551 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002552 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002553 // The app has too many tasks already and we can't add any more
2554 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2555 return INVALID_TASK_ID;
2556 }
2557 task.lastTaskDescription.copyFrom(description);
2558
2559 // TODO: Send the thumbnail to WM to store it.
2560
2561 return task.taskId;
2562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(callingIdent);
2565 }
2566 }
2567
2568 @Override
2569 public Point getAppTaskThumbnailSize() {
2570 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002572 }
2573 }
2574
2575 @Override
2576 public void setTaskResizeable(int taskId, int resizeableMode) {
2577 synchronized (mGlobalLock) {
2578 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2579 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2580 if (task == null) {
2581 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2582 return;
2583 }
2584 task.setResizeMode(resizeableMode);
2585 }
2586 }
2587
2588 @Override
2589 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002590 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
2594 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2595 if (task == null) {
2596 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2597 return;
2598 }
2599 // Place the task in the right stack if it isn't there already based on
2600 // the requested bounds.
2601 // The stack transition logic is:
2602 // - a null bounds on a freeform task moves that task to fullscreen
2603 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2604 // that task to freeform
2605 // - otherwise the task is not moved
2606 ActivityStack stack = task.getStack();
2607 if (!task.getWindowConfiguration().canResizeTask()) {
2608 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2609 }
2610 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2611 stack = stack.getDisplay().getOrCreateStack(
2612 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2613 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2614 stack = stack.getDisplay().getOrCreateStack(
2615 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2616 }
2617
2618 // Reparent the task to the right stack if necessary
2619 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2620 if (stack != task.getStack()) {
2621 // Defer resume until the task is resized below
2622 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2623 DEFER_RESUME, "resizeTask");
2624 preserveWindow = false;
2625 }
2626
2627 // After reparenting (which only resizes the task to the stack bounds), resize the
2628 // task to the actual bounds provided
2629 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2630 }
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
2634 }
2635
2636 @Override
2637 public boolean releaseActivityInstance(IBinder token) {
2638 synchronized (mGlobalLock) {
2639 final long origId = Binder.clearCallingIdentity();
2640 try {
2641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2642 if (r == null) {
2643 return false;
2644 }
2645 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2646 } finally {
2647 Binder.restoreCallingIdentity(origId);
2648 }
2649 }
2650 }
2651
2652 @Override
2653 public void releaseSomeActivities(IApplicationThread appInt) {
2654 synchronized (mGlobalLock) {
2655 final long origId = Binder.clearCallingIdentity();
2656 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002657 WindowProcessController app =
2658 mAm.getRecordForAppLocked(appInt).getWindowProcessController();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002659 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2660 } finally {
2661 Binder.restoreCallingIdentity(origId);
2662 }
2663 }
2664 }
2665
2666 @Override
2667 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
2668 int secondaryDisplayShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002669 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002670 != PackageManager.PERMISSION_GRANTED) {
2671 throw new SecurityException("Requires permission "
2672 + android.Manifest.permission.DEVICE_POWER);
2673 }
2674
2675 synchronized (mGlobalLock) {
2676 long ident = Binder.clearCallingIdentity();
2677 if (mKeyguardShown != keyguardShowing) {
2678 mKeyguardShown = keyguardShowing;
2679 reportCurKeyguardUsageEventLocked(keyguardShowing);
2680 }
2681 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002682 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002683 secondaryDisplayShowing);
2684 } finally {
2685 Binder.restoreCallingIdentity(ident);
2686 }
2687 }
2688
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002689 mH.post(() -> {
2690 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2691 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2692 }
2693 });
2694 }
2695
2696 void onScreenAwakeChanged(boolean isAwake) {
2697 mH.post(() -> {
2698 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2699 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2700 }
2701 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 }
2703
2704 @Override
2705 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002706 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2707 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002708
2709 final File passedIconFile = new File(filePath);
2710 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2711 passedIconFile.getName());
2712 if (!legitIconFile.getPath().equals(filePath)
2713 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2714 throw new IllegalArgumentException("Bad file path: " + filePath
2715 + " passed for userId " + userId);
2716 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002717 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002718 }
2719
2720 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002721 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002722 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2723 final ActivityOptions activityOptions = safeOptions != null
2724 ? safeOptions.getOptions(mStackSupervisor)
2725 : null;
2726 if (activityOptions == null
2727 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2728 || activityOptions.getCustomInPlaceResId() == 0) {
2729 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2730 "with valid animation");
2731 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002732 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2733 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734 activityOptions.getCustomInPlaceResId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002735 mWindowManager.executeAppTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002736 }
2737
2738 @Override
2739 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741 synchronized (mGlobalLock) {
2742 final long ident = Binder.clearCallingIdentity();
2743 try {
2744 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2745 if (stack == null) {
2746 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2747 return;
2748 }
2749 if (!stack.isActivityTypeStandardOrUndefined()) {
2750 throw new IllegalArgumentException(
2751 "Removing non-standard stack is not allowed.");
2752 }
2753 mStackSupervisor.removeStack(stack);
2754 } finally {
2755 Binder.restoreCallingIdentity(ident);
2756 }
2757 }
2758 }
2759
2760 @Override
2761 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763
2764 synchronized (mGlobalLock) {
2765 final long ident = Binder.clearCallingIdentity();
2766 try {
2767 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2768 + " to displayId=" + displayId);
2769 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2770 } finally {
2771 Binder.restoreCallingIdentity(ident);
2772 }
2773 }
2774 }
2775
2776 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 public void exitFreeformMode(IBinder token) {
2778 synchronized (mGlobalLock) {
2779 long ident = Binder.clearCallingIdentity();
2780 try {
2781 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2782 if (r == null) {
2783 throw new IllegalArgumentException(
2784 "exitFreeformMode: No activity record matching token=" + token);
2785 }
2786
2787 final ActivityStack stack = r.getStack();
2788 if (stack == null || !stack.inFreeformWindowingMode()) {
2789 throw new IllegalStateException(
2790 "exitFreeformMode: You can only go fullscreen from freeform.");
2791 }
2792
2793 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
2794 } finally {
2795 Binder.restoreCallingIdentity(ident);
2796 }
2797 }
2798 }
2799
2800 /** Sets the task stack listener that gets callbacks when a task stack changes. */
2801 @Override
2802 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002805 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 }
2807
2808 /** Unregister a task stack listener so that it stops receiving callbacks. */
2809 @Override
2810 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002811 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002813 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 }
2815
2816 private void reportCurKeyguardUsageEventLocked(boolean keyguardShowing) {
2817 mAm.reportGlobalUsageEventLocked(keyguardShowing
2818 ? UsageEvents.Event.KEYGUARD_SHOWN
2819 : UsageEvents.Event.KEYGUARD_HIDDEN);
2820 }
2821
2822 @Override
2823 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
2824 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
2825 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
2826 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
2827 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
2828 }
2829
2830 @Override
2831 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
2832 IBinder activityToken, int flags) {
2833 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
2834 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
2835 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
2836 }
2837
2838 @Override
2839 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
2840 Bundle args) {
2841 return enqueueAssistContext(requestType, intent, hint, null, null, null,
2842 true /* focused */, true /* newSessionId */, userHandle, args,
2843 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
2844 }
2845
2846 @Override
2847 public Bundle getAssistContextExtras(int requestType) {
2848 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
2849 null, null, true /* focused */, true /* newSessionId */,
2850 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
2851 if (pae == null) {
2852 return null;
2853 }
2854 synchronized (pae) {
2855 while (!pae.haveResult) {
2856 try {
2857 pae.wait();
2858 } catch (InterruptedException e) {
2859 }
2860 }
2861 }
2862 synchronized (mGlobalLock) {
2863 buildAssistBundleLocked(pae, pae.result);
2864 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002865 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 }
2867 return pae.extras;
2868 }
2869
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002870 /**
2871 * Binder IPC calls go through the public entry point.
2872 * This can be called with or without the global lock held.
2873 */
2874 private static int checkCallingPermission(String permission) {
2875 return checkPermission(
2876 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
2877 }
2878
2879 /** This can be called with or without the global lock held. */
2880 void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
2881 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
2882 mAmInternal.enforceCallingPermission(permission, func);
2883 }
2884 }
2885
2886 @VisibleForTesting
2887 int checkGetTasksPermission(String permission, int pid, int uid) {
2888 return checkPermission(permission, pid, uid);
2889 }
2890
2891 static int checkPermission(String permission, int pid, int uid) {
2892 if (permission == null) {
2893 return PackageManager.PERMISSION_DENIED;
2894 }
2895 return checkComponentPermission(permission, pid, uid, -1, true);
2896 }
2897
2898 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
2899 if (getRecentTasks().isCallerRecents(callingUid)) {
2900 // Always allow the recents component to get tasks
2901 return true;
2902 }
2903
2904 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
2905 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2906 if (!allowed) {
2907 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
2908 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
2909 // Temporary compatibility: some existing apps on the system image may
2910 // still be requesting the old permission and not switched to the new
2911 // one; if so, we'll still allow them full access. This means we need
2912 // to see if they are holding the old permission and are a system app.
2913 try {
2914 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
2915 allowed = true;
2916 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2917 + " is using old GET_TASKS but privileged; allowing");
2918 }
2919 } catch (RemoteException e) {
2920 }
2921 }
2922 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
2923 + " does not hold REAL_GET_TASKS; limiting output");
2924 }
2925 return allowed;
2926 }
2927
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
2929 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
2930 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
2931 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002932 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933 "enqueueAssistContext()");
2934
2935 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002936 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 if (activity == null) {
2938 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
2939 return null;
2940 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002941 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
2943 return null;
2944 }
2945 if (focused) {
2946 if (activityToken != null) {
2947 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
2948 if (activity != caller) {
2949 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
2950 + " is not current top " + activity);
2951 return null;
2952 }
2953 }
2954 } else {
2955 activity = ActivityRecord.forTokenLocked(activityToken);
2956 if (activity == null) {
2957 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
2958 + " couldn't be found");
2959 return null;
2960 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002961 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002962 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
2963 return null;
2964 }
2965 }
2966
2967 PendingAssistExtras pae;
2968 Bundle extras = new Bundle();
2969 if (args != null) {
2970 extras.putAll(args);
2971 }
2972 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002973 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974
2975 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
2976 userHandle);
2977 pae.isHome = activity.isActivityTypeHome();
2978
2979 // Increment the sessionId if necessary
2980 if (newSessionId) {
2981 mViSessionId++;
2982 }
2983 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002984 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
2985 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002987 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 } catch (RemoteException e) {
2989 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
2990 return null;
2991 }
2992 return pae;
2993 }
2994 }
2995
2996 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
2997 if (result != null) {
2998 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
2999 }
3000 if (pae.hint != null) {
3001 pae.extras.putBoolean(pae.hint, true);
3002 }
3003 }
3004
3005 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3006 IAssistDataReceiver receiver;
3007 synchronized (mGlobalLock) {
3008 mPendingAssistExtras.remove(pae);
3009 receiver = pae.receiver;
3010 }
3011 if (receiver != null) {
3012 // Caller wants result sent back to them.
3013 Bundle sendBundle = new Bundle();
3014 // At least return the receiver extras
3015 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3016 try {
3017 pae.receiver.onHandleAssistData(sendBundle);
3018 } catch (RemoteException e) {
3019 }
3020 }
3021 }
3022
3023 public class PendingAssistExtras extends Binder implements Runnable {
3024 public final ActivityRecord activity;
3025 public boolean isHome;
3026 public final Bundle extras;
3027 public final Intent intent;
3028 public final String hint;
3029 public final IAssistDataReceiver receiver;
3030 public final int userHandle;
3031 public boolean haveResult = false;
3032 public Bundle result = null;
3033 public AssistStructure structure = null;
3034 public AssistContent content = null;
3035 public Bundle receiverExtras;
3036
3037 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3038 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3039 int _userHandle) {
3040 activity = _activity;
3041 extras = _extras;
3042 intent = _intent;
3043 hint = _hint;
3044 receiver = _receiver;
3045 receiverExtras = _receiverExtras;
3046 userHandle = _userHandle;
3047 }
3048
3049 @Override
3050 public void run() {
3051 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3052 synchronized (this) {
3053 haveResult = true;
3054 notifyAll();
3055 }
3056 pendingAssistExtrasTimedOut(this);
3057 }
3058 }
3059
3060 @Override
3061 public boolean isAssistDataAllowedOnCurrentActivity() {
3062 int userId;
3063 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003064 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3066 return false;
3067 }
3068
3069 final ActivityRecord activity = focusedStack.getTopActivity();
3070 if (activity == null) {
3071 return false;
3072 }
3073 userId = activity.userId;
3074 }
3075 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3076 }
3077
3078 @Override
3079 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3080 long ident = Binder.clearCallingIdentity();
3081 try {
3082 synchronized (mGlobalLock) {
3083 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003084 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 if (top != caller) {
3086 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3087 + " is not current top " + top);
3088 return false;
3089 }
3090 if (!top.nowVisible) {
3091 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3092 + " is not visible");
3093 return false;
3094 }
3095 }
3096 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3097 token);
3098 } finally {
3099 Binder.restoreCallingIdentity(ident);
3100 }
3101 }
3102
3103 @Override
3104 public boolean isRootVoiceInteraction(IBinder token) {
3105 synchronized (mGlobalLock) {
3106 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3107 if (r == null) {
3108 return false;
3109 }
3110 return r.rootVoiceInteraction;
3111 }
3112 }
3113
Wale Ogunwalef6733932018-06-27 05:14:34 -07003114 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3115 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3116 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3117 if (activityToCallback == null) return;
3118 activityToCallback.setVoiceSessionLocked(voiceSession);
3119
3120 // Inform the activity
3121 try {
3122 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3123 voiceInteractor);
3124 long token = Binder.clearCallingIdentity();
3125 try {
3126 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3127 } finally {
3128 Binder.restoreCallingIdentity(token);
3129 }
3130 // TODO: VI Should we cache the activity so that it's easier to find later
3131 // rather than scan through all the stacks and activities?
3132 } catch (RemoteException re) {
3133 activityToCallback.clearVoiceSessionLocked();
3134 // TODO: VI Should this terminate the voice session?
3135 }
3136 }
3137
3138 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3139 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3140 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3141 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3142 boolean wasRunningVoice = mRunningVoice != null;
3143 mRunningVoice = session;
3144 if (!wasRunningVoice) {
3145 mVoiceWakeLock.acquire();
3146 updateSleepIfNeededLocked();
3147 }
3148 }
3149 }
3150
3151 void finishRunningVoiceLocked() {
3152 if (mRunningVoice != null) {
3153 mRunningVoice = null;
3154 mVoiceWakeLock.release();
3155 updateSleepIfNeededLocked();
3156 }
3157 }
3158
3159 @Override
3160 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3161 synchronized (mGlobalLock) {
3162 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3163 if (keepAwake) {
3164 mVoiceWakeLock.acquire();
3165 } else {
3166 mVoiceWakeLock.release();
3167 }
3168 }
3169 }
3170 }
3171
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 @Override
3173 public ComponentName getActivityClassForToken(IBinder token) {
3174 synchronized (mGlobalLock) {
3175 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3176 if (r == null) {
3177 return null;
3178 }
3179 return r.intent.getComponent();
3180 }
3181 }
3182
3183 @Override
3184 public String getPackageForToken(IBinder token) {
3185 synchronized (mGlobalLock) {
3186 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3187 if (r == null) {
3188 return null;
3189 }
3190 return r.packageName;
3191 }
3192 }
3193
3194 @Override
3195 public void showLockTaskEscapeMessage(IBinder token) {
3196 synchronized (mGlobalLock) {
3197 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3198 if (r == null) {
3199 return;
3200 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003201 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 }
3203 }
3204
3205 @Override
3206 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003207 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 final long token = Binder.clearCallingIdentity();
3209 try {
3210 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003211 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 }
3213 } finally {
3214 Binder.restoreCallingIdentity(token);
3215 }
3216 }
3217
3218 /**
3219 * Try to place task to provided position. The final position might be different depending on
3220 * current user and stacks state. The task will be moved to target stack if it's currently in
3221 * different stack.
3222 */
3223 @Override
3224 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003225 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 synchronized (mGlobalLock) {
3227 long ident = Binder.clearCallingIdentity();
3228 try {
3229 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3230 + taskId + " in stackId=" + stackId + " at position=" + position);
3231 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3232 if (task == null) {
3233 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3234 + taskId);
3235 }
3236
3237 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3238
3239 if (stack == null) {
3240 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3241 + stackId);
3242 }
3243 if (!stack.isActivityTypeStandardOrUndefined()) {
3244 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3245 + " the position of task " + taskId + " in/to non-standard stack");
3246 }
3247
3248 // TODO: Have the callers of this API call a separate reparent method if that is
3249 // what they intended to do vs. having this method also do reparenting.
3250 if (task.getStack() == stack) {
3251 // Change position in current stack.
3252 stack.positionChildAt(task, position);
3253 } else {
3254 // Reparent to new stack.
3255 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3256 !DEFER_RESUME, "positionTaskInStack");
3257 }
3258 } finally {
3259 Binder.restoreCallingIdentity(ident);
3260 }
3261 }
3262 }
3263
3264 @Override
3265 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3266 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3267 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3268 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3269 synchronized (mGlobalLock) {
3270 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3271 if (record == null) {
3272 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3273 + "found for: " + token);
3274 }
3275 record.setSizeConfigurations(horizontalSizeConfiguration,
3276 verticalSizeConfigurations, smallestSizeConfigurations);
3277 }
3278 }
3279
3280 /**
3281 * Dismisses split-screen multi-window mode.
3282 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3283 */
3284 @Override
3285 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003286 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003287 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3288 final long ident = Binder.clearCallingIdentity();
3289 try {
3290 synchronized (mGlobalLock) {
3291 final ActivityStack stack =
3292 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3293 if (stack == null) {
3294 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3295 return;
3296 }
3297
3298 if (toTop) {
3299 // Caller wants the current split-screen primary stack to be the top stack after
3300 // it goes fullscreen, so move it to the front.
3301 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003302 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003303 // In this case the current split-screen primary stack shouldn't be the top
3304 // stack after it goes fullscreen, but it current has focus, so we move the
3305 // focus to the top-most split-screen secondary stack next to it.
3306 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3307 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3308 if (otherStack != null) {
3309 otherStack.moveToFront("dismissSplitScreenMode_other");
3310 }
3311 }
3312
3313 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3314 }
3315 } finally {
3316 Binder.restoreCallingIdentity(ident);
3317 }
3318 }
3319
3320 /**
3321 * Dismisses Pip
3322 * @param animate True if the dismissal should be animated.
3323 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3324 * default animation duration should be used.
3325 */
3326 @Override
3327 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003328 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 final long ident = Binder.clearCallingIdentity();
3330 try {
3331 synchronized (mGlobalLock) {
3332 final PinnedActivityStack stack =
3333 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3334 if (stack == null) {
3335 Slog.w(TAG, "dismissPip: pinned stack not found.");
3336 return;
3337 }
3338 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3339 throw new IllegalArgumentException("Stack: " + stack
3340 + " doesn't support animated resize.");
3341 }
3342 if (animate) {
3343 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3344 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3345 } else {
3346 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3347 }
3348 }
3349 } finally {
3350 Binder.restoreCallingIdentity(ident);
3351 }
3352 }
3353
3354 @Override
3355 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003356 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 synchronized (mGlobalLock) {
3358 mSuppressResizeConfigChanges = suppress;
3359 }
3360 }
3361
3362 /**
3363 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3364 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3365 * activity and clearing the task at the same time.
3366 */
3367 @Override
3368 // TODO: API should just be about changing windowing modes...
3369 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 "moveTasksToFullscreenStack()");
3372 synchronized (mGlobalLock) {
3373 final long origId = Binder.clearCallingIdentity();
3374 try {
3375 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3376 if (stack != null){
3377 if (!stack.isActivityTypeStandardOrUndefined()) {
3378 throw new IllegalArgumentException(
3379 "You can't move tasks from non-standard stacks.");
3380 }
3381 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3382 }
3383 } finally {
3384 Binder.restoreCallingIdentity(origId);
3385 }
3386 }
3387 }
3388
3389 /**
3390 * Moves the top activity in the input stackId to the pinned stack.
3391 *
3392 * @param stackId Id of stack to move the top activity to pinned stack.
3393 * @param bounds Bounds to use for pinned stack.
3394 *
3395 * @return True if the top activity of the input stack was successfully moved to the pinned
3396 * stack.
3397 */
3398 @Override
3399 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 "moveTopActivityToPinnedStack()");
3402 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003403 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3405 + "Device doesn't support picture-in-picture mode");
3406 }
3407
3408 long ident = Binder.clearCallingIdentity();
3409 try {
3410 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3411 } finally {
3412 Binder.restoreCallingIdentity(ident);
3413 }
3414 }
3415 }
3416
3417 @Override
3418 public boolean isInMultiWindowMode(IBinder token) {
3419 final long origId = Binder.clearCallingIdentity();
3420 try {
3421 synchronized (mGlobalLock) {
3422 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3423 if (r == null) {
3424 return false;
3425 }
3426 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3427 return r.inMultiWindowMode();
3428 }
3429 } finally {
3430 Binder.restoreCallingIdentity(origId);
3431 }
3432 }
3433
3434 @Override
3435 public boolean isInPictureInPictureMode(IBinder token) {
3436 final long origId = Binder.clearCallingIdentity();
3437 try {
3438 synchronized (mGlobalLock) {
3439 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3440 }
3441 } finally {
3442 Binder.restoreCallingIdentity(origId);
3443 }
3444 }
3445
3446 private boolean isInPictureInPictureMode(ActivityRecord r) {
3447 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3448 || r.getStack().isInStackLocked(r) == null) {
3449 return false;
3450 }
3451
3452 // If we are animating to fullscreen then we have already dispatched the PIP mode
3453 // changed, so we should reflect that check here as well.
3454 final PinnedActivityStack stack = r.getStack();
3455 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3456 return !windowController.isAnimatingBoundsToFullscreen();
3457 }
3458
3459 @Override
3460 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3461 final long origId = Binder.clearCallingIdentity();
3462 try {
3463 synchronized (mGlobalLock) {
3464 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3465 "enterPictureInPictureMode", token, params);
3466
3467 // If the activity is already in picture in picture mode, then just return early
3468 if (isInPictureInPictureMode(r)) {
3469 return true;
3470 }
3471
3472 // Activity supports picture-in-picture, now check that we can enter PiP at this
3473 // point, if it is
3474 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3475 false /* beforeStopping */)) {
3476 return false;
3477 }
3478
3479 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003480 synchronized (mGlobalLock) {
3481 // Only update the saved args from the args that are set
3482 r.pictureInPictureArgs.copyOnlySet(params);
3483 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3484 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3485 // Adjust the source bounds by the insets for the transition down
3486 final Rect sourceBounds = new Rect(
3487 r.pictureInPictureArgs.getSourceRectHint());
3488 mStackSupervisor.moveActivityToPinnedStackLocked(
3489 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3490 final PinnedActivityStack stack = r.getStack();
3491 stack.setPictureInPictureAspectRatio(aspectRatio);
3492 stack.setPictureInPictureActions(actions);
3493 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3494 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3495 logPictureInPictureArgs(params);
3496 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 };
3498
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003499 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003500 // If the keyguard is showing or occluded, then try and dismiss it before
3501 // entering picture-in-picture (this will prompt the user to authenticate if the
3502 // device is currently locked).
3503 dismissKeyguard(token, new KeyguardDismissCallback() {
3504 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003505 public void onDismissSucceeded() {
3506 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 }
3508 }, null /* message */);
3509 } else {
3510 // Enter picture in picture immediately otherwise
3511 enterPipRunnable.run();
3512 }
3513 return true;
3514 }
3515 } finally {
3516 Binder.restoreCallingIdentity(origId);
3517 }
3518 }
3519
3520 @Override
3521 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3522 final long origId = Binder.clearCallingIdentity();
3523 try {
3524 synchronized (mGlobalLock) {
3525 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3526 "setPictureInPictureParams", token, params);
3527
3528 // Only update the saved args from the args that are set
3529 r.pictureInPictureArgs.copyOnlySet(params);
3530 if (r.inPinnedWindowingMode()) {
3531 // If the activity is already in picture-in-picture, update the pinned stack now
3532 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3533 // be used the next time the activity enters PiP
3534 final PinnedActivityStack stack = r.getStack();
3535 if (!stack.isAnimatingBoundsToFullscreen()) {
3536 stack.setPictureInPictureAspectRatio(
3537 r.pictureInPictureArgs.getAspectRatio());
3538 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3539 }
3540 }
3541 logPictureInPictureArgs(params);
3542 }
3543 } finally {
3544 Binder.restoreCallingIdentity(origId);
3545 }
3546 }
3547
3548 @Override
3549 public int getMaxNumPictureInPictureActions(IBinder token) {
3550 // Currently, this is a static constant, but later, we may change this to be dependent on
3551 // the context of the activity
3552 return 3;
3553 }
3554
3555 private void logPictureInPictureArgs(PictureInPictureParams params) {
3556 if (params.hasSetActions()) {
3557 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3558 params.getActions().size());
3559 }
3560 if (params.hasSetAspectRatio()) {
3561 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3562 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3563 MetricsLogger.action(lm);
3564 }
3565 }
3566
3567 /**
3568 * Checks the state of the system and the activity associated with the given {@param token} to
3569 * verify that picture-in-picture is supported for that activity.
3570 *
3571 * @return the activity record for the given {@param token} if all the checks pass.
3572 */
3573 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3574 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003576 throw new IllegalStateException(caller
3577 + ": Device doesn't support picture-in-picture mode.");
3578 }
3579
3580 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3581 if (r == null) {
3582 throw new IllegalStateException(caller
3583 + ": Can't find activity for token=" + token);
3584 }
3585
3586 if (!r.supportsPictureInPicture()) {
3587 throw new IllegalStateException(caller
3588 + ": Current activity does not support picture-in-picture.");
3589 }
3590
3591 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003592 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 params.getAspectRatio())) {
3594 final float minAspectRatio = mContext.getResources().getFloat(
3595 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3596 final float maxAspectRatio = mContext.getResources().getFloat(
3597 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3598 throw new IllegalArgumentException(String.format(caller
3599 + ": Aspect ratio is too extreme (must be between %f and %f).",
3600 minAspectRatio, maxAspectRatio));
3601 }
3602
3603 // Truncate the number of actions if necessary
3604 params.truncateActions(getMaxNumPictureInPictureActions(token));
3605
3606 return r;
3607 }
3608
3609 @Override
3610 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003611 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 synchronized (mGlobalLock) {
3613 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3614 if (r == null) {
3615 throw new IllegalArgumentException("Activity does not exist; token="
3616 + activityToken);
3617 }
3618 return r.getUriPermissionsLocked().getExternalTokenLocked();
3619 }
3620 }
3621
3622 @Override
3623 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3624 Rect tempDockedTaskInsetBounds,
3625 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003626 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003627 long ident = Binder.clearCallingIdentity();
3628 try {
3629 synchronized (mGlobalLock) {
3630 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3631 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3632 PRESERVE_WINDOWS);
3633 }
3634 } finally {
3635 Binder.restoreCallingIdentity(ident);
3636 }
3637 }
3638
3639 @Override
3640 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003641 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 final long ident = Binder.clearCallingIdentity();
3643 try {
3644 synchronized (mGlobalLock) {
3645 mStackSupervisor.setSplitScreenResizing(resizing);
3646 }
3647 } finally {
3648 Binder.restoreCallingIdentity(ident);
3649 }
3650 }
3651
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003652 /**
3653 * Check that we have the features required for VR-related API calls, and throw an exception if
3654 * not.
3655 */
3656 void enforceSystemHasVrFeature() {
3657 if (!mContext.getPackageManager().hasSystemFeature(
3658 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3659 throw new UnsupportedOperationException("VR mode not supported on this device!");
3660 }
3661 }
3662
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 @Override
3664 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003665 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003666
3667 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3668
3669 ActivityRecord r;
3670 synchronized (mGlobalLock) {
3671 r = ActivityRecord.isInStackLocked(token);
3672 }
3673
3674 if (r == null) {
3675 throw new IllegalArgumentException();
3676 }
3677
3678 int err;
3679 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3680 VrManagerInternal.NO_ERROR) {
3681 return err;
3682 }
3683
3684 // Clear the binder calling uid since this path may call moveToTask().
3685 final long callingId = Binder.clearCallingIdentity();
3686 try {
3687 synchronized (mGlobalLock) {
3688 r.requestedVrComponent = (enabled) ? packageName : null;
3689
3690 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003691 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003692 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 }
3694 return 0;
3695 }
3696 } finally {
3697 Binder.restoreCallingIdentity(callingId);
3698 }
3699 }
3700
3701 @Override
3702 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3703 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3704 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003705 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3707 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3708 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003709 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 || activity.voiceSession != null) {
3711 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3712 return;
3713 }
3714 if (activity.pendingVoiceInteractionStart) {
3715 Slog.w(TAG, "Pending start of voice interaction already.");
3716 return;
3717 }
3718 activity.pendingVoiceInteractionStart = true;
3719 }
3720 LocalServices.getService(VoiceInteractionManagerInternal.class)
3721 .startLocalVoiceInteraction(callingActivity, options);
3722 }
3723
3724 @Override
3725 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3726 LocalServices.getService(VoiceInteractionManagerInternal.class)
3727 .stopLocalVoiceInteraction(callingActivity);
3728 }
3729
3730 @Override
3731 public boolean supportsLocalVoiceInteraction() {
3732 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3733 .supportsLocalVoiceInteraction();
3734 }
3735
3736 /** Notifies all listeners when the pinned stack animation starts. */
3737 @Override
3738 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003739 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 }
3741
3742 /** Notifies all listeners when the pinned stack animation ends. */
3743 @Override
3744 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003745 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003746 }
3747
3748 @Override
3749 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003750 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 final long ident = Binder.clearCallingIdentity();
3752 try {
3753 synchronized (mGlobalLock) {
3754 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3755 }
3756 } finally {
3757 Binder.restoreCallingIdentity(ident);
3758 }
3759 }
3760
3761 @Override
3762 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003763 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003764
3765 synchronized (mGlobalLock) {
3766 // Check if display is initialized in AM.
3767 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3768 // Call might come when display is not yet added or has already been removed.
3769 if (DEBUG_CONFIGURATION) {
3770 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3771 + displayId);
3772 }
3773 return false;
3774 }
3775
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003776 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003777 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003778 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779 }
3780
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003781 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003783 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003784 }
3785
3786 final long origId = Binder.clearCallingIdentity();
3787 try {
3788 if (values != null) {
3789 Settings.System.clearConfiguration(values);
3790 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
3793 return mTmpUpdateConfigurationResult.changes != 0;
3794 } finally {
3795 Binder.restoreCallingIdentity(origId);
3796 }
3797 }
3798 }
3799
3800 @Override
3801 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003802 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003803
3804 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003805 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003807 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 }
3809
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003810 if (mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003811 // Update OOM levels based on display size.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003812 mAm.mProcessList.applyDisplaySize(mWindowManager);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 }
3814
3815 final long origId = Binder.clearCallingIdentity();
3816 try {
3817 if (values != null) {
3818 Settings.System.clearConfiguration(values);
3819 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003820 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 UserHandle.USER_NULL, false /* deferResume */,
3822 mTmpUpdateConfigurationResult);
3823 return mTmpUpdateConfigurationResult.changes != 0;
3824 } finally {
3825 Binder.restoreCallingIdentity(origId);
3826 }
3827 }
3828 }
3829
3830 @Override
3831 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
3832 CharSequence message) {
3833 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003834 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
3836 }
3837 final long callingId = Binder.clearCallingIdentity();
3838 try {
3839 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003840 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(callingId);
3844 }
3845 }
3846
3847 @Override
3848 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003849 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 "cancelTaskWindowTransition()");
3851 final long ident = Binder.clearCallingIdentity();
3852 try {
3853 synchronized (mGlobalLock) {
3854 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
3855 MATCH_TASK_IN_STACKS_ONLY);
3856 if (task == null) {
3857 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
3858 return;
3859 }
3860 task.cancelWindowTransition();
3861 }
3862 } finally {
3863 Binder.restoreCallingIdentity(ident);
3864 }
3865 }
3866
3867 @Override
3868 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003869 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 final long ident = Binder.clearCallingIdentity();
3871 try {
3872 final TaskRecord task;
3873 synchronized (mGlobalLock) {
3874 task = mStackSupervisor.anyTaskForIdLocked(taskId,
3875 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3876 if (task == null) {
3877 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
3878 return null;
3879 }
3880 }
3881 // Don't call this while holding the lock as this operation might hit the disk.
3882 return task.getSnapshot(reducedResolution);
3883 } finally {
3884 Binder.restoreCallingIdentity(ident);
3885 }
3886 }
3887
3888 @Override
3889 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
3890 synchronized (mGlobalLock) {
3891 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3892 if (r == null) {
3893 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
3894 + token);
3895 return;
3896 }
3897 final long origId = Binder.clearCallingIdentity();
3898 try {
3899 r.setDisablePreviewScreenshots(disable);
3900 } finally {
3901 Binder.restoreCallingIdentity(origId);
3902 }
3903 }
3904 }
3905
3906 /** Return the user id of the last resumed activity. */
3907 @Override
3908 public @UserIdInt
3909 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
3912 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003913 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003914 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003916 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 }
3918 }
3919
3920 @Override
3921 public void updateLockTaskFeatures(int userId, int flags) {
3922 final int callingUid = Binder.getCallingUid();
3923 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003924 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 "updateLockTaskFeatures()");
3926 }
3927 synchronized (mGlobalLock) {
3928 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
3929 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003930 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003931 }
3932 }
3933
3934 @Override
3935 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
3936 synchronized (mGlobalLock) {
3937 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3938 if (r == null) {
3939 return;
3940 }
3941 final long origId = Binder.clearCallingIdentity();
3942 try {
3943 r.setShowWhenLocked(showWhenLocked);
3944 } finally {
3945 Binder.restoreCallingIdentity(origId);
3946 }
3947 }
3948 }
3949
3950 @Override
3951 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
3952 synchronized (mGlobalLock) {
3953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3954 if (r == null) {
3955 return;
3956 }
3957 final long origId = Binder.clearCallingIdentity();
3958 try {
3959 r.setTurnScreenOn(turnScreenOn);
3960 } finally {
3961 Binder.restoreCallingIdentity(origId);
3962 }
3963 }
3964 }
3965
3966 @Override
3967 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003968 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 "registerRemoteAnimations");
3970 definition.setCallingPid(Binder.getCallingPid());
3971 synchronized (mGlobalLock) {
3972 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3973 if (r == null) {
3974 return;
3975 }
3976 final long origId = Binder.clearCallingIdentity();
3977 try {
3978 r.registerRemoteAnimations(definition);
3979 } finally {
3980 Binder.restoreCallingIdentity(origId);
3981 }
3982 }
3983 }
3984
3985 @Override
3986 public void registerRemoteAnimationForNextActivityStart(String packageName,
3987 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 "registerRemoteAnimationForNextActivityStart");
3990 adapter.setCallingPid(Binder.getCallingPid());
3991 synchronized (mGlobalLock) {
3992 final long origId = Binder.clearCallingIdentity();
3993 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07003994 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 packageName, adapter);
3996 } finally {
3997 Binder.restoreCallingIdentity(origId);
3998 }
3999 }
4000 }
4001
4002 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4003 @Override
4004 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4005 synchronized (mGlobalLock) {
4006 final long origId = Binder.clearCallingIdentity();
4007 try {
4008 mAm.mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
4009 } finally {
4010 Binder.restoreCallingIdentity(origId);
4011 }
4012 }
4013 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004014
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004015 @Override
4016 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004017 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004018 synchronized (mGlobalLock) {
4019 synchronized (mAm.mPidsSelfLocked) {
4020 final int pid = Binder.getCallingPid();
4021 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004022 mVrController.setVrThreadLocked(tid, pid, proc.getWindowProcessController());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004023 }
4024 }
4025 }
4026
4027 @Override
4028 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004029 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004030 != PERMISSION_GRANTED) {
4031 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4032 + Binder.getCallingPid()
4033 + ", uid=" + Binder.getCallingUid()
4034 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4035 Slog.w(TAG, msg);
4036 throw new SecurityException(msg);
4037 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004038 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004039 synchronized (mGlobalLock) {
4040 synchronized (mAm.mPidsSelfLocked) {
4041 final int pid = Binder.getCallingPid();
4042 final ProcessRecord proc = mAm.mPidsSelfLocked.get(pid);
4043 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
4044 }
4045 }
4046 }
4047
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004048 @Override
4049 public void stopAppSwitches() {
4050 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4051 synchronized (mGlobalLock) {
4052 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4053 mDidAppSwitch = false;
4054 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4055 }
4056 }
4057
4058 @Override
4059 public void resumeAppSwitches() {
4060 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4061 synchronized (mGlobalLock) {
4062 // Note that we don't execute any pending app switches... we will
4063 // let those wait until either the timeout, or the next start
4064 // activity request.
4065 mAppSwitchesAllowedTime = 0;
4066 }
4067 }
4068
4069 void onStartActivitySetDidAppSwitch() {
4070 if (mDidAppSwitch) {
4071 // This is the second allowed switch since we stopped switches, so now just generally
4072 // allow switches. Use case:
4073 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4074 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4075 // anyone to switch again).
4076 mAppSwitchesAllowedTime = 0;
4077 } else {
4078 mDidAppSwitch = true;
4079 }
4080 }
4081
4082 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004083 boolean shouldDisableNonVrUiLocked() {
4084 return mVrController.shouldDisableNonVrUiLocked();
4085 }
4086
4087 void applyUpdateVrModeLocked(ActivityRecord r) {
4088 // VR apps are expected to run in a main display. If an app is turning on VR for
4089 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4090 // fullscreen stack before enabling VR Mode.
4091 // TODO: The goal of this code is to keep the VR app on the main display. When the
4092 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4093 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4094 // option would be a better choice here.
4095 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4096 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4097 + " to main stack for VR");
4098 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4099 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4100 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4101 }
4102 mH.post(() -> {
4103 if (!mVrController.onVrModeChanged(r)) {
4104 return;
4105 }
4106 synchronized (mGlobalLock) {
4107 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4108 mWindowManager.disableNonVrUi(disableNonVrUi);
4109 if (disableNonVrUi) {
4110 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4111 // then remove the pinned stack.
4112 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4113 }
4114 }
4115 });
4116 }
4117
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004118 ActivityStack getTopDisplayFocusedStack() {
4119 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004120 }
4121
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004122 /** Pokes the task persister. */
4123 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4124 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4125 }
4126
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004127 void onTopProcChangedLocked(WindowProcessController proc) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004128 mVrController.onTopProcChangedLocked(proc);
4129 }
4130
4131 boolean isKeyguardLocked() {
4132 return mKeyguardController.isKeyguardLocked();
4133 }
4134
4135 boolean isNextTransitionForward() {
4136 int transit = mWindowManager.getPendingAppTransition();
4137 return transit == TRANSIT_ACTIVITY_OPEN
4138 || transit == TRANSIT_TASK_OPEN
4139 || transit == TRANSIT_TASK_TO_FRONT;
4140 }
4141
Wale Ogunwalef6733932018-06-27 05:14:34 -07004142 void dumpSleepStates(PrintWriter pw, boolean testPssMode) {
4143 synchronized (mGlobalLock) {
4144 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
4145 if (mRunningVoice != null) {
4146 pw.println(" mRunningVoice=" + mRunningVoice);
4147 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
4148 }
4149 pw.println(" mSleeping=" + mSleeping);
4150 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
4151 pw.println(" mVrController=" + mVrController);
4152 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004153 }
4154
Wale Ogunwalef6733932018-06-27 05:14:34 -07004155 void writeSleepStateToProto(ProtoOutputStream proto) {
4156 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4157 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4158 st.toString());
4159 }
4160
4161 if (mRunningVoice != null) {
4162 final long vrToken = proto.start(
4163 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4164 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4165 mRunningVoice.toString());
4166 mVoiceWakeLock.writeToProto(
4167 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4168 proto.end(vrToken);
4169 }
4170
4171 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4172 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4173 mShuttingDown);
4174 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004175 }
4176
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004177 int getCurrentUserId() {
4178 return mAmInternal.getCurrentUserId();
4179 }
4180
4181 private void enforceNotIsolatedCaller(String caller) {
4182 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4183 throw new SecurityException("Isolated process not allowed to call " + caller);
4184 }
4185 }
4186
Wale Ogunwalef6733932018-06-27 05:14:34 -07004187 public Configuration getConfiguration() {
4188 Configuration ci;
4189 synchronized(mGlobalLock) {
4190 ci = new Configuration(getGlobalConfiguration());
4191 ci.userSetLocale = false;
4192 }
4193 return ci;
4194 }
4195
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004196 /**
4197 * Current global configuration information. Contains general settings for the entire system,
4198 * also corresponds to the merged configuration of the default display.
4199 */
4200 Configuration getGlobalConfiguration() {
4201 return mStackSupervisor.getConfiguration();
4202 }
4203
4204 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4205 boolean initLocale) {
4206 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4207 }
4208
4209 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4210 boolean initLocale, boolean deferResume) {
4211 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4212 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4213 UserHandle.USER_NULL, deferResume);
4214 }
4215
4216 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4217 final long origId = Binder.clearCallingIdentity();
4218 try {
4219 synchronized (mGlobalLock) {
4220 updateConfigurationLocked(values, null, false, true, userId,
4221 false /* deferResume */);
4222 }
4223 } finally {
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226 }
4227
4228 void updateUserConfiguration() {
4229 synchronized (mGlobalLock) {
4230 final Configuration configuration = new Configuration(getGlobalConfiguration());
4231 final int currentUserId = mAmInternal.getCurrentUserId();
4232 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(), configuration,
4233 currentUserId, Settings.System.canWrite(mContext));
4234 updateConfigurationLocked(configuration, null /* starting */, false /* initLocale */,
4235 false /* persistent */, currentUserId, false /* deferResume */);
4236 }
4237 }
4238
4239 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4240 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4241 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4242 deferResume, null /* result */);
4243 }
4244
4245 /**
4246 * Do either or both things: (1) change the current configuration, and (2)
4247 * make sure the given activity is running with the (now) current
4248 * configuration. Returns true if the activity has been left running, or
4249 * false if <var>starting</var> is being destroyed to match the new
4250 * configuration.
4251 *
4252 * @param userId is only used when persistent parameter is set to true to persist configuration
4253 * for that particular user
4254 */
4255 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4256 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4257 ActivityTaskManagerService.UpdateConfigurationResult result) {
4258 int changes = 0;
4259 boolean kept = true;
4260
4261 if (mWindowManager != null) {
4262 mWindowManager.deferSurfaceLayout();
4263 }
4264 try {
4265 if (values != null) {
4266 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4267 deferResume);
4268 }
4269
4270 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4271 } finally {
4272 if (mWindowManager != null) {
4273 mWindowManager.continueSurfaceLayout();
4274 }
4275 }
4276
4277 if (result != null) {
4278 result.changes = changes;
4279 result.activityRelaunched = !kept;
4280 }
4281 return kept;
4282 }
4283
4284 /**
4285 * Returns true if this configuration change is interesting enough to send an
4286 * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
4287 */
4288 private static boolean isSplitConfigurationChange(int configDiff) {
4289 return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
4290 }
4291
4292 /** Update default (global) configuration and notify listeners about changes. */
4293 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4294 boolean persistent, int userId, boolean deferResume) {
4295 mTempConfig.setTo(getGlobalConfiguration());
4296 final int changes = mTempConfig.updateFrom(values);
4297 if (changes == 0) {
4298 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4299 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4300 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4301 // (even if there are no actual changes) to unfreeze the window.
4302 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4303 return 0;
4304 }
4305
4306 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4307 "Updating global configuration to: " + values);
4308
4309 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4310 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4311 values.colorMode,
4312 values.densityDpi,
4313 values.fontScale,
4314 values.hardKeyboardHidden,
4315 values.keyboard,
4316 values.keyboardHidden,
4317 values.mcc,
4318 values.mnc,
4319 values.navigation,
4320 values.navigationHidden,
4321 values.orientation,
4322 values.screenHeightDp,
4323 values.screenLayout,
4324 values.screenWidthDp,
4325 values.smallestScreenWidthDp,
4326 values.touchscreen,
4327 values.uiMode);
4328
4329
4330 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4331 final LocaleList locales = values.getLocales();
4332 int bestLocaleIndex = 0;
4333 if (locales.size() > 1) {
4334 if (mSupportedSystemLocales == null) {
4335 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4336 }
4337 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4338 }
4339 SystemProperties.set("persist.sys.locale",
4340 locales.get(bestLocaleIndex).toLanguageTag());
4341 LocaleList.setDefault(locales, bestLocaleIndex);
4342 mAm.mHandler.sendMessage(mAm.mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG,
4343 locales.get(bestLocaleIndex)));
4344 }
4345
4346 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
4347 mTempConfig.seq = mConfigurationSeq;
4348
4349 // Update stored global config and notify everyone about the change.
4350 mStackSupervisor.onConfigurationChanged(mTempConfig);
4351
4352 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4353 // TODO(multi-display): Update UsageEvents#Event to include displayId.
4354 mAm.mUsageStatsService.reportConfigurationChange(
4355 mTempConfig, mAmInternal.getCurrentUserId());
4356
4357 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004358 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359
4360 AttributeCache ac = AttributeCache.instance();
4361 if (ac != null) {
4362 ac.updateConfiguration(mTempConfig);
4363 }
4364
4365 // Make sure all resources in our process are updated right now, so that anyone who is going
4366 // to retrieve resource values after we return will be sure to get the new ones. This is
4367 // especially important during boot, where the first config change needs to guarantee all
4368 // resources have that config before following boot code is executed.
4369 mAm.mSystemThread.applyConfigurationToResources(mTempConfig);
4370
4371 // We need another copy of global config because we're scheduling some calls instead of
4372 // running them in place. We need to be sure that object we send will be handled unchanged.
4373 final Configuration configCopy = new Configuration(mTempConfig);
4374 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
4375 Message msg = mAm.mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
4376 msg.obj = configCopy;
4377 msg.arg1 = userId;
4378 mAm.mHandler.sendMessage(msg);
4379 }
4380
4381 for (int i = mAm.mLruProcesses.size() - 1; i >= 0; i--) {
4382 ProcessRecord app = mAm.mLruProcesses.get(i);
4383 try {
4384 if (app.thread != null) {
4385 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc "
4386 + app.processName + " new config " + configCopy);
4387 getLifecycleManager().scheduleTransaction(app.thread,
4388 ConfigurationChangeItem.obtain(configCopy));
4389 }
4390 } catch (Exception e) {
4391 Slog.e(TAG_CONFIGURATION, "Failed to schedule configuration change", e);
4392 }
4393 }
4394
4395 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
4396 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING
4397 | Intent.FLAG_RECEIVER_FOREGROUND
4398 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4399 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4400 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4401 UserHandle.USER_ALL);
4402 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
4403 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
4404 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
4405 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
4406 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
4407 if (initLocale || !mAm.mProcessesReady) {
4408 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4409 }
4410 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
4411 OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
4412 UserHandle.USER_ALL);
4413 }
4414
4415 // Send a broadcast to PackageInstallers if the configuration change is interesting
4416 // for the purposes of installing additional splits.
4417 if (!initLocale && isSplitConfigurationChange(changes)) {
4418 intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
4419 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
4420 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4421
4422 // Typically only app stores will have this permission.
4423 String[] permissions = new String[] { android.Manifest.permission.INSTALL_PACKAGES };
4424 mAm.broadcastIntentLocked(null, null, intent, null, null, 0, null, null, permissions,
4425 OP_NONE, null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
4426 }
4427
4428 // Override configuration of the default display duplicates global config, so we need to
4429 // update it also. This will also notify WindowManager about changes.
4430 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4431 DEFAULT_DISPLAY);
4432
4433 return changes;
4434 }
4435
4436 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4437 boolean deferResume, int displayId) {
4438 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4439 displayId, null /* result */);
4440 }
4441
4442 /**
4443 * Updates override configuration specific for the selected display. If no config is provided,
4444 * new one will be computed in WM based on current display info.
4445 */
4446 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4447 ActivityRecord starting, boolean deferResume, int displayId,
4448 ActivityTaskManagerService.UpdateConfigurationResult result) {
4449 int changes = 0;
4450 boolean kept = true;
4451
4452 if (mWindowManager != null) {
4453 mWindowManager.deferSurfaceLayout();
4454 }
4455 try {
4456 if (values != null) {
4457 if (displayId == DEFAULT_DISPLAY) {
4458 // Override configuration of the default display duplicates global config, so
4459 // we're calling global config update instead for default display. It will also
4460 // apply the correct override config.
4461 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4462 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4463 } else {
4464 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4465 }
4466 }
4467
4468 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4469 } finally {
4470 if (mWindowManager != null) {
4471 mWindowManager.continueSurfaceLayout();
4472 }
4473 }
4474
4475 if (result != null) {
4476 result.changes = changes;
4477 result.activityRelaunched = !kept;
4478 }
4479 return kept;
4480 }
4481
4482 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4483 int displayId) {
4484 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4485 final int changes = mTempConfig.updateFrom(values);
4486 if (changes != 0) {
4487 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4488 + mTempConfig + " for displayId=" + displayId);
4489 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4490
4491 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4492 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
4493 mAm.mAppWarnings.onDensityChanged();
4494
4495 mAm.killAllBackgroundProcessesExcept(N,
4496 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4497 }
4498 }
4499
4500 // Update the configuration with WM first and check if any of the stacks need to be resized
4501 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4502 // necessary. This way we don't need to relaunch again afterwards in
4503 // ensureActivityConfiguration().
4504 if (mWindowManager != null) {
4505 final int[] resizedStacks =
4506 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4507 if (resizedStacks != null) {
4508 for (int stackId : resizedStacks) {
4509 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4510 }
4511 }
4512 }
4513
4514 return changes;
4515 }
4516
Wale Ogunwalef6733932018-06-27 05:14:34 -07004517 private void updateEventDispatchingLocked(boolean booted) {
4518 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4519 }
4520
4521 void enableScreenAfterBoot(boolean booted) {
4522 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4523 SystemClock.uptimeMillis());
4524 mWindowManager.enableScreenAfterBoot();
4525
4526 synchronized (mGlobalLock) {
4527 updateEventDispatchingLocked(booted);
4528 }
4529 }
4530
4531 boolean canShowErrorDialogs() {
4532 return mShowDialogs && !mSleeping && !mShuttingDown
4533 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
4534 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
Wale Ogunwale86b74462018-07-02 08:42:43 -07004535 mAmInternal.getCurrentUserId())
Wale Ogunwalef6733932018-06-27 05:14:34 -07004536 && !(UserManager.isDeviceInDemoMode(mContext)
Wale Ogunwale86b74462018-07-02 08:42:43 -07004537 && mAmInternal.getCurrentUser().isDemo());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004538 }
4539
4540 /**
4541 * Decide based on the configuration whether we should show the ANR,
4542 * crash, etc dialogs. The idea is that if there is no affordance to
4543 * press the on-screen buttons, or the user experience would be more
4544 * greatly impacted than the crash itself, we shouldn't show the dialog.
4545 *
4546 * A thought: SystemUI might also want to get told about this, the Power
4547 * dialog / global actions also might want different behaviors.
4548 */
4549 private void updateShouldShowDialogsLocked(Configuration config) {
4550 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4551 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4552 && config.navigation == Configuration.NAVIGATION_NONAV);
4553 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4554 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4555 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4556 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4557 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4558 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4559 HIDE_ERROR_DIALOGS, 0) != 0;
4560 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4561 }
4562
4563 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4564 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4565 FONT_SCALE, 1.0f, userId);
4566
4567 synchronized (this) {
4568 if (getGlobalConfiguration().fontScale == scaleFactor) {
4569 return;
4570 }
4571
4572 final Configuration configuration
4573 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4574 configuration.fontScale = scaleFactor;
4575 updatePersistentConfiguration(configuration, userId);
4576 }
4577 }
4578
4579 // Actually is sleeping or shutting down or whatever else in the future
4580 // is an inactive state.
4581 boolean isSleepingOrShuttingDownLocked() {
4582 return isSleepingLocked() || mShuttingDown;
4583 }
4584
4585 boolean isSleepingLocked() {
4586 return mSleeping;
4587 }
4588
4589 /**
4590 * Update AMS states when an activity is resumed. This should only be called by
4591 * {@link ActivityStack#onActivityStateChanged(
4592 * ActivityRecord, ActivityStack.ActivityState, String)} when an activity is resumed.
4593 */
4594 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4595 final TaskRecord task = r.getTask();
4596 if (task.isActivityTypeStandard()) {
4597 if (mCurAppTimeTracker != r.appTimeTracker) {
4598 // We are switching app tracking. Complete the current one.
4599 if (mCurAppTimeTracker != null) {
4600 mCurAppTimeTracker.stop();
4601 mH.obtainMessage(
4602 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4603 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4604 mCurAppTimeTracker = null;
4605 }
4606 if (r.appTimeTracker != null) {
4607 mCurAppTimeTracker = r.appTimeTracker;
4608 startTimeTrackingFocusedActivityLocked();
4609 }
4610 } else {
4611 startTimeTrackingFocusedActivityLocked();
4612 }
4613 } else {
4614 r.appTimeTracker = null;
4615 }
4616 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
4617 // TODO: Probably not, because we don't want to resume voice on switching
4618 // back to this activity
4619 if (task.voiceInteractor != null) {
4620 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
4621 } else {
4622 finishRunningVoiceLocked();
4623
4624 if (mLastResumedActivity != null) {
4625 final IVoiceInteractionSession session;
4626
4627 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
4628 if (lastResumedActivityTask != null
4629 && lastResumedActivityTask.voiceSession != null) {
4630 session = lastResumedActivityTask.voiceSession;
4631 } else {
4632 session = mLastResumedActivity.voiceSession;
4633 }
4634
4635 if (session != null) {
4636 // We had been in a voice interaction session, but now focused has
4637 // move to something different. Just finish the session, we can't
4638 // return to it and retain the proper state and synchronization with
4639 // the voice interaction service.
4640 finishVoiceTask(session);
4641 }
4642 }
4643 }
4644
4645 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
4646 mAmInternal.sendForegroundProfileChanged(r.userId);
4647 }
4648 updateResumedAppTrace(r);
4649 mLastResumedActivity = r;
4650
4651 mWindowManager.setFocusedApp(r.appToken, true);
4652
4653 applyUpdateLockStateLocked(r);
4654 applyUpdateVrModeLocked(r);
4655
4656 EventLogTags.writeAmSetResumedActivity(
4657 r == null ? -1 : r.userId,
4658 r == null ? "NULL" : r.shortComponentName,
4659 reason);
4660 }
4661
4662 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
4663 synchronized (mGlobalLock) {
4664 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
4665 updateSleepIfNeededLocked();
4666 return token;
4667 }
4668 }
4669
4670 void updateSleepIfNeededLocked() {
4671 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
4672 final boolean wasSleeping = mSleeping;
4673 boolean updateOomAdj = false;
4674
4675 if (!shouldSleep) {
4676 // If wasSleeping is true, we need to wake up activity manager state from when
4677 // we started sleeping. In either case, we need to apply the sleep tokens, which
4678 // will wake up stacks or put them to sleep as appropriate.
4679 if (wasSleeping) {
4680 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004681 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4682 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004683 startTimeTrackingFocusedActivityLocked();
4684 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
4685 mStackSupervisor.comeOutOfSleepIfNeededLocked();
4686 }
4687 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
4688 if (wasSleeping) {
4689 updateOomAdj = true;
4690 }
4691 } else if (!mSleeping && shouldSleep) {
4692 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07004693 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
4694 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004695 if (mCurAppTimeTracker != null) {
4696 mCurAppTimeTracker.stop();
4697 }
4698 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
4699 mStackSupervisor.goingToSleepLocked();
4700 updateResumedAppTrace(null /* resumed */);
4701 updateOomAdj = true;
4702 }
4703 if (updateOomAdj) {
4704 mH.post(mAmInternal::updateOomAdj);
4705 }
4706 }
4707
4708 void updateOomAdj() {
4709 mH.post(mAmInternal::updateOomAdj);
4710 }
4711
Andrii Kulian52d255c2018-07-13 11:32:19 -07004712 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07004713 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07004714 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07004715 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
4716 mCurAppTimeTracker.start(resumedActivity.packageName);
4717 }
4718 }
4719
4720 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
4721 if (mTracedResumedActivity != null) {
4722 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
4723 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
4724 }
4725 if (resumed != null) {
4726 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
4727 constructResumedTraceName(resumed.packageName), 0);
4728 }
4729 mTracedResumedActivity = resumed;
4730 }
4731
4732 private String constructResumedTraceName(String packageName) {
4733 return "focused app: " + packageName;
4734 }
4735
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004736 /** Helper method that requests bounds from WM and applies them to stack. */
4737 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
4738 final Rect newStackBounds = new Rect();
4739 final ActivityStack stack = mStackSupervisor.getStack(stackId);
4740
4741 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
4742 if (stack == null) {
4743 final StringWriter writer = new StringWriter();
4744 final PrintWriter printWriter = new PrintWriter(writer);
4745 mStackSupervisor.dumpDisplays(printWriter);
4746 printWriter.flush();
4747
4748 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
4749 }
4750
4751 stack.getBoundsForNewConfiguration(newStackBounds);
4752 mStackSupervisor.resizeStackLocked(
4753 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
4754 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
4755 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
4756 }
4757
4758 /** Applies latest configuration and/or visibility updates if needed. */
4759 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
4760 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004761 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762 // mainStack is null during startup.
4763 if (mainStack != null) {
4764 if (changes != 0 && starting == null) {
4765 // If the configuration changed, and the caller is not already
4766 // in the process of starting an activity, then find the top
4767 // activity to check if its configuration needs to change.
4768 starting = mainStack.topRunningActivityLocked();
4769 }
4770
4771 if (starting != null) {
4772 kept = starting.ensureActivityConfiguration(changes,
4773 false /* preserveWindow */);
4774 // And we need to make sure at this point that all other activities
4775 // are made visible with the correct configuration.
4776 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
4777 !PRESERVE_WINDOWS);
4778 }
4779 }
4780
4781 return kept;
4782 }
4783
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004784 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
4785 if (true || Build.IS_USER) {
4786 return;
4787 }
4788
4789 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4790 StrictMode.allowThreadDiskWrites();
4791 try {
4792 File tracesDir = new File("/data/anr");
4793 File tracesFile = null;
4794 try {
4795 tracesFile = File.createTempFile("app_slow", null, tracesDir);
4796
4797 StringBuilder sb = new StringBuilder();
4798 Time tobj = new Time();
4799 tobj.set(System.currentTimeMillis());
4800 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4801 sb.append(": ");
4802 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4803 sb.append(" since ");
4804 sb.append(msg);
4805 FileOutputStream fos = new FileOutputStream(tracesFile);
4806 fos.write(sb.toString().getBytes());
4807 if (app == null) {
4808 fos.write("\n*** No application process!".getBytes());
4809 }
4810 fos.close();
4811 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4812 } catch (IOException e) {
4813 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
4814 return;
4815 }
4816
4817 if (app != null && app.getPid() > 0) {
4818 ArrayList<Integer> firstPids = new ArrayList<Integer>();
4819 firstPids.add(app.getPid());
4820 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
4821 }
4822
4823 File lastTracesFile = null;
4824 File curTracesFile = null;
4825 for (int i=9; i>=0; i--) {
4826 String name = String.format(Locale.US, "slow%02d.txt", i);
4827 curTracesFile = new File(tracesDir, name);
4828 if (curTracesFile.exists()) {
4829 if (lastTracesFile != null) {
4830 curTracesFile.renameTo(lastTracesFile);
4831 } else {
4832 curTracesFile.delete();
4833 }
4834 }
4835 lastTracesFile = curTracesFile;
4836 }
4837 tracesFile.renameTo(curTracesFile);
4838 } finally {
4839 StrictMode.setThreadPolicy(oldPolicy);
4840 }
4841 }
4842
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004844 static final int REPORT_TIME_TRACKER_MSG = 1;
4845
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 public H(Looper looper) {
4847 super(looper, null, true);
4848 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004849
4850 @Override
4851 public void handleMessage(Message msg) {
4852 switch (msg.what) {
4853 case REPORT_TIME_TRACKER_MSG: {
4854 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
4855 tracker.deliverResult(mContext);
4856 } break;
4857 }
4858 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004859 }
4860
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004861 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004862 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004863
4864 public UiHandler() {
4865 super(com.android.server.UiThread.get().getLooper(), null, true);
4866 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004867
4868 @Override
4869 public void handleMessage(Message msg) {
4870 switch (msg.what) {
4871 case DISMISS_DIALOG_UI_MSG: {
4872 final Dialog d = (Dialog) msg.obj;
4873 d.dismiss();
4874 break;
4875 }
4876 }
4877 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 }
4879
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004880 final class LocalService extends ActivityTaskManagerInternal {
4881 @Override
4882 public SleepToken acquireSleepToken(String tag, int displayId) {
4883 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07004884 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004885 }
4886
4887 @Override
4888 public ComponentName getHomeActivityForUser(int userId) {
4889 synchronized (mGlobalLock) {
4890 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId);
4891 return homeActivity == null ? null : homeActivity.realActivity;
4892 }
4893 }
4894
4895 @Override
4896 public void onLocalVoiceInteractionStarted(IBinder activity,
4897 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
4898 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004899 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004900 }
4901 }
4902
4903 @Override
4904 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
4905 synchronized (mGlobalLock) {
4906 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
4907 reasons, timestamp);
4908 }
4909 }
4910
4911 @Override
4912 public void notifyAppTransitionFinished() {
4913 synchronized (mGlobalLock) {
4914 mStackSupervisor.notifyAppTransitionDone();
4915 }
4916 }
4917
4918 @Override
4919 public void notifyAppTransitionCancelled() {
4920 synchronized (mGlobalLock) {
4921 mStackSupervisor.notifyAppTransitionDone();
4922 }
4923 }
4924
4925 @Override
4926 public List<IBinder> getTopVisibleActivities() {
4927 synchronized (mGlobalLock) {
4928 return mStackSupervisor.getTopVisibleActivities();
4929 }
4930 }
4931
4932 @Override
4933 public void notifyDockedStackMinimizedChanged(boolean minimized) {
4934 synchronized (mGlobalLock) {
4935 mStackSupervisor.setDockedStackMinimized(minimized);
4936 }
4937 }
4938
4939 @Override
4940 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
4941 Bundle bOptions) {
4942 Preconditions.checkNotNull(intents, "intents");
4943 final String[] resolvedTypes = new String[intents.length];
4944
4945 // UID of the package on user userId.
4946 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
4947 // packageUid may not be initialized.
4948 int packageUid = 0;
4949 final long ident = Binder.clearCallingIdentity();
4950
4951 try {
4952 for (int i = 0; i < intents.length; i++) {
4953 resolvedTypes[i] =
4954 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
4955 }
4956
4957 packageUid = AppGlobals.getPackageManager().getPackageUid(
4958 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
4959 } catch (RemoteException e) {
4960 // Shouldn't happen.
4961 } finally {
4962 Binder.restoreCallingIdentity(ident);
4963 }
4964
4965 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004966 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004967 packageUid, packageName,
4968 intents, resolvedTypes, null /* resultTo */,
4969 SafeActivityOptions.fromBundle(bOptions), userId,
4970 false /* validateIncomingUser */);
4971 }
4972 }
4973
4974 @Override
4975 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
4976 Intent intent, Bundle options, int userId) {
4977 return ActivityTaskManagerService.this.startActivityAsUser(
4978 caller, callerPacakge, intent,
4979 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
4980 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
4981 false /*validateIncomingUser*/);
4982 }
4983
4984 @Override
4985 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
4986 synchronized (mGlobalLock) {
4987
4988 // We might change the visibilities here, so prepare an empty app transition which
4989 // might be overridden later if we actually change visibilities.
4990 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004992 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004993 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004994 false /* alwaysKeepCurrent */);
4995 }
4996 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
4997
4998 // If there was a transition set already we don't want to interfere with it as we
4999 // might be starting it too early.
5000 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005001 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005002 }
5003 }
5004 if (callback != null) {
5005 callback.run();
5006 }
5007 }
5008
5009 @Override
5010 public void notifyKeyguardTrustedChanged() {
5011 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005012 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005013 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5014 }
5015 }
5016 }
5017
5018 /**
5019 * Called after virtual display Id is updated by
5020 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5021 * {@param vrVr2dDisplayId}.
5022 */
5023 @Override
5024 public void setVr2dDisplayId(int vr2dDisplayId) {
5025 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5026 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005027 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005028 }
5029 }
5030
5031 @Override
5032 public void setFocusedActivity(IBinder token) {
5033 synchronized (mGlobalLock) {
5034 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5035 if (r == null) {
5036 throw new IllegalArgumentException(
5037 "setFocusedActivity: No activity record matching token=" + token);
5038 }
5039 if (mStackSupervisor.moveFocusableActivityStackToFrontLocked(
5040 r, "setFocusedActivity")) {
5041 mStackSupervisor.resumeFocusedStackTopActivityLocked();
5042 }
5043 }
5044 }
5045
5046 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005047 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005048 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005049 }
5050
5051 @Override
5052 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005053 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005054 }
5055
5056 @Override
5057 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005058 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005059 }
5060
5061 @Override
5062 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5063 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5064 }
5065
5066 @Override
5067 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005069 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005070
5071 @Override
5072 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5073 synchronized (mGlobalLock) {
5074 mActiveVoiceInteractionServiceComponent = component;
5075 }
5076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077
5078 @Override
5079 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5080 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5081 return;
5082 }
5083 synchronized (mGlobalLock) {
5084 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5085 if (types == null) {
5086 if (uid < 0) {
5087 return;
5088 }
5089 types = new ArrayMap<>();
5090 mAllowAppSwitchUids.put(userId, types);
5091 }
5092 if (uid < 0) {
5093 types.remove(type);
5094 } else {
5095 types.put(type, uid);
5096 }
5097 }
5098 }
5099
5100 @Override
5101 public void onUserStopped(int userId) {
5102 synchronized (mGlobalLock) {
5103 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5104 mAllowAppSwitchUids.remove(userId);
5105 }
5106 }
5107
5108 @Override
5109 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5110 synchronized (mGlobalLock) {
5111 return ActivityTaskManagerService.this.isGetTasksAllowed(
5112 caller, callingPid, callingUid);
5113 }
5114 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005115
5116 @Override
5117 public void onProcessAdded(WindowProcessController proc) {
5118 synchronized (mGlobalLock) {
5119 mProcessNames.put(proc.mName, proc.mUid, proc);
5120 }
5121 }
5122
5123 @Override
5124 public void onProcessRemoved(String name, int uid) {
5125 synchronized (mGlobalLock) {
5126 mProcessNames.remove(name, uid);
5127 }
5128 }
5129
5130 @Override
5131 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5132 synchronized (mGlobalLock) {
5133 if (proc == mHomeProcess) {
5134 mHomeProcess = null;
5135 }
5136 if (proc == mPreviousProcess) {
5137 mPreviousProcess = null;
5138 }
5139 }
5140 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005141
5142 @Override
5143 public int getTopProcessState() {
5144 synchronized (mGlobalLock) {
5145 return mTopProcessState;
5146 }
5147 }
5148
5149 @Override
5150 public boolean isSleeping() {
5151 synchronized (mGlobalLock) {
5152 return isSleepingLocked();
5153 }
5154 }
5155
5156 @Override
5157 public boolean isShuttingDown() {
5158 synchronized (mGlobalLock) {
5159 return mShuttingDown;
5160 }
5161 }
5162
5163 @Override
5164 public boolean shuttingDown(boolean booted, int timeout) {
5165 synchronized (mGlobalLock) {
5166 mShuttingDown = true;
5167 mStackSupervisor.prepareForShutdownLocked();
5168 updateEventDispatchingLocked(booted);
5169 return mStackSupervisor.shutdownLocked(timeout);
5170 }
5171 }
5172
5173 @Override
5174 public void enableScreenAfterBoot(boolean booted) {
5175 synchronized (mGlobalLock) {
5176 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5177 SystemClock.uptimeMillis());
5178 mWindowManager.enableScreenAfterBoot();
5179 updateEventDispatchingLocked(booted);
5180 }
5181 }
5182
5183 @Override
5184 public boolean showStrictModeViolationDialog() {
5185 synchronized (mGlobalLock) {
5186 return mShowDialogs && !mSleeping && !mShuttingDown;
5187 }
5188 }
5189
5190 @Override
5191 public void showSystemReadyErrorDialogsIfNeeded() {
5192 synchronized (mGlobalLock) {
5193 try {
5194 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5195 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5196 + " data partition or your device will be unstable.");
5197 mUiHandler.post(() -> {
5198 if (mShowDialogs) {
5199 AlertDialog d = new BaseErrorDialog(mUiContext);
5200 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5201 d.setCancelable(false);
5202 d.setTitle(mUiContext.getText(R.string.android_system_label));
5203 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5204 d.setButton(DialogInterface.BUTTON_POSITIVE,
5205 mUiContext.getText(R.string.ok),
5206 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5207 d.show();
5208 }
5209 });
5210 }
5211 } catch (RemoteException e) {
5212 }
5213
5214 if (!Build.isBuildConsistent()) {
5215 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5216 mUiHandler.post(() -> {
5217 if (mShowDialogs) {
5218 AlertDialog d = new BaseErrorDialog(mUiContext);
5219 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5220 d.setCancelable(false);
5221 d.setTitle(mUiContext.getText(R.string.android_system_label));
5222 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5223 d.setButton(DialogInterface.BUTTON_POSITIVE,
5224 mUiContext.getText(R.string.ok),
5225 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5226 d.show();
5227 }
5228 });
5229 }
5230 }
5231 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005232 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07005233}