blob: 750fc68326270fb227b0d36389b38edddb9db38a [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
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
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;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070055import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800126import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
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;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700218import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.EventLog;
220import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700221import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700223import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700225import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700226import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700227import android.view.IRecentsAnimationRunner;
228import android.view.RemoteAnimationAdapter;
229import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700293import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Map;
295import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296
297/**
298 * System service for managing activities and their containers (task, stacks, displays,... ).
299 *
300 * {@hide}
301 */
302public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700303 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700304 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700305 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
306 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
307 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
308 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
309 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700310 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700311
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100316 // How long we permit background activity starts after an activity in the process
317 // started or finished.
318 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319
Wale Ogunwale98875612018-10-12 07:53:02 -0700320 /** Used to indicate that an app transition should be animated. */
321 static final boolean ANIMATE = true;
322
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700323 /** Hardware-reported OpenGLES version. */
324 final int GL_ES_VERSION;
325
Wale Ogunwale31913b52018-10-13 08:29:31 -0700326 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
327 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
328 public static final String DUMP_LASTANR_CMD = "lastanr" ;
329 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
330 public static final String DUMP_STARTER_CMD = "starter" ;
331 public static final String DUMP_CONTAINERS_CMD = "containers" ;
332 public static final String DUMP_RECENTS_CMD = "recents" ;
333 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
334
Wale Ogunwale64258362018-10-16 15:13:37 -0700335 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
336 public static final int RELAUNCH_REASON_NONE = 0;
337 /** This activity is being relaunched due to windowing mode change. */
338 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
339 /** This activity is being relaunched due to a free-resize operation. */
340 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
341
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700342 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700343
Wale Ogunwalef6733932018-06-27 05:14:34 -0700344 /**
345 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
346 * change at runtime. Use mContext for non-UI purposes.
347 */
348 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700350 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700353 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700354 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800355 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800356 @VisibleForTesting
357 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 PowerManagerInternal mPowerManagerInternal;
359 private UsageStatsManagerInternal mUsageStatsInternal;
360
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700361 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 IntentFirewall mIntentFirewall;
363
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700364 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800365 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800366 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700367 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
369 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
370 *
371 * @see WindowManagerThreadPriorityBooster
372 */
373 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700374 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800375 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700376 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700377 private UserManagerService mUserManager;
378 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700379 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800380 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700381 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /** All processes currently running that might have a window organized by name. */
383 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100384 /** All processes we currently have running mapped by pid and uid */
385 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** This is the process holding what we currently consider to be the "home" activity. */
387 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700388 /** The currently running heavy-weight process, if any. */
389 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700390 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /**
392 * This is the process holding the activity the user last visited that is in a different process
393 * from the one they are currently in.
394 */
395 WindowProcessController mPreviousProcess;
396 /** The time at which the previous process was last visible. */
397 long mPreviousProcessVisibleTime;
398
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700399 /** List of intents that were used to start the most recent tasks. */
400 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700401 /** State of external calls telling us if the device is awake or asleep. */
402 private boolean mKeyguardShown = false;
403
404 // Wrapper around VoiceInteractionServiceManager
405 private AssistUtils mAssistUtils;
406
407 // VoiceInteraction session ID that changes for each new request except when
408 // being called for multi-window assist in a single session.
409 private int mViSessionId = 1000;
410
411 // How long to wait in getAssistContextExtras for the activity and foreground services
412 // to respond with the result.
413 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
414
415 // How long top wait when going through the modern assist (which doesn't need to block
416 // on getting this result before starting to launch its UI).
417 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
418
419 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
420 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
421
Alison Cichowlas3e340502018-08-07 17:15:01 -0400422 // Permission tokens are used to temporarily granted a trusted app the ability to call
423 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
424 // showing any appropriate error messages to the user.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
426 10 * MINUTE_IN_MILLIS;
427
428 // How long before the service actually expires a token. This is slightly longer than
429 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
430 // expiration exception.
431 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
432 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
433
434 // How long the service will remember expired tokens, for the purpose of providing error
435 // messaging when a client uses an expired token.
436 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
437 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
438
439 // Activity tokens of system activities that are delegating their call to
440 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
441 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
442
443 // Permission tokens that have expired, but we remember for error reporting.
444 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
447
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700448 // Keeps track of the active voice interaction service component, notified from
449 // VoiceInteractionManagerService
450 ComponentName mActiveVoiceInteractionServiceComponent;
451
Michal Karpinskida34cd42019-04-02 19:46:52 +0100452 // A map userId and all its companion app uids
453 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000454
Wale Ogunwalee2172292018-10-25 10:11:10 -0700455 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700456 KeyguardController mKeyguardController;
457 private final ClientLifecycleManager mLifecycleManager;
458 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700459 /** The controller for all operations related to locktask. */
460 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700461 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700462
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 boolean mSuppressResizeConfigChanges;
464
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700465 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 new UpdateConfigurationResult();
467
468 static final class UpdateConfigurationResult {
469 // Configuration changes that were updated.
470 int changes;
471 // If the activity was relaunched to match the new configuration.
472 boolean activityRelaunched;
473
474 void reset() {
475 changes = 0;
476 activityRelaunched = false;
477 }
478 }
479
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 private int mConfigurationSeq;
482 // To cache the list of supported system locales
483 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484
485 /**
486 * Temp object used when global and/or display override configuration is updated. It is also
487 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
488 * anyone...
489 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private Configuration mTempConfig = new Configuration();
491
Wale Ogunwalef6733932018-06-27 05:14:34 -0700492 /** Temporary to avoid allocations. */
493 final StringBuilder mStringBuilder = new StringBuilder(256);
494
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 // Amount of time after a call to stopAppSwitches() during which we will
496 // prevent further untrusted switches from happening.
497 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
498
499 /**
500 * The time at which we will allow normal application switches again,
501 * after a call to {@link #stopAppSwitches()}.
502 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700503 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 /**
505 * This is set to true after the first switch after mAppSwitchesAllowedTime
506 * is set; any switches after that will clear the time.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509
Ricky Wai906af482019-06-03 17:25:28 +0100510 /**
511 * Last stop app switches time, apps finished before this time cannot start background activity
512 * even if they are in grace period.
513 */
514 private long mLastStopAppSwitchesTime;
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 IActivityController mController = null;
517 boolean mControllerIsAMonkey = false;
518
Wale Ogunwale214f3482018-10-04 11:00:47 -0700519 final int mFactoryTest;
520
521 /** Used to control how we initialize the service. */
522 ComponentName mTopComponent;
523 String mTopAction = Intent.ACTION_MAIN;
524 String mTopData;
525
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800526 /** Profiling app information. */
527 String mProfileApp = null;
528 WindowProcessController mProfileProc = null;
529 ProfilerInfo mProfilerInfo = null;
530
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700532 * Dump of the activity state at the time of the last ANR. Cleared after
533 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
534 */
535 String mLastANRState;
536
537 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538 * Used to retain an update lock when the foreground activity is in
539 * immersive mode.
540 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542
543 /**
544 * Packages that are being allowed to perform unrestricted app switches. Mapping is
545 * User -> Type -> uid.
546 */
547 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
548
549 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private int mThumbnailWidth;
551 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700552
553 /**
554 * Flag that indicates if multi-window is enabled.
555 *
556 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
557 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
558 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
559 * At least one of the forms of multi-window must be enabled in order for this flag to be
560 * initialized to 'true'.
561 *
562 * @see #mSupportsSplitScreenMultiWindow
563 * @see #mSupportsFreeformWindowManagement
564 * @see #mSupportsPictureInPicture
565 * @see #mSupportsMultiDisplay
566 */
567 boolean mSupportsMultiWindow;
568 boolean mSupportsSplitScreenMultiWindow;
569 boolean mSupportsFreeformWindowManagement;
570 boolean mSupportsPictureInPicture;
571 boolean mSupportsMultiDisplay;
572 boolean mForceResizableActivities;
573
574 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
575
576 // VR Vr2d Display Id.
577 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700578
Wale Ogunwalef6733932018-06-27 05:14:34 -0700579 /**
580 * Set while we are wanting to sleep, to prevent any
581 * activities from being started/resumed.
582 *
583 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
584 *
585 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
586 * while in the sleep state until there is a pending transition out of sleep, in which case
587 * mSleeping is set to false, and remains false while awake.
588 *
589 * Whether mSleeping can quickly toggled between true/false without the device actually
590 * display changing states is undefined.
591 */
592 private boolean mSleeping = false;
593
594 /**
595 * The process state used for processes that are running the top activities.
596 * This changes between TOP and TOP_SLEEPING to following mSleeping.
597 */
598 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
599
Riddle Hsua0022cd2019-09-09 21:12:41 +0800600 @Retention(RetentionPolicy.SOURCE)
601 @IntDef({
602 LAYOUT_REASON_CONFIG_CHANGED,
603 LAYOUT_REASON_VISIBILITY_CHANGED,
604 })
605 @interface LayoutReason {}
606 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
607 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
608
609 /** The reasons to perform surface placement. */
610 @LayoutReason
611 private int mLayoutReasons;
612
Wale Ogunwalef6733932018-06-27 05:14:34 -0700613 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
614 // automatically. Important for devices without direct input devices.
615 private boolean mShowDialogs = true;
616
617 /** Set if we are shutting down the system, similar to sleeping. */
618 boolean mShuttingDown = false;
619
620 /**
621 * We want to hold a wake lock while running a voice interaction session, since
622 * this may happen with the screen off and we need to keep the CPU running to
623 * be able to continue to interact with the user.
624 */
625 PowerManager.WakeLock mVoiceWakeLock;
626
627 /**
628 * Set while we are running a voice interaction. This overrides sleeping while it is active.
629 */
630 IVoiceInteractionSession mRunningVoice;
631
632 /**
633 * The last resumed activity. This is identical to the current resumed activity most
634 * of the time but could be different when we're pausing one activity before we resume
635 * another activity.
636 */
637 ActivityRecord mLastResumedActivity;
638
639 /**
640 * The activity that is currently being traced as the active resumed activity.
641 *
642 * @see #updateResumedAppTrace
643 */
644 private @Nullable ActivityRecord mTracedResumedActivity;
645
646 /** If non-null, we are tracking the time the user spends in the currently focused app. */
647 AppTimeTracker mCurAppTimeTracker;
648
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700649 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700650
Wale Ogunwale53783742018-09-16 10:21:51 -0700651 /**
652 * Packages that the user has asked to have run in screen size
653 * compatibility mode instead of filling the screen.
654 */
655 CompatModePackages mCompatModePackages;
656
Wale Ogunwalef6733932018-06-27 05:14:34 -0700657 private FontScaleSettingObserver mFontScaleSettingObserver;
658
Ricky Wai96f5c352019-04-10 18:40:17 +0100659 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private final class FontScaleSettingObserver extends ContentObserver {
662 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
663 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
664
665 public FontScaleSettingObserver() {
666 super(mH);
667 final ContentResolver resolver = mContext.getContentResolver();
668 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
669 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
670 UserHandle.USER_ALL);
671 }
672
673 @Override
674 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
675 if (mFontScaleUri.equals(uri)) {
676 updateFontScaleIfNeeded(userId);
677 } else if (mHideErrorDialogsUri.equals(uri)) {
678 synchronized (mGlobalLock) {
679 updateShouldShowDialogsLocked(getGlobalConfiguration());
680 }
681 }
682 }
683 }
684
Riddle Hsua0536432019-02-16 00:38:59 +0800685 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
686 @Target(ElementType.METHOD)
687 @Retention(RetentionPolicy.SOURCE)
688 @interface HotPath {
689 int NONE = 0;
690 int OOM_ADJUSTMENT = 1;
691 int LRU_UPDATE = 2;
692 int PROCESS_CHANGE = 3;
693 int caller() default NONE;
694 }
695
Charles Chen8d98dd22018-12-26 17:36:54 +0800696 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
697 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700698 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700699 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700700 mSystemThread = ActivityThread.currentActivityThread();
701 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700702 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800703 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700704 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void onSystemReady() {
708 synchronized (mGlobalLock) {
709 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
710 PackageManager.FEATURE_CANT_SAVE_STATE);
711 mAssistUtils = new AssistUtils(mContext);
712 mVrController.onSystemReady();
713 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700714 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700715 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700716 }
717
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 public void onInitPowerManagement() {
719 synchronized (mGlobalLock) {
720 mStackSupervisor.initPowerManagement();
721 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
722 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
723 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
724 mVoiceWakeLock.setReferenceCounted(false);
725 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700726 }
727
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700728 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700729 mFontScaleSettingObserver = new FontScaleSettingObserver();
730 }
731
Wale Ogunwale59507092018-10-29 09:00:30 -0700732 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733 final boolean freeformWindowManagement =
734 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
735 || Settings.Global.getInt(
736 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
737
738 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
739 final boolean supportsPictureInPicture = supportsMultiWindow &&
740 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
741 final boolean supportsSplitScreenMultiWindow =
742 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
743 final boolean supportsMultiDisplay = mContext.getPackageManager()
744 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700745 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
746 final boolean forceResizable = Settings.Global.getInt(
747 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
748
749 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900750 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700751
752 final Configuration configuration = new Configuration();
753 Settings.System.getConfiguration(resolver, configuration);
754 if (forceRtl) {
755 // This will take care of setting the correct layout direction flags
756 configuration.setLayoutDirection(configuration.locale);
757 }
758
759 synchronized (mGlobalLock) {
760 mForceResizableActivities = forceResizable;
761 final boolean multiWindowFormEnabled = freeformWindowManagement
762 || supportsSplitScreenMultiWindow
763 || supportsPictureInPicture
764 || supportsMultiDisplay;
765 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
766 mSupportsMultiWindow = true;
767 mSupportsFreeformWindowManagement = freeformWindowManagement;
768 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
769 mSupportsPictureInPicture = supportsPictureInPicture;
770 mSupportsMultiDisplay = supportsMultiDisplay;
771 } else {
772 mSupportsMultiWindow = false;
773 mSupportsFreeformWindowManagement = false;
774 mSupportsSplitScreenMultiWindow = false;
775 mSupportsPictureInPicture = false;
776 mSupportsMultiDisplay = false;
777 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700778 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 // This happens before any activities are started, so we can change global configuration
780 // in-place.
781 updateConfigurationLocked(configuration, null, true);
782 final Configuration globalConfig = getGlobalConfiguration();
783 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
784
785 // Load resources only after the current configuration has been set.
786 final Resources res = mContext.getResources();
787 mThumbnailWidth = res.getDimensionPixelSize(
788 com.android.internal.R.dimen.thumbnail_width);
789 mThumbnailHeight = res.getDimensionPixelSize(
790 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700791 }
792 }
793
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800794 public WindowManagerGlobalLock getGlobalLock() {
795 return mGlobalLock;
796 }
797
Yunfan Chen585f2932019-01-29 16:04:45 +0900798 /** For test purpose only. */
799 @VisibleForTesting
800 public ActivityTaskManagerInternal getAtmInternal() {
801 return mInternal;
802 }
803
Riddle Hsud93a6c42018-11-29 21:50:06 +0800804 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
805 Looper looper) {
806 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700807 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700808 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700809 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800810 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700811 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
814 mTempConfig.setToDefaults();
815 mTempConfig.setLocales(LocaleList.getDefault());
816 mConfigurationSeq = mTempConfig.seq = 1;
817 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800818 mRootActivityContainer = new RootActivityContainer(this);
819 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700820
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700823 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700825 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mKeyguardController = mStackSupervisor.getKeyguardController();
828 }
829
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 public void onActivityManagerInternalAdded() {
831 synchronized (mGlobalLock) {
832 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
833 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
834 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700835 }
836
Yunfan Chen75157d72018-07-27 14:47:21 +0900837 int increaseConfigurationSeqLocked() {
838 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
839 return mConfigurationSeq;
840 }
841
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700842 protected ActivityStackSupervisor createStackSupervisor() {
843 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
844 supervisor.initialize();
845 return supervisor;
846 }
847
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800848 protected AppWarnings createAppWarnings(
849 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
850 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
851 }
852
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 public void setWindowManager(WindowManagerService wm) {
854 synchronized (mGlobalLock) {
855 mWindowManager = wm;
856 mLockTaskController.setWindowManager(wm);
857 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800858 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
863 synchronized (mGlobalLock) {
864 mUsageStatsInternal = usageStatsManager;
865 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700866 }
867
Wale Ogunwalef6733932018-06-27 05:14:34 -0700868 UserManagerService getUserManager() {
869 if (mUserManager == null) {
870 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
871 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
872 }
873 return mUserManager;
874 }
875
876 AppOpsService getAppOpsService() {
877 if (mAppOpsService == null) {
878 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
879 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
880 }
881 return mAppOpsService;
882 }
883
884 boolean hasUserRestriction(String restriction, int userId) {
885 return getUserManager().hasUserRestriction(restriction, userId);
886 }
887
Michal Karpinski15486842019-04-25 17:33:42 +0100888 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
889 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
890 callingUid, callingPackage);
891 if (mode == AppOpsManager.MODE_DEFAULT) {
892 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
893 == PERMISSION_GRANTED;
894 }
895 return mode == AppOpsManager.MODE_ALLOWED;
896 }
897
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700898 @VisibleForTesting
899 protected void setRecentTasks(RecentTasks recentTasks) {
900 mRecentTasks = recentTasks;
901 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700902 }
903
904 RecentTasks getRecentTasks() {
905 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700906 }
907
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700908 ClientLifecycleManager getLifecycleManager() {
909 return mLifecycleManager;
910 }
911
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700912 ActivityStartController getActivityStartController() {
913 return mActivityStartController;
914 }
915
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700916 TaskChangeNotificationController getTaskChangeNotificationController() {
917 return mTaskChangeNotificationController;
918 }
919
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700920 LockTaskController getLockTaskController() {
921 return mLockTaskController;
922 }
923
Yunfan Chen75157d72018-07-27 14:47:21 +0900924 /**
925 * Return the global configuration used by the process corresponding to the input pid. This is
926 * usually the global configuration with some overrides specific to that process.
927 */
928 Configuration getGlobalConfigurationForCallingPid() {
929 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800930 return getGlobalConfigurationForPid(pid);
931 }
932
933 /**
934 * Return the global configuration used by the process corresponding to the given pid.
935 */
936 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900937 if (pid == MY_PID || pid < 0) {
938 return getGlobalConfiguration();
939 }
940 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100941 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 return app != null ? app.getConfiguration() : getGlobalConfiguration();
943 }
944 }
945
946 /**
947 * Return the device configuration info used by the process corresponding to the input pid.
948 * The value is consistent with the global configuration for the process.
949 */
950 @Override
951 public ConfigurationInfo getDeviceConfigurationInfo() {
952 ConfigurationInfo config = new ConfigurationInfo();
953 synchronized (mGlobalLock) {
954 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
955 config.reqTouchScreen = globalConfig.touchscreen;
956 config.reqKeyboardType = globalConfig.keyboard;
957 config.reqNavigation = globalConfig.navigation;
958 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
959 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
960 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
961 }
962 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
963 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
964 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
965 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700966 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900967 }
968 return config;
969 }
970
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700971 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700972 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700973 }
974
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700975 public static final class Lifecycle extends SystemService {
976 private final ActivityTaskManagerService mService;
977
978 public Lifecycle(Context context) {
979 super(context);
980 mService = new ActivityTaskManagerService(context);
981 }
982
983 @Override
984 public void onStart() {
985 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700987 }
988
Garfield Tan891146c2018-10-09 12:14:00 -0700989 @Override
990 public void onUnlockUser(int userId) {
991 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800992 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700993 }
994 }
995
996 @Override
997 public void onCleanupUser(int userId) {
998 synchronized (mService.getGlobalLock()) {
999 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1000 }
1001 }
1002
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001003 public ActivityTaskManagerService getService() {
1004 return mService;
1005 }
1006 }
1007
1008 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001009 public final int startActivity(IApplicationThread caller, String callingPackage,
1010 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1011 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1012 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1013 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1014 UserHandle.getCallingUserId());
1015 }
1016
1017 @Override
1018 public final int startActivities(IApplicationThread caller, String callingPackage,
1019 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1020 int userId) {
1021 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 enforceNotIsolatedCaller(reason);
1023 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001025 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1026 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1027 reason, null /* originatingPendingIntent */,
1028 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 }
1030
1031 @Override
1032 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1033 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1034 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1035 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1036 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1037 true /*validateIncomingUser*/);
1038 }
1039
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001040 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1042 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1043 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001044 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001046 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1048
1049 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001050 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 .setCaller(caller)
1052 .setCallingPackage(callingPackage)
1053 .setResolvedType(resolvedType)
1054 .setResultTo(resultTo)
1055 .setResultWho(resultWho)
1056 .setRequestCode(requestCode)
1057 .setStartFlags(startFlags)
1058 .setProfilerInfo(profilerInfo)
1059 .setActivityOptions(bOptions)
1060 .setMayWait(userId)
1061 .execute();
1062
1063 }
1064
1065 @Override
1066 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1067 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001068 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1069 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070 // Refuse possible leaked file descriptors
1071 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1072 throw new IllegalArgumentException("File descriptors passed in Intent");
1073 }
1074
1075 if (!(target instanceof PendingIntentRecord)) {
1076 throw new IllegalArgumentException("Bad PendingIntent object");
1077 }
1078
1079 PendingIntentRecord pir = (PendingIntentRecord)target;
1080
1081 synchronized (mGlobalLock) {
1082 // If this is coming from the currently resumed activity, it is
1083 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001084 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 if (stack.mResumedActivity != null &&
1086 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001087 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 }
1089 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001090 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 }
1093
1094 @Override
1095 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1096 Bundle bOptions) {
1097 // Refuse possible leaked file descriptors
1098 if (intent != null && intent.hasFileDescriptors()) {
1099 throw new IllegalArgumentException("File descriptors passed in Intent");
1100 }
1101 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1102
1103 synchronized (mGlobalLock) {
1104 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1105 if (r == null) {
1106 SafeActivityOptions.abort(options);
1107 return false;
1108 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001109 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001110 // The caller is not running... d'oh!
1111 SafeActivityOptions.abort(options);
1112 return false;
1113 }
1114 intent = new Intent(intent);
1115 // The caller is not allowed to change the data.
1116 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1117 // And we are resetting to find the next component...
1118 intent.setComponent(null);
1119
1120 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1121
1122 ActivityInfo aInfo = null;
1123 try {
1124 List<ResolveInfo> resolves =
1125 AppGlobals.getPackageManager().queryIntentActivities(
1126 intent, r.resolvedType,
1127 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1128 UserHandle.getCallingUserId()).getList();
1129
1130 // Look for the original activity in the list...
1131 final int N = resolves != null ? resolves.size() : 0;
1132 for (int i=0; i<N; i++) {
1133 ResolveInfo rInfo = resolves.get(i);
1134 if (rInfo.activityInfo.packageName.equals(r.packageName)
1135 && rInfo.activityInfo.name.equals(r.info.name)) {
1136 // We found the current one... the next matching is
1137 // after it.
1138 i++;
1139 if (i<N) {
1140 aInfo = resolves.get(i).activityInfo;
1141 }
1142 if (debug) {
1143 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1144 + "/" + r.info.name);
1145 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1146 ? "null" : aInfo.packageName + "/" + aInfo.name));
1147 }
1148 break;
1149 }
1150 }
1151 } catch (RemoteException e) {
1152 }
1153
1154 if (aInfo == null) {
1155 // Nobody who is next!
1156 SafeActivityOptions.abort(options);
1157 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1158 return false;
1159 }
1160
1161 intent.setComponent(new ComponentName(
1162 aInfo.applicationInfo.packageName, aInfo.name));
1163 intent.setFlags(intent.getFlags()&~(
1164 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1165 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1166 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1167 FLAG_ACTIVITY_NEW_TASK));
1168
1169 // Okay now we need to start the new activity, replacing the currently running activity.
1170 // This is a little tricky because we want to start the new one as if the current one is
1171 // finished, but not finish the current one first so that there is no flicker.
1172 // And thus...
1173 final boolean wasFinishing = r.finishing;
1174 r.finishing = true;
1175
1176 // Propagate reply information over to the new activity.
1177 final ActivityRecord resultTo = r.resultTo;
1178 final String resultWho = r.resultWho;
1179 final int requestCode = r.requestCode;
1180 r.resultTo = null;
1181 if (resultTo != null) {
1182 resultTo.removeResultsLocked(r, resultWho, requestCode);
1183 }
1184
1185 final long origId = Binder.clearCallingIdentity();
1186 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001187 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001188 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001189 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001190 .setResolvedType(r.resolvedType)
1191 .setActivityInfo(aInfo)
1192 .setResultTo(resultTo != null ? resultTo.appToken : null)
1193 .setResultWho(resultWho)
1194 .setRequestCode(requestCode)
1195 .setCallingPid(-1)
1196 .setCallingUid(r.launchedFromUid)
1197 .setCallingPackage(r.launchedFromPackage)
1198 .setRealCallingPid(-1)
1199 .setRealCallingUid(r.launchedFromUid)
1200 .setActivityOptions(options)
1201 .execute();
1202 Binder.restoreCallingIdentity(origId);
1203
1204 r.finishing = wasFinishing;
1205 if (res != ActivityManager.START_SUCCESS) {
1206 return false;
1207 }
1208 return true;
1209 }
1210 }
1211
1212 @Override
1213 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1214 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1215 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1216 final WaitResult res = new WaitResult();
1217 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001218 enforceNotIsolatedCaller("startActivityAndWait");
1219 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1220 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001222 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001223 .setCaller(caller)
1224 .setCallingPackage(callingPackage)
1225 .setResolvedType(resolvedType)
1226 .setResultTo(resultTo)
1227 .setResultWho(resultWho)
1228 .setRequestCode(requestCode)
1229 .setStartFlags(startFlags)
1230 .setActivityOptions(bOptions)
1231 .setMayWait(userId)
1232 .setProfilerInfo(profilerInfo)
1233 .setWaitResult(res)
1234 .execute();
1235 }
1236 return res;
1237 }
1238
1239 @Override
1240 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1241 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1242 int startFlags, Configuration config, Bundle bOptions, int userId) {
1243 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001244 enforceNotIsolatedCaller("startActivityWithConfig");
1245 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1246 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001248 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001249 .setCaller(caller)
1250 .setCallingPackage(callingPackage)
1251 .setResolvedType(resolvedType)
1252 .setResultTo(resultTo)
1253 .setResultWho(resultWho)
1254 .setRequestCode(requestCode)
1255 .setStartFlags(startFlags)
1256 .setGlobalConfiguration(config)
1257 .setActivityOptions(bOptions)
1258 .setMayWait(userId)
1259 .execute();
1260 }
1261 }
1262
Alison Cichowlas3e340502018-08-07 17:15:01 -04001263
1264 @Override
1265 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1266 int callingUid = Binder.getCallingUid();
1267 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1268 throw new SecurityException("Only the system process can request a permission token, "
1269 + "received request from uid: " + callingUid);
1270 }
1271 IBinder permissionToken = new Binder();
1272 synchronized (mGlobalLock) {
1273 mStartActivitySources.put(permissionToken, delegatorToken);
1274 }
1275
1276 Message expireMsg = PooledLambda.obtainMessage(
1277 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1278 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1279
1280 Message forgetMsg = PooledLambda.obtainMessage(
1281 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1282 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1283
1284 return permissionToken;
1285 }
1286
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 @Override
1288 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1289 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001290 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1291 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001293 // permission grants) as any app that may launch one of your own activities. So we only
1294 // allow this in two cases:
1295 // 1) The caller is an activity that is part of the core framework, and then only when it
1296 // is running as the system.
1297 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1298 // can only be requested by a system activity, which may then delegate this call to
1299 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001300 final ActivityRecord sourceRecord;
1301 final int targetUid;
1302 final String targetPackage;
1303 final boolean isResolver;
1304 synchronized (mGlobalLock) {
1305 if (resultTo == null) {
1306 throw new SecurityException("Must be called from an activity");
1307 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001308 final IBinder sourceToken;
1309 if (permissionToken != null) {
1310 // To even attempt to use a permissionToken, an app must also have this signature
1311 // permission.
1312 mAmInternal.enforceCallingPermission(
1313 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1314 "startActivityAsCaller");
1315 // If called with a permissionToken, we want the sourceRecord from the delegator
1316 // activity that requested this token.
1317 sourceToken = mStartActivitySources.remove(permissionToken);
1318 if (sourceToken == null) {
1319 // Invalid permissionToken, check if it recently expired.
1320 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1321 throw new SecurityException("Called with expired permission token: "
1322 + permissionToken);
1323 } else {
1324 throw new SecurityException("Called with invalid permission token: "
1325 + permissionToken);
1326 }
1327 }
1328 } else {
1329 // This method was called directly by the source.
1330 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001331 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001332
Wale Ogunwaled32da472018-11-16 07:19:28 -08001333 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001334 if (sourceRecord == null) {
1335 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 }
1337 if (sourceRecord.app == null) {
1338 throw new SecurityException("Called without a process attached to activity");
1339 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001340
1341 // Whether called directly or from a delegate, the source activity must be from the
1342 // android package.
1343 if (!sourceRecord.info.packageName.equals("android")) {
1344 throw new SecurityException("Must be called from an activity that is "
1345 + "declared in the android package");
1346 }
1347
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001348 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 // This is still okay, as long as this activity is running under the
1350 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001351 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001352 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001353 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 + " must be system uid or original calling uid "
1355 + sourceRecord.launchedFromUid);
1356 }
1357 }
1358 if (ignoreTargetSecurity) {
1359 if (intent.getComponent() == null) {
1360 throw new SecurityException(
1361 "Component must be specified with ignoreTargetSecurity");
1362 }
1363 if (intent.getSelector() != null) {
1364 throw new SecurityException(
1365 "Selector not allowed with ignoreTargetSecurity");
1366 }
1367 }
1368 targetUid = sourceRecord.launchedFromUid;
1369 targetPackage = sourceRecord.launchedFromPackage;
1370 isResolver = sourceRecord.isResolverOrChildActivity();
1371 }
1372
1373 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001374 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 }
1376
1377 // TODO: Switch to user app stacks here.
1378 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001379 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .setCallingUid(targetUid)
1381 .setCallingPackage(targetPackage)
1382 .setResolvedType(resolvedType)
1383 .setResultTo(resultTo)
1384 .setResultWho(resultWho)
1385 .setRequestCode(requestCode)
1386 .setStartFlags(startFlags)
1387 .setActivityOptions(bOptions)
1388 .setMayWait(userId)
1389 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1390 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001391 // The target may well be in the background, which would normally prevent it
1392 // from starting an activity. Here we definitely want the start to succeed.
1393 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .execute();
1395 } catch (SecurityException e) {
1396 // XXX need to figure out how to propagate to original app.
1397 // A SecurityException here is generally actually a fault of the original
1398 // calling activity (such as a fairly granting permissions), so propagate it
1399 // back to them.
1400 /*
1401 StringBuilder msg = new StringBuilder();
1402 msg.append("While launching");
1403 msg.append(intent.toString());
1404 msg.append(": ");
1405 msg.append(e.getMessage());
1406 */
1407 throw e;
1408 }
1409 }
1410
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1412 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1413 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1414 }
1415
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 @Override
1417 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1418 Intent intent, String resolvedType, IVoiceInteractionSession session,
1419 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1420 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001421 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 if (session == null || interactor == null) {
1423 throw new NullPointerException("null session or interactor");
1424 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001425 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001427 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 .setCallingUid(callingUid)
1429 .setCallingPackage(callingPackage)
1430 .setResolvedType(resolvedType)
1431 .setVoiceSession(session)
1432 .setVoiceInteractor(interactor)
1433 .setStartFlags(startFlags)
1434 .setProfilerInfo(profilerInfo)
1435 .setActivityOptions(bOptions)
1436 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001437 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .execute();
1439 }
1440
1441 @Override
1442 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1443 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001444 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1445 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001447 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 .setCallingUid(callingUid)
1449 .setCallingPackage(callingPackage)
1450 .setResolvedType(resolvedType)
1451 .setActivityOptions(bOptions)
1452 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001453 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .execute();
1455 }
1456
Riddle Hsu609a8e22019-06-27 16:46:29 -06001457 /**
1458 * Start the recents activity to perform the recents animation.
1459 *
1460 * @param intent The intent to start the recents activity.
1461 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1462 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001464 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1465 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001466 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001468 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 final long origId = Binder.clearCallingIdentity();
1470 try {
1471 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001472 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1473 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001474 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475
1476 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001477 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001478 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001480 if (recentsAnimationRunner == null) {
1481 anim.preloadRecentsActivity();
1482 } else {
1483 anim.startRecentsActivity(recentsAnimationRunner);
1484 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485 }
1486 } finally {
1487 Binder.restoreCallingIdentity(origId);
1488 }
1489 }
1490
1491 @Override
1492 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001493 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494 "startActivityFromRecents()");
1495
1496 final int callingPid = Binder.getCallingPid();
1497 final int callingUid = Binder.getCallingUid();
1498 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1499 final long origId = Binder.clearCallingIdentity();
1500 try {
1501 synchronized (mGlobalLock) {
1502 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1503 safeOptions);
1504 }
1505 } finally {
1506 Binder.restoreCallingIdentity(origId);
1507 }
1508 }
1509
1510 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001511 * Public API to check if the client is allowed to start an activity on specified display.
1512 *
1513 * If the target display is private or virtual, some restrictions will apply.
1514 *
1515 * @param displayId Target display id.
1516 * @param intent Intent used to launch the activity.
1517 * @param resolvedType The MIME type of the intent.
1518 * @param userId The id of the user for whom the call is made.
1519 * @return {@code true} if a call to start an activity on the target display should succeed and
1520 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1521 */
1522 @Override
1523 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1524 String resolvedType, int userId) {
1525 final int callingUid = Binder.getCallingUid();
1526 final int callingPid = Binder.getCallingPid();
1527 final long origId = Binder.clearCallingIdentity();
1528
1529 try {
1530 // Collect information about the target of the Intent.
1531 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1532 0 /* startFlags */, null /* profilerInfo */, userId,
1533 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1534 UserHandle.USER_NULL));
1535 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1536
1537 synchronized (mGlobalLock) {
1538 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1539 aInfo);
1540 }
1541 } finally {
1542 Binder.restoreCallingIdentity(origId);
1543 }
1544 }
1545
1546 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 * This is the internal entry point for handling Activity.finish().
1548 *
1549 * @param token The Binder token referencing the Activity we want to finish.
1550 * @param resultCode Result code, if any, from this Activity.
1551 * @param resultData Result data (Intent), if any, from this Activity.
1552 * @param finishTask Whether to finish the task associated with this Activity.
1553 *
1554 * @return Returns true if the activity successfully finished, or false if it is still running.
1555 */
1556 @Override
1557 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1558 int finishTask) {
1559 // Refuse possible leaked file descriptors
1560 if (resultData != null && resultData.hasFileDescriptors()) {
1561 throw new IllegalArgumentException("File descriptors passed in Intent");
1562 }
1563
1564 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001565 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 if (r == null) {
1567 return true;
1568 }
1569 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001570 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001571 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 if (rootR == null) {
1573 Slog.w(TAG, "Finishing task with all activities already finished");
1574 }
1575 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1576 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001577 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 return false;
1579 }
1580
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001581 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1582 // We should consolidate.
1583 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001585 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 if (next != null) {
1587 // ask watcher if this is allowed
1588 boolean resumeOK = true;
1589 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001590 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 Watchdog.getInstance().setActivityController(null);
1594 }
1595
1596 if (!resumeOK) {
1597 Slog.i(TAG, "Not finishing activity because controller resumed");
1598 return false;
1599 }
1600 }
1601 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001602
1603 // note down that the process has finished an activity and is in background activity
1604 // starts grace period
1605 if (r.app != null) {
1606 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1607 }
1608
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 final long origId = Binder.clearCallingIdentity();
1610 try {
1611 boolean res;
1612 final boolean finishWithRootActivity =
1613 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1614 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1615 || (finishWithRootActivity && r == rootR)) {
1616 // If requested, remove the task that is associated to this activity only if it
1617 // was the root activity in the task. The result code and data is ignored
1618 // because we don't support returning them across task boundaries. Also, to
1619 // keep backwards compatibility we remove the task from recents when finishing
1620 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001621 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 finishWithRootActivity, "finish-activity");
1623 if (!res) {
1624 Slog.i(TAG, "Removing task failed to finish activity");
1625 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001626 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001627 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001629 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001630 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 if (!res) {
1632 Slog.i(TAG, "Failed to finish by app-request");
1633 }
1634 }
1635 return res;
1636 } finally {
1637 Binder.restoreCallingIdentity(origId);
1638 }
1639 }
1640 }
1641
1642 @Override
1643 public boolean finishActivityAffinity(IBinder token) {
1644 synchronized (mGlobalLock) {
1645 final long origId = Binder.clearCallingIdentity();
1646 try {
1647 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1648 if (r == null) {
1649 return false;
1650 }
1651
1652 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1653 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001654 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 return false;
1656 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001657 r.finishActivityAffinity();
1658 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 } finally {
1660 Binder.restoreCallingIdentity(origId);
1661 }
1662 }
1663 }
1664
1665 @Override
1666 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1667 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001668 try {
1669 WindowProcessController proc = null;
1670 synchronized (mGlobalLock) {
1671 ActivityStack stack = ActivityRecord.getStackLocked(token);
1672 if (stack == null) {
1673 return;
1674 }
1675 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1676 false /* fromTimeout */, false /* processPausingActivities */, config);
1677 if (r != null) {
1678 proc = r.app;
1679 }
1680 if (stopProfiling && proc != null) {
1681 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 }
1683 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001684 } finally {
1685 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 }
1688
1689 @Override
1690 public final void activityResumed(IBinder token) {
1691 final long origId = Binder.clearCallingIdentity();
1692 synchronized (mGlobalLock) {
1693 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 }
1695 Binder.restoreCallingIdentity(origId);
1696 }
1697
1698 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001699 public final void activityTopResumedStateLost() {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1703 }
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 public final void activityPaused(IBinder token) {
1709 final long origId = Binder.clearCallingIdentity();
1710 synchronized (mGlobalLock) {
1711 ActivityStack stack = ActivityRecord.getStackLocked(token);
1712 if (stack != null) {
1713 stack.activityPausedLocked(token, false);
1714 }
1715 }
1716 Binder.restoreCallingIdentity(origId);
1717 }
1718
1719 @Override
1720 public final void activityStopped(IBinder token, Bundle icicle,
1721 PersistableBundle persistentState, CharSequence description) {
1722 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1723
1724 // Refuse possible leaked file descriptors
1725 if (icicle != null && icicle.hasFileDescriptors()) {
1726 throw new IllegalArgumentException("File descriptors passed in Bundle");
1727 }
1728
1729 final long origId = Binder.clearCallingIdentity();
1730
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001731 String restartingName = null;
1732 int restartingUid = 0;
1733 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001735 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001737 if (r.attachedToProcess()
1738 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1739 // The activity was requested to restart from
1740 // {@link #restartActivityProcessIfVisible}.
1741 restartingName = r.app.mName;
1742 restartingUid = r.app.mUid;
1743 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 r.activityStoppedLocked(icicle, persistentState, description);
1745 }
1746 }
1747
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001748 if (restartingName != null) {
1749 // In order to let the foreground activity can be restarted with its saved state from
1750 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1751 // until the activity reports stopped with the state. And the activity record will be
1752 // kept because the record state is restarting, then the activity will be restarted
1753 // immediately if it is still the top one.
1754 mStackSupervisor.removeRestartTimeouts(r);
1755 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1756 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758
1759 Binder.restoreCallingIdentity(origId);
1760 }
1761
1762 @Override
1763 public final void activityDestroyed(IBinder token) {
1764 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1765 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001766 final long origId = Binder.clearCallingIdentity();
1767 try {
1768 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1769 if (activity != null) {
1770 activity.destroyed("activityDestroyed");
1771 }
1772 } finally {
1773 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 }
1775 }
1776 }
1777
1778 @Override
1779 public final void activityRelaunched(IBinder token) {
1780 final long origId = Binder.clearCallingIdentity();
1781 synchronized (mGlobalLock) {
1782 mStackSupervisor.activityRelaunchedLocked(token);
1783 }
1784 Binder.restoreCallingIdentity(origId);
1785 }
1786
1787 public final void activitySlept(IBinder token) {
1788 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1789
1790 final long origId = Binder.clearCallingIdentity();
1791
1792 synchronized (mGlobalLock) {
1793 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1794 if (r != null) {
1795 mStackSupervisor.activitySleptLocked(r);
1796 }
1797 }
1798
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801
1802 @Override
1803 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1804 synchronized (mGlobalLock) {
1805 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1806 if (r == null) {
1807 return;
1808 }
1809 final long origId = Binder.clearCallingIdentity();
1810 try {
1811 r.setRequestedOrientation(requestedOrientation);
1812 } finally {
1813 Binder.restoreCallingIdentity(origId);
1814 }
1815 }
1816 }
1817
1818 @Override
1819 public int getRequestedOrientation(IBinder token) {
1820 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001821 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 return (r != null)
1823 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001824 }
1825 }
1826
1827 @Override
1828 public void setImmersive(IBinder token, boolean immersive) {
1829 synchronized (mGlobalLock) {
1830 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1831 if (r == null) {
1832 throw new IllegalArgumentException();
1833 }
1834 r.immersive = immersive;
1835
1836 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001837 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001838 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001839 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842 }
1843
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001844 void applyUpdateLockStateLocked(ActivityRecord r) {
1845 // Modifications to the UpdateLock state are done on our handler, outside
1846 // the activity manager's locks. The new state is determined based on the
1847 // state *now* of the relevant activity record. The object is passed to
1848 // the handler solely for logging detail, not to be consulted/modified.
1849 final boolean nextState = r != null && r.immersive;
1850 mH.post(() -> {
1851 if (mUpdateLock.isHeld() != nextState) {
1852 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1853 "Applying new update lock state '" + nextState + "' for " + r);
1854 if (nextState) {
1855 mUpdateLock.acquire();
1856 } else {
1857 mUpdateLock.release();
1858 }
1859 }
1860 });
1861 }
1862
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 @Override
1864 public boolean isImmersive(IBinder token) {
1865 synchronized (mGlobalLock) {
1866 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1867 if (r == null) {
1868 throw new IllegalArgumentException();
1869 }
1870 return r.immersive;
1871 }
1872 }
1873
1874 @Override
1875 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001878 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 return (r != null) ? r.immersive : false;
1880 }
1881 }
1882
1883 @Override
1884 public void overridePendingTransition(IBinder token, String packageName,
1885 int enterAnim, int exitAnim) {
1886 synchronized (mGlobalLock) {
1887 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1888 if (self == null) {
1889 return;
1890 }
1891
1892 final long origId = Binder.clearCallingIdentity();
1893
1894 if (self.isState(
1895 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001896 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001897 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 }
1899
1900 Binder.restoreCallingIdentity(origId);
1901 }
1902 }
1903
1904 @Override
1905 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001906 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001908 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001909 if (r == null) {
1910 return ActivityManager.COMPAT_MODE_UNKNOWN;
1911 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001912 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914 }
1915
1916 @Override
1917 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001922 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 if (r == null) {
1924 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1925 return;
1926 }
1927 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public int getLaunchedFromUid(IBinder activityToken) {
1934 ActivityRecord srec;
1935 synchronized (mGlobalLock) {
1936 srec = ActivityRecord.forTokenLocked(activityToken);
1937 }
1938 if (srec == null) {
1939 return -1;
1940 }
1941 return srec.launchedFromUid;
1942 }
1943
1944 @Override
1945 public String getLaunchedFromPackage(IBinder activityToken) {
1946 ActivityRecord srec;
1947 synchronized (mGlobalLock) {
1948 srec = ActivityRecord.forTokenLocked(activityToken);
1949 }
1950 if (srec == null) {
1951 return null;
1952 }
1953 return srec.launchedFromPackage;
1954 }
1955
1956 @Override
1957 public boolean convertFromTranslucent(IBinder token) {
1958 final long origId = Binder.clearCallingIdentity();
1959 try {
1960 synchronized (mGlobalLock) {
1961 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1962 if (r == null) {
1963 return false;
1964 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001965 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 }
1967 } finally {
1968 Binder.restoreCallingIdentity(origId);
1969 }
1970 }
1971
1972 @Override
1973 public boolean convertToTranslucent(IBinder token, Bundle options) {
1974 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1975 final long origId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
1978 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1979 if (r == null) {
1980 return false;
1981 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001982 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 int index = task.mActivities.lastIndexOf(r);
1984 if (index > 0) {
1985 ActivityRecord under = task.mActivities.get(index - 1);
1986 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1987 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001988 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990 } finally {
1991 Binder.restoreCallingIdentity(origId);
1992 }
1993 }
1994
1995 @Override
1996 public void notifyActivityDrawn(IBinder token) {
1997 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1998 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001999 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002001 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 }
2003 }
2004 }
2005
2006 @Override
2007 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2008 synchronized (mGlobalLock) {
2009 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2010 if (r == null) {
2011 return;
2012 }
2013 r.reportFullyDrawnLocked(restoredFromBundle);
2014 }
2015 }
2016
2017 @Override
2018 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2019 synchronized (mGlobalLock) {
2020 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2021 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2022 return stack.mDisplayId;
2023 }
2024 return DEFAULT_DISPLAY;
2025 }
2026 }
2027
2028 @Override
2029 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002030 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 long ident = Binder.clearCallingIdentity();
2032 try {
2033 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002034 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002036 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002037 }
2038 return null;
2039 }
2040 } finally {
2041 Binder.restoreCallingIdentity(ident);
2042 }
2043 }
2044
2045 @Override
2046 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002047 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002048 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2049 final long callingId = Binder.clearCallingIdentity();
2050 try {
2051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002052 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002053 if (stack == null) {
2054 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2055 return;
2056 }
2057 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002058 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 }
2061 }
2062 } finally {
2063 Binder.restoreCallingIdentity(callingId);
2064 }
2065 }
2066
2067 @Override
2068 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002069 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2071 final long callingId = Binder.clearCallingIdentity();
2072 try {
2073 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002074 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002075 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 if (task == null) {
2077 return;
2078 }
2079 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002080 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002081 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002082 }
2083 }
2084 } finally {
2085 Binder.restoreCallingIdentity(callingId);
2086 }
2087 }
2088
2089 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002090 public void restartActivityProcessIfVisible(IBinder activityToken) {
2091 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2092 final long callingId = Binder.clearCallingIdentity();
2093 try {
2094 synchronized (mGlobalLock) {
2095 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2096 if (r == null) {
2097 return;
2098 }
2099 r.restartProcessIfVisible();
2100 }
2101 } finally {
2102 Binder.restoreCallingIdentity(callingId);
2103 }
2104 }
2105
2106 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002108 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 synchronized (mGlobalLock) {
2110 final long ident = Binder.clearCallingIdentity();
2111 try {
2112 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2113 "remove-task");
2114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
2117 }
2118 }
2119
2120 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002121 public void removeAllVisibleRecentTasks() {
2122 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2123 synchronized (mGlobalLock) {
2124 final long ident = Binder.clearCallingIdentity();
2125 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002126 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002127 } finally {
2128 Binder.restoreCallingIdentity(ident);
2129 }
2130 }
2131 }
2132
2133 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2135 synchronized (mGlobalLock) {
2136 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2137 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002138 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139 }
2140 }
2141 return false;
2142 }
2143
2144 @Override
2145 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2146 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002147
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002148 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002149 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2150 if (r != null) {
2151 return r.getActivityStack().navigateUpToLocked(
2152 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002153 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002154 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 }
2156 }
2157
2158 /**
2159 * Attempts to move a task backwards in z-order (the order of activities within the task is
2160 * unchanged).
2161 *
2162 * There are several possible results of this call:
2163 * - if the task is locked, then we will show the lock toast
2164 * - if there is a task behind the provided task, then that task is made visible and resumed as
2165 * this task is moved to the back
2166 * - otherwise, if there are no other tasks in the stack:
2167 * - if this task is in the pinned stack, then we remove the stack completely, which will
2168 * have the effect of moving the task to the top or bottom of the fullscreen stack
2169 * (depending on whether it is visible)
2170 * - otherwise, we simply return home and hide this task
2171 *
2172 * @param token A reference to the activity we wish to move
2173 * @param nonRoot If false then this only works if the activity is the root
2174 * of a task; if true it will work for any activity in a task.
2175 * @return Returns true if the move completed, false if not.
2176 */
2177 @Override
2178 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002179 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 synchronized (mGlobalLock) {
2181 final long origId = Binder.clearCallingIdentity();
2182 try {
2183 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002184 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002185 if (task != null) {
2186 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2187 }
2188 } finally {
2189 Binder.restoreCallingIdentity(origId);
2190 }
2191 }
2192 return false;
2193 }
2194
2195 @Override
2196 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002197 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 long ident = Binder.clearCallingIdentity();
2199 Rect rect = new Rect();
2200 try {
2201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002202 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002203 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2204 if (task == null) {
2205 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2206 return rect;
2207 }
2208 if (task.getStack() != null) {
2209 // Return the bounds from window manager since it will be adjusted for various
2210 // things like the presense of a docked stack for tasks that aren't resizeable.
2211 task.getWindowContainerBounds(rect);
2212 } else {
2213 // Task isn't in window manager yet since it isn't associated with a stack.
2214 // Return the persist value from activity manager
2215 if (!task.matchParentBounds()) {
2216 rect.set(task.getBounds());
2217 } else if (task.mLastNonFullscreenBounds != null) {
2218 rect.set(task.mLastNonFullscreenBounds);
2219 }
2220 }
2221 }
2222 } finally {
2223 Binder.restoreCallingIdentity(ident);
2224 }
2225 return rect;
2226 }
2227
2228 @Override
2229 public ActivityManager.TaskDescription getTaskDescription(int id) {
2230 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002231 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002233 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002234 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2235 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002236 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 }
2238 }
2239 return null;
2240 }
2241
2242 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002243 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2244 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2245 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2246 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2247 return;
2248 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002249 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 synchronized (mGlobalLock) {
2251 final long ident = Binder.clearCallingIdentity();
2252 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002253 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002254 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 if (task == null) {
2256 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2257 return;
2258 }
2259
2260 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2261 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2262
2263 if (!task.isActivityTypeStandardOrUndefined()) {
2264 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2265 + " non-standard task " + taskId + " to windowing mode="
2266 + windowingMode);
2267 }
2268
2269 final ActivityStack stack = task.getStack();
2270 if (toTop) {
2271 stack.moveToFront("setTaskWindowingMode", task);
2272 }
2273 stack.setWindowingMode(windowingMode);
2274 } finally {
2275 Binder.restoreCallingIdentity(ident);
2276 }
2277 }
2278 }
2279
2280 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002282 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002283 ActivityRecord r = getCallingRecordLocked(token);
2284 return r != null ? r.info.packageName : null;
2285 }
2286 }
2287
2288 @Override
2289 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 ActivityRecord r = getCallingRecordLocked(token);
2292 return r != null ? r.intent.getComponent() : null;
2293 }
2294 }
2295
2296 private ActivityRecord getCallingRecordLocked(IBinder token) {
2297 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2298 if (r == null) {
2299 return null;
2300 }
2301 return r.resultTo;
2302 }
2303
2304 @Override
2305 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307
2308 synchronized (mGlobalLock) {
2309 final long origId = Binder.clearCallingIdentity();
2310 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002311 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 } finally {
2313 Binder.restoreCallingIdentity(origId);
2314 }
2315 }
2316 }
2317
Mark Renouf446251d2019-04-26 10:22:41 -04002318 @Override
2319 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2320 synchronized (mGlobalLock) {
2321 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2322 if (r == null) {
2323 return;
2324 }
2325 ActivityStack stack = r.getActivityStack();
2326 if (stack != null && stack.isSingleTaskInstance()) {
2327 // Single-task stacks are used for activities which are presented in floating
2328 // windows above full screen activities. Instead of directly finishing the
2329 // task, a task change listener is used to notify SystemUI so the action can be
2330 // handled specially.
2331 final TaskRecord task = r.getTaskRecord();
2332 mTaskChangeNotificationController
2333 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2334 } else {
2335 try {
2336 callback.requestFinish();
2337 } catch (RemoteException e) {
2338 Slog.e(TAG, "Failed to invoke request finish callback", e);
2339 }
2340 }
2341 }
2342 }
2343
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002344 /**
2345 * TODO: Add mController hook
2346 */
2347 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002348 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2349 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002350 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351
2352 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2353 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002354 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2355 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 }
2357 }
2358
Ricky Waiaca8a772019-04-04 16:01:06 +01002359 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2360 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002362
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 final int callingPid = Binder.getCallingPid();
2364 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002365 if (!isSameApp(callingUid, callingPackage)) {
2366 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2367 + Binder.getCallingPid() + " as package " + callingPackage;
2368 Slog.w(TAG, msg);
2369 throw new SecurityException(msg);
2370 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 SafeActivityOptions.abort(options);
2373 return;
2374 }
2375 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 WindowProcessController callerApp = null;
2377 if (appThread != null) {
2378 callerApp = getProcessController(appThread);
2379 }
2380 final ActivityStarter starter = getActivityStartController().obtainStarter(
2381 null /* intent */, "moveTaskToFront");
2382 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2383 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002384 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002385 return;
2386 }
2387 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002389 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 if (task == null) {
2391 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002392 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 return;
2394 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002395 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002397 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 return;
2399 }
2400 ActivityOptions realOptions = options != null
2401 ? options.getOptions(mStackSupervisor)
2402 : null;
2403 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2404 false /* forceNonResizable */);
2405
2406 final ActivityRecord topActivity = task.getTopActivity();
2407 if (topActivity != null) {
2408
2409 // We are reshowing a task, use a starting window to hide the initial draw delay
2410 // so the transition can start earlier.
2411 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2412 true /* taskSwitch */, fromRecents);
2413 }
2414 } finally {
2415 Binder.restoreCallingIdentity(origId);
2416 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002417 }
2418
Ricky Waiaca8a772019-04-04 16:01:06 +01002419 /**
2420 * Return true if callingUid is system, or packageName belongs to that callingUid.
2421 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002422 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002423 try {
2424 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2425 if (packageName == null) {
2426 return false;
2427 }
2428 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2429 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2430 UserHandle.getUserId(callingUid));
2431 return UserHandle.isSameApp(callingUid, uid);
2432 }
2433 } catch (RemoteException e) {
2434 // Should not happen
2435 }
2436 return true;
2437 }
2438
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002439 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2440 int callingPid, int callingUid, String name) {
2441 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2442 return true;
2443 }
2444
2445 if (getRecentTasks().isCallerRecents(sourceUid)) {
2446 return true;
2447 }
2448
2449 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2450 if (perm == PackageManager.PERMISSION_GRANTED) {
2451 return true;
2452 }
2453 if (checkAllowAppSwitchUid(sourceUid)) {
2454 return true;
2455 }
2456
2457 // If the actual IPC caller is different from the logical source, then
2458 // also see if they are allowed to control app switches.
2459 if (callingUid != -1 && callingUid != sourceUid) {
2460 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2461 if (perm == PackageManager.PERMISSION_GRANTED) {
2462 return true;
2463 }
2464 if (checkAllowAppSwitchUid(callingUid)) {
2465 return true;
2466 }
2467 }
2468
2469 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2470 return false;
2471 }
2472
2473 private boolean checkAllowAppSwitchUid(int uid) {
2474 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2475 if (types != null) {
2476 for (int i = types.size() - 1; i >= 0; i--) {
2477 if (types.valueAt(i).intValue() == uid) {
2478 return true;
2479 }
2480 }
2481 }
2482 return false;
2483 }
2484
2485 @Override
2486 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2487 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2488 "setActivityController()");
2489 synchronized (mGlobalLock) {
2490 mController = controller;
2491 mControllerIsAMonkey = imAMonkey;
2492 Watchdog.getInstance().setActivityController(controller);
2493 }
2494 }
2495
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002496 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002497 synchronized (mGlobalLock) {
2498 return mController != null && mControllerIsAMonkey;
2499 }
2500 }
2501
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002502 @Override
2503 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2504 synchronized (mGlobalLock) {
2505 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2506 }
2507 }
2508
2509 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002510 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2511 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2512 }
2513
2514 @Override
2515 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2516 @WindowConfiguration.ActivityType int ignoreActivityType,
2517 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2518 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002519 final int callingPid = Binder.getCallingPid();
2520 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002521 final int[] profileIds = getUserManager().getProfileIds(
2522 UserHandle.getUserId(callingUid), true);
2523 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2524 for (int i = 0; i < profileIds.length; i++) {
2525 callingProfileIds.add(profileIds[i]);
2526 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2528
2529 synchronized (mGlobalLock) {
2530 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2531
Nicholas Sauer0259e532019-08-30 08:24:55 -07002532 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002533 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002534 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002535 }
2536
2537 return list;
2538 }
2539
2540 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002541 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2542 synchronized (mGlobalLock) {
2543 final long origId = Binder.clearCallingIdentity();
2544 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2545 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002546 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547 }
2548 Binder.restoreCallingIdentity(origId);
2549 }
2550 }
2551
2552 @Override
2553 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002554 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002555 ActivityStack stack = ActivityRecord.getStackLocked(token);
2556 if (stack != null) {
2557 return stack.willActivityBeVisibleLocked(token);
2558 }
2559 return false;
2560 }
2561 }
2562
2563 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002565 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002566 synchronized (mGlobalLock) {
2567 final long ident = Binder.clearCallingIdentity();
2568 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002569 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002570 if (task == null) {
2571 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2572 return;
2573 }
2574
2575 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2576 + " to stackId=" + stackId + " toTop=" + toTop);
2577
Wale Ogunwaled32da472018-11-16 07:19:28 -08002578 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002579 if (stack == null) {
2580 throw new IllegalStateException(
2581 "moveTaskToStack: No stack for stackId=" + stackId);
2582 }
2583 if (!stack.isActivityTypeStandardOrUndefined()) {
2584 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2585 + taskId + " to stack " + stackId);
2586 }
2587 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002588 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002589 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2590 }
2591 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2592 "moveTaskToStack");
2593 } finally {
2594 Binder.restoreCallingIdentity(ident);
2595 }
2596 }
2597 }
2598
2599 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002600 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2601 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602
2603 final long ident = Binder.clearCallingIdentity();
2604 try {
2605 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002606 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2607 if (stack == null) {
2608 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2609 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002610 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002611 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2612 throw new IllegalArgumentException("Stack: " + stackId
2613 + " doesn't support animated resize.");
2614 }
2615 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2616 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 }
2618 } finally {
2619 Binder.restoreCallingIdentity(ident);
2620 }
2621 }
2622
wilsonshih5c4cf522019-01-25 09:03:47 +08002623 @Override
2624 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2625 int animationDuration) {
2626 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2627
2628 final long ident = Binder.clearCallingIdentity();
2629 try {
2630 synchronized (mGlobalLock) {
2631 if (xOffset == 0 && yOffset == 0) {
2632 return;
2633 }
2634 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2635 if (stack == null) {
2636 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2637 return;
2638 }
2639 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2640 throw new IllegalArgumentException("Stack: " + stackId
2641 + " doesn't support animated resize.");
2642 }
2643 final Rect destBounds = new Rect();
2644 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002645 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002646 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2647 return;
2648 }
2649 destBounds.offset(xOffset, yOffset);
2650 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2651 animationDuration, false /* fromFullscreen */);
2652 }
2653 } finally {
2654 Binder.restoreCallingIdentity(ident);
2655 }
2656 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002657 /**
2658 * Moves the specified task to the primary-split-screen stack.
2659 *
2660 * @param taskId Id of task to move.
2661 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2662 * exist already. See
2663 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2664 * and
2665 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2666 * @param toTop If the task and stack should be moved to the top.
2667 * @param animate Whether we should play an animation for the moving the task.
2668 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2669 * stack. Pass {@code null} to use default bounds.
2670 * @param showRecents If the recents activity should be shown on the other side of the task
2671 * going into split-screen mode.
2672 */
2673 @Override
2674 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2675 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002676 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002677 "setTaskWindowingModeSplitScreenPrimary()");
2678 synchronized (mGlobalLock) {
2679 final long ident = Binder.clearCallingIdentity();
2680 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002681 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002682 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002683 if (task == null) {
2684 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2685 return false;
2686 }
2687 if (DEBUG_STACK) Slog.d(TAG_STACK,
2688 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2689 + " to createMode=" + createMode + " toTop=" + toTop);
2690 if (!task.isActivityTypeStandardOrUndefined()) {
2691 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2692 + " non-standard task " + taskId + " to split-screen windowing mode");
2693 }
2694
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002695 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 final int windowingMode = task.getWindowingMode();
2697 final ActivityStack stack = task.getStack();
2698 if (toTop) {
2699 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2700 }
2701 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002702 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2703 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 return windowingMode != task.getWindowingMode();
2705 } finally {
2706 Binder.restoreCallingIdentity(ident);
2707 }
2708 }
2709 }
2710
2711 /**
2712 * Removes stacks in the input windowing modes from the system if they are of activity type
2713 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2714 */
2715 @Override
2716 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002717 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 "removeStacksInWindowingModes()");
2719
2720 synchronized (mGlobalLock) {
2721 final long ident = Binder.clearCallingIdentity();
2722 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
2729
2730 @Override
2731 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002732 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002733 "removeStacksWithActivityTypes()");
2734
2735 synchronized (mGlobalLock) {
2736 final long ident = Binder.clearCallingIdentity();
2737 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002738 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 } finally {
2740 Binder.restoreCallingIdentity(ident);
2741 }
2742 }
2743 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744
2745 @Override
2746 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2747 int userId) {
2748 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2750 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 final boolean detailed = checkGetTasksPermission(
2753 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2754 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 == PackageManager.PERMISSION_GRANTED;
2756
2757 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002758 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002759 callingUid);
2760 }
2761 }
2762
2763 @Override
2764 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002765 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 long ident = Binder.clearCallingIdentity();
2767 try {
2768 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002769 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770 }
2771 } finally {
2772 Binder.restoreCallingIdentity(ident);
2773 }
2774 }
2775
2776 @Override
2777 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002778 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 long ident = Binder.clearCallingIdentity();
2780 try {
2781 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002782 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 }
2784 } finally {
2785 Binder.restoreCallingIdentity(ident);
2786 }
2787 }
2788
2789 @Override
2790 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002791 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 final long callingUid = Binder.getCallingUid();
2793 final long origId = Binder.clearCallingIdentity();
2794 try {
2795 synchronized (mGlobalLock) {
2796 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002797 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2799 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2800 }
2801 } finally {
2802 Binder.restoreCallingIdentity(origId);
2803 }
2804 }
2805
2806 @Override
2807 public void startLockTaskModeByToken(IBinder token) {
2808 synchronized (mGlobalLock) {
2809 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2810 if (r == null) {
2811 return;
2812 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002813 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 }
2815 }
2816
2817 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002818 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002819 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002820 // This makes inner call to look as if it was initiated by system.
2821 long ident = Binder.clearCallingIdentity();
2822 try {
2823 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002824 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002825 MATCH_TASK_IN_STACKS_ONLY);
2826 if (task == null) {
2827 return;
2828 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829
2830 // When starting lock task mode the stack must be in front and focused
2831 task.getStack().moveToFront("startSystemLockTaskMode");
2832 startLockTaskModeLocked(task, true /* isSystemCaller */);
2833 }
2834 } finally {
2835 Binder.restoreCallingIdentity(ident);
2836 }
2837 }
2838
2839 @Override
2840 public void stopLockTaskModeByToken(IBinder token) {
2841 synchronized (mGlobalLock) {
2842 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2843 if (r == null) {
2844 return;
2845 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002846 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002847 }
2848 }
2849
2850 /**
2851 * This API should be called by SystemUI only when user perform certain action to dismiss
2852 * lock task mode. We should only dismiss pinned lock task mode in this case.
2853 */
2854 @Override
2855 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002856 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2858 }
2859
2860 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2861 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2862 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2863 return;
2864 }
2865
Wale Ogunwaled32da472018-11-16 07:19:28 -08002866 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 if (stack == null || task != stack.topTask()) {
2868 throw new IllegalArgumentException("Invalid task, not in foreground");
2869 }
2870
2871 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2872 // system or a specific app.
2873 // * System-initiated requests will only start the pinned mode (screen pinning)
2874 // * App-initiated requests
2875 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2876 // - will start the pinned mode, otherwise
2877 final int callingUid = Binder.getCallingUid();
2878 long ident = Binder.clearCallingIdentity();
2879 try {
2880 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002881 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002883 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 } finally {
2885 Binder.restoreCallingIdentity(ident);
2886 }
2887 }
2888
2889 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2890 final int callingUid = Binder.getCallingUid();
2891 long ident = Binder.clearCallingIdentity();
2892 try {
2893 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002894 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 }
2896 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2897 // task and jumping straight into a call in the case of emergency call back.
2898 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2899 if (tm != null) {
2900 tm.showInCallScreen(false);
2901 }
2902 } finally {
2903 Binder.restoreCallingIdentity(ident);
2904 }
2905 }
2906
2907 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002908 public void updateLockTaskPackages(int userId, String[] packages) {
2909 final int callingUid = Binder.getCallingUid();
2910 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2911 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2912 "updateLockTaskPackages()");
2913 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002914 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002915 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2916 + Arrays.toString(packages));
2917 getLockTaskController().updateLockTaskPackages(userId, packages);
2918 }
2919 }
2920
2921 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 public boolean isInLockTaskMode() {
2923 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2924 }
2925
2926 @Override
2927 public int getLockTaskModeState() {
2928 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002929 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 }
2931 }
2932
2933 @Override
2934 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2935 synchronized (mGlobalLock) {
2936 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2937 if (r != null) {
2938 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002939 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002941 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 }
2943 }
2944 }
2945
2946 @Override
2947 public Bundle getActivityOptions(IBinder token) {
2948 final long origId = Binder.clearCallingIdentity();
2949 try {
2950 synchronized (mGlobalLock) {
2951 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2952 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002953 final ActivityOptions activityOptions = r.takeOptionsLocked(
2954 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 return activityOptions == null ? null : activityOptions.toBundle();
2956 }
2957 return null;
2958 }
2959 } finally {
2960 Binder.restoreCallingIdentity(origId);
2961 }
2962 }
2963
2964 @Override
2965 public List<IBinder> getAppTasks(String callingPackage) {
2966 int callingUid = Binder.getCallingUid();
2967 long ident = Binder.clearCallingIdentity();
2968 try {
2969 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002970 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 }
2972 } finally {
2973 Binder.restoreCallingIdentity(ident);
2974 }
2975 }
2976
2977 @Override
2978 public void finishVoiceTask(IVoiceInteractionSession session) {
2979 synchronized (mGlobalLock) {
2980 final long origId = Binder.clearCallingIdentity();
2981 try {
2982 // TODO: VI Consider treating local voice interactions and voice tasks
2983 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002984 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 } finally {
2986 Binder.restoreCallingIdentity(origId);
2987 }
2988 }
2989
2990 }
2991
2992 @Override
2993 public boolean isTopOfTask(IBinder token) {
2994 synchronized (mGlobalLock) {
2995 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002996 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 }
2998 }
2999
3000 @Override
3001 public void notifyLaunchTaskBehindComplete(IBinder token) {
3002 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3003 }
3004
3005 @Override
3006 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003007 mH.post(() -> {
3008 synchronized (mGlobalLock) {
3009 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003010 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003011 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003012 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003013 } catch (RemoteException e) {
3014 }
3015 }
3016 }
3017
3018 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003019 }
3020
3021 /** Called from an app when assist data is ready. */
3022 @Override
3023 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3024 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003025 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 synchronized (pae) {
3027 pae.result = extras;
3028 pae.structure = structure;
3029 pae.content = content;
3030 if (referrer != null) {
3031 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3032 }
3033 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003034 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003035 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003036 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 structure.setHomeActivity(pae.isHome);
3038 }
3039 pae.haveResult = true;
3040 pae.notifyAll();
3041 if (pae.intent == null && pae.receiver == null) {
3042 // Caller is just waiting for the result.
3043 return;
3044 }
3045 }
3046 // We are now ready to launch the assist activity.
3047 IAssistDataReceiver sendReceiver = null;
3048 Bundle sendBundle = null;
3049 synchronized (mGlobalLock) {
3050 buildAssistBundleLocked(pae, extras);
3051 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003052 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 if (!exists) {
3054 // Timed out.
3055 return;
3056 }
3057
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003058 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 // Caller wants result sent back to them.
3060 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003061 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003062 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003063 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3064 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3066 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3067 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3068 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3069 }
3070 }
3071 if (sendReceiver != null) {
3072 try {
3073 sendReceiver.onHandleAssistData(sendBundle);
3074 } catch (RemoteException e) {
3075 }
3076 return;
3077 }
3078
3079 final long ident = Binder.clearCallingIdentity();
3080 try {
3081 if (TextUtils.equals(pae.intent.getAction(),
3082 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003083 // Start voice interaction through VoiceInteractionManagerService.
3084 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3085 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 } else {
3087 pae.intent.replaceExtras(pae.extras);
3088 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3089 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3090 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003091 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092
3093 try {
3094 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3095 } catch (ActivityNotFoundException e) {
3096 Slog.w(TAG, "No activity to handle assist action.", e);
3097 }
3098 }
3099 } finally {
3100 Binder.restoreCallingIdentity(ident);
3101 }
3102 }
3103
3104 @Override
3105 public int addAppTask(IBinder activityToken, Intent intent,
3106 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3107 final int callingUid = Binder.getCallingUid();
3108 final long callingIdent = Binder.clearCallingIdentity();
3109
3110 try {
3111 synchronized (mGlobalLock) {
3112 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3113 if (r == null) {
3114 throw new IllegalArgumentException("Activity does not exist; token="
3115 + activityToken);
3116 }
3117 ComponentName comp = intent.getComponent();
3118 if (comp == null) {
3119 throw new IllegalArgumentException("Intent " + intent
3120 + " must specify explicit component");
3121 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 if (thumbnail.getWidth() != mThumbnailWidth
3123 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 throw new IllegalArgumentException("Bad thumbnail size: got "
3125 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003126 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 }
3128 if (intent.getSelector() != null) {
3129 intent.setSelector(null);
3130 }
3131 if (intent.getSourceBounds() != null) {
3132 intent.setSourceBounds(null);
3133 }
3134 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3135 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3136 // The caller has added this as an auto-remove task... that makes no
3137 // sense, so turn off auto-remove.
3138 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3139 }
3140 }
3141 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3142 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3143 if (ainfo.applicationInfo.uid != callingUid) {
3144 throw new SecurityException(
3145 "Can't add task for another application: target uid="
3146 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3147 }
3148
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003149 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003151 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003153 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 // The app has too many tasks already and we can't add any more
3155 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3156 return INVALID_TASK_ID;
3157 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003158 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159
3160 // TODO: Send the thumbnail to WM to store it.
3161
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003162 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 }
3164 } finally {
3165 Binder.restoreCallingIdentity(callingIdent);
3166 }
3167 }
3168
3169 @Override
3170 public Point getAppTaskThumbnailSize() {
3171 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003172 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 }
3174 }
3175
3176 @Override
3177 public void setTaskResizeable(int taskId, int resizeableMode) {
3178 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003179 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3181 if (task == null) {
3182 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3183 return;
3184 }
3185 task.setResizeMode(resizeableMode);
3186 }
3187 }
3188
3189 @Override
3190 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003191 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 long ident = Binder.clearCallingIdentity();
3193 try {
3194 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003195 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003196 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 if (task == null) {
3198 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3199 return;
3200 }
3201 // Place the task in the right stack if it isn't there already based on
3202 // the requested bounds.
3203 // The stack transition logic is:
3204 // - a null bounds on a freeform task moves that task to fullscreen
3205 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3206 // that task to freeform
3207 // - otherwise the task is not moved
3208 ActivityStack stack = task.getStack();
3209 if (!task.getWindowConfiguration().canResizeTask()) {
3210 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3211 }
3212 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3213 stack = stack.getDisplay().getOrCreateStack(
3214 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3215 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3216 stack = stack.getDisplay().getOrCreateStack(
3217 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3218 }
3219
3220 // Reparent the task to the right stack if necessary
3221 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3222 if (stack != task.getStack()) {
3223 // Defer resume until the task is resized below
3224 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3225 DEFER_RESUME, "resizeTask");
3226 preserveWindow = false;
3227 }
3228
3229 // After reparenting (which only resizes the task to the stack bounds), resize the
3230 // task to the actual bounds provided
3231 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3232 }
3233 } finally {
3234 Binder.restoreCallingIdentity(ident);
3235 }
3236 }
3237
3238 @Override
3239 public boolean releaseActivityInstance(IBinder token) {
3240 synchronized (mGlobalLock) {
3241 final long origId = Binder.clearCallingIdentity();
3242 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003243 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3244 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 return false;
3246 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003247 r.destroyImmediately(true /* removeFromApp */, "app-req");
3248 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 } finally {
3250 Binder.restoreCallingIdentity(origId);
3251 }
3252 }
3253 }
3254
3255 @Override
3256 public void releaseSomeActivities(IApplicationThread appInt) {
3257 synchronized (mGlobalLock) {
3258 final long origId = Binder.clearCallingIdentity();
3259 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003260 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003261 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 } finally {
3263 Binder.restoreCallingIdentity(origId);
3264 }
3265 }
3266 }
3267
3268 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003269 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003270 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 != PackageManager.PERMISSION_GRANTED) {
3272 throw new SecurityException("Requires permission "
3273 + android.Manifest.permission.DEVICE_POWER);
3274 }
3275
3276 synchronized (mGlobalLock) {
3277 long ident = Binder.clearCallingIdentity();
3278 if (mKeyguardShown != keyguardShowing) {
3279 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003280 final Message msg = PooledLambda.obtainMessage(
3281 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3282 keyguardShowing);
3283 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 }
3285 try {
wilsonshih177261f2019-02-22 12:02:18 +08003286 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003287 } finally {
3288 Binder.restoreCallingIdentity(ident);
3289 }
3290 }
3291
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 mH.post(() -> {
3293 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3294 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3295 }
3296 });
3297 }
3298
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003299 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003300 mH.post(() -> {
3301 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3302 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3303 }
3304 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 }
3306
3307 @Override
3308 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003309 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3310 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311
3312 final File passedIconFile = new File(filePath);
3313 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3314 passedIconFile.getName());
3315 if (!legitIconFile.getPath().equals(filePath)
3316 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3317 throw new IllegalArgumentException("Bad file path: " + filePath
3318 + " passed for userId " + userId);
3319 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003320 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 }
3322
3323 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003324 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3326 final ActivityOptions activityOptions = safeOptions != null
3327 ? safeOptions.getOptions(mStackSupervisor)
3328 : null;
3329 if (activityOptions == null
3330 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3331 || activityOptions.getCustomInPlaceResId() == 0) {
3332 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3333 "with valid animation");
3334 }
lumark588a3e82018-07-20 18:53:54 +08003335 // Get top display of front most application.
3336 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3337 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003338 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3339 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3340 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003341 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003342 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003343 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 }
3345
3346 @Override
3347 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003348 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 synchronized (mGlobalLock) {
3350 final long ident = Binder.clearCallingIdentity();
3351 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003352 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 if (stack == null) {
3354 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3355 return;
3356 }
3357 if (!stack.isActivityTypeStandardOrUndefined()) {
3358 throw new IllegalArgumentException(
3359 "Removing non-standard stack is not allowed.");
3360 }
3361 mStackSupervisor.removeStack(stack);
3362 } finally {
3363 Binder.restoreCallingIdentity(ident);
3364 }
3365 }
3366 }
3367
3368 @Override
3369 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371
3372 synchronized (mGlobalLock) {
3373 final long ident = Binder.clearCallingIdentity();
3374 try {
3375 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3376 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003377 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } finally {
3379 Binder.restoreCallingIdentity(ident);
3380 }
3381 }
3382 }
3383
3384 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003385 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 synchronized (mGlobalLock) {
3387 long ident = Binder.clearCallingIdentity();
3388 try {
3389 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3390 if (r == null) {
3391 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003392 "toggleFreeformWindowingMode: No activity record matching token="
3393 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 }
3395
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003396 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003397 if (stack == null) {
3398 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3399 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 }
3401
Yunfan Chend967af82019-01-17 18:30:18 +09003402 if (!stack.inFreeformWindowingMode()
3403 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3404 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3405 + "toggle between fullscreen and freeform.");
3406 }
3407
3408 if (stack.inFreeformWindowingMode()) {
3409 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003410 } else if (stack.getParent().inFreeformWindowingMode()) {
3411 // If the window is on a freeform display, set it to undefined. It will be
3412 // resolved to freeform and it can adjust windowing mode when the display mode
3413 // changes in runtime.
3414 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003415 } else {
3416 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3417 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 } finally {
3419 Binder.restoreCallingIdentity(ident);
3420 }
3421 }
3422 }
3423
3424 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3425 @Override
3426 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003427 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003429 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 }
3431
3432 /** Unregister a task stack listener so that it stops receiving callbacks. */
3433 @Override
3434 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003437 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 @Override
3441 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3442 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3443 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3444 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3445 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3446 }
3447
3448 @Override
3449 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3450 IBinder activityToken, int flags) {
3451 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3452 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3453 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3454 }
3455
3456 @Override
3457 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3458 Bundle args) {
3459 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3460 true /* focused */, true /* newSessionId */, userHandle, args,
3461 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3462 }
3463
3464 @Override
3465 public Bundle getAssistContextExtras(int requestType) {
3466 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3467 null, null, true /* focused */, true /* newSessionId */,
3468 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3469 if (pae == null) {
3470 return null;
3471 }
3472 synchronized (pae) {
3473 while (!pae.haveResult) {
3474 try {
3475 pae.wait();
3476 } catch (InterruptedException e) {
3477 }
3478 }
3479 }
3480 synchronized (mGlobalLock) {
3481 buildAssistBundleLocked(pae, pae.result);
3482 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003483 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485 return pae.extras;
3486 }
3487
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003488 /**
3489 * Binder IPC calls go through the public entry point.
3490 * This can be called with or without the global lock held.
3491 */
3492 private static int checkCallingPermission(String permission) {
3493 return checkPermission(
3494 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3495 }
3496
3497 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003498 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003499 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3500 mAmInternal.enforceCallingPermission(permission, func);
3501 }
3502 }
3503
3504 @VisibleForTesting
3505 int checkGetTasksPermission(String permission, int pid, int uid) {
3506 return checkPermission(permission, pid, uid);
3507 }
3508
3509 static int checkPermission(String permission, int pid, int uid) {
3510 if (permission == null) {
3511 return PackageManager.PERMISSION_DENIED;
3512 }
3513 return checkComponentPermission(permission, pid, uid, -1, true);
3514 }
3515
Wale Ogunwale214f3482018-10-04 11:00:47 -07003516 public static int checkComponentPermission(String permission, int pid, int uid,
3517 int owningUid, boolean exported) {
3518 return ActivityManagerService.checkComponentPermission(
3519 permission, pid, uid, owningUid, exported);
3520 }
3521
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003522 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3523 if (getRecentTasks().isCallerRecents(callingUid)) {
3524 // Always allow the recents component to get tasks
3525 return true;
3526 }
3527
3528 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3529 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3530 if (!allowed) {
3531 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3532 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3533 // Temporary compatibility: some existing apps on the system image may
3534 // still be requesting the old permission and not switched to the new
3535 // one; if so, we'll still allow them full access. This means we need
3536 // to see if they are holding the old permission and are a system app.
3537 try {
3538 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3539 allowed = true;
3540 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3541 + " is using old GET_TASKS but privileged; allowing");
3542 }
3543 } catch (RemoteException e) {
3544 }
3545 }
3546 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3547 + " does not hold REAL_GET_TASKS; limiting output");
3548 }
3549 return allowed;
3550 }
3551
Nicholas Sauer0259e532019-08-30 08:24:55 -07003552 boolean isCrossUserAllowed(int pid, int uid) {
3553 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3554 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3555 }
3556
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3558 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3559 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3560 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003561 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 "enqueueAssistContext()");
3563
3564 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003565 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 if (activity == null) {
3567 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3568 return null;
3569 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003570 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3572 return null;
3573 }
3574 if (focused) {
3575 if (activityToken != null) {
3576 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3577 if (activity != caller) {
3578 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3579 + " is not current top " + activity);
3580 return null;
3581 }
3582 }
3583 } else {
3584 activity = ActivityRecord.forTokenLocked(activityToken);
3585 if (activity == null) {
3586 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3587 + " couldn't be found");
3588 return null;
3589 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003590 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3592 return null;
3593 }
3594 }
3595
3596 PendingAssistExtras pae;
3597 Bundle extras = new Bundle();
3598 if (args != null) {
3599 extras.putAll(args);
3600 }
3601 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003602 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603
3604 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3605 userHandle);
3606 pae.isHome = activity.isActivityTypeHome();
3607
3608 // Increment the sessionId if necessary
3609 if (newSessionId) {
3610 mViSessionId++;
3611 }
3612 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003613 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3614 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003615 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003616 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003617 } catch (RemoteException e) {
3618 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3619 return null;
3620 }
3621 return pae;
3622 }
3623 }
3624
3625 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3626 if (result != null) {
3627 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3628 }
3629 if (pae.hint != null) {
3630 pae.extras.putBoolean(pae.hint, true);
3631 }
3632 }
3633
3634 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3635 IAssistDataReceiver receiver;
3636 synchronized (mGlobalLock) {
3637 mPendingAssistExtras.remove(pae);
3638 receiver = pae.receiver;
3639 }
3640 if (receiver != null) {
3641 // Caller wants result sent back to them.
3642 Bundle sendBundle = new Bundle();
3643 // At least return the receiver extras
3644 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3645 try {
3646 pae.receiver.onHandleAssistData(sendBundle);
3647 } catch (RemoteException e) {
3648 }
3649 }
3650 }
3651
3652 public class PendingAssistExtras extends Binder implements Runnable {
3653 public final ActivityRecord activity;
3654 public boolean isHome;
3655 public final Bundle extras;
3656 public final Intent intent;
3657 public final String hint;
3658 public final IAssistDataReceiver receiver;
3659 public final int userHandle;
3660 public boolean haveResult = false;
3661 public Bundle result = null;
3662 public AssistStructure structure = null;
3663 public AssistContent content = null;
3664 public Bundle receiverExtras;
3665
3666 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3667 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3668 int _userHandle) {
3669 activity = _activity;
3670 extras = _extras;
3671 intent = _intent;
3672 hint = _hint;
3673 receiver = _receiver;
3674 receiverExtras = _receiverExtras;
3675 userHandle = _userHandle;
3676 }
3677
3678 @Override
3679 public void run() {
3680 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3681 synchronized (this) {
3682 haveResult = true;
3683 notifyAll();
3684 }
3685 pendingAssistExtrasTimedOut(this);
3686 }
3687 }
3688
3689 @Override
3690 public boolean isAssistDataAllowedOnCurrentActivity() {
3691 int userId;
3692 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003693 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3695 return false;
3696 }
3697
3698 final ActivityRecord activity = focusedStack.getTopActivity();
3699 if (activity == null) {
3700 return false;
3701 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003702 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 }
3704 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3705 }
3706
3707 @Override
3708 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3709 long ident = Binder.clearCallingIdentity();
3710 try {
3711 synchronized (mGlobalLock) {
3712 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003713 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 if (top != caller) {
3715 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3716 + " is not current top " + top);
3717 return false;
3718 }
3719 if (!top.nowVisible) {
3720 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3721 + " is not visible");
3722 return false;
3723 }
3724 }
3725 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3726 token);
3727 } finally {
3728 Binder.restoreCallingIdentity(ident);
3729 }
3730 }
3731
3732 @Override
3733 public boolean isRootVoiceInteraction(IBinder token) {
3734 synchronized (mGlobalLock) {
3735 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3736 if (r == null) {
3737 return false;
3738 }
3739 return r.rootVoiceInteraction;
3740 }
3741 }
3742
Wale Ogunwalef6733932018-06-27 05:14:34 -07003743 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3744 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3745 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3746 if (activityToCallback == null) return;
3747 activityToCallback.setVoiceSessionLocked(voiceSession);
3748
3749 // Inform the activity
3750 try {
3751 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3752 voiceInteractor);
3753 long token = Binder.clearCallingIdentity();
3754 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003755 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003756 } finally {
3757 Binder.restoreCallingIdentity(token);
3758 }
3759 // TODO: VI Should we cache the activity so that it's easier to find later
3760 // rather than scan through all the stacks and activities?
3761 } catch (RemoteException re) {
3762 activityToCallback.clearVoiceSessionLocked();
3763 // TODO: VI Should this terminate the voice session?
3764 }
3765 }
3766
3767 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3768 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3769 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3770 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3771 boolean wasRunningVoice = mRunningVoice != null;
3772 mRunningVoice = session;
3773 if (!wasRunningVoice) {
3774 mVoiceWakeLock.acquire();
3775 updateSleepIfNeededLocked();
3776 }
3777 }
3778 }
3779
3780 void finishRunningVoiceLocked() {
3781 if (mRunningVoice != null) {
3782 mRunningVoice = null;
3783 mVoiceWakeLock.release();
3784 updateSleepIfNeededLocked();
3785 }
3786 }
3787
3788 @Override
3789 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3790 synchronized (mGlobalLock) {
3791 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3792 if (keepAwake) {
3793 mVoiceWakeLock.acquire();
3794 } else {
3795 mVoiceWakeLock.release();
3796 }
3797 }
3798 }
3799 }
3800
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 @Override
3802 public ComponentName getActivityClassForToken(IBinder token) {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return null;
3807 }
3808 return r.intent.getComponent();
3809 }
3810 }
3811
3812 @Override
3813 public String getPackageForToken(IBinder token) {
3814 synchronized (mGlobalLock) {
3815 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3816 if (r == null) {
3817 return null;
3818 }
3819 return r.packageName;
3820 }
3821 }
3822
3823 @Override
3824 public void showLockTaskEscapeMessage(IBinder token) {
3825 synchronized (mGlobalLock) {
3826 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3827 if (r == null) {
3828 return;
3829 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003830 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 }
3832 }
3833
3834 @Override
3835 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003836 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 final long token = Binder.clearCallingIdentity();
3838 try {
3839 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003840 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(token);
3844 }
3845 }
3846
3847 /**
3848 * Try to place task to provided position. The final position might be different depending on
3849 * current user and stacks state. The task will be moved to target stack if it's currently in
3850 * different stack.
3851 */
3852 @Override
3853 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003854 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 synchronized (mGlobalLock) {
3856 long ident = Binder.clearCallingIdentity();
3857 try {
3858 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3859 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003860 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861 if (task == null) {
3862 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3863 + taskId);
3864 }
3865
Wale Ogunwaled32da472018-11-16 07:19:28 -08003866 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003867
3868 if (stack == null) {
3869 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3870 + stackId);
3871 }
3872 if (!stack.isActivityTypeStandardOrUndefined()) {
3873 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3874 + " the position of task " + taskId + " in/to non-standard stack");
3875 }
3876
3877 // TODO: Have the callers of this API call a separate reparent method if that is
3878 // what they intended to do vs. having this method also do reparenting.
3879 if (task.getStack() == stack) {
3880 // Change position in current stack.
3881 stack.positionChildAt(task, position);
3882 } else {
3883 // Reparent to new stack.
3884 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3885 !DEFER_RESUME, "positionTaskInStack");
3886 }
3887 } finally {
3888 Binder.restoreCallingIdentity(ident);
3889 }
3890 }
3891 }
3892
3893 @Override
3894 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3895 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3896 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003897 + Arrays.toString(horizontalSizeConfiguration) + " "
3898 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003899 synchronized (mGlobalLock) {
3900 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3901 if (record == null) {
3902 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3903 + "found for: " + token);
3904 }
3905 record.setSizeConfigurations(horizontalSizeConfiguration,
3906 verticalSizeConfigurations, smallestSizeConfigurations);
3907 }
3908 }
3909
3910 /**
3911 * Dismisses split-screen multi-window mode.
3912 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3913 */
3914 @Override
3915 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003916 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3918 final long ident = Binder.clearCallingIdentity();
3919 try {
3920 synchronized (mGlobalLock) {
3921 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003922 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 if (stack == null) {
3924 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3925 return;
3926 }
3927
3928 if (toTop) {
3929 // Caller wants the current split-screen primary stack to be the top stack after
3930 // it goes fullscreen, so move it to the front.
3931 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003932 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003934 // stack after it goes fullscreen, so we move the focus to the top-most
3935 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3937 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3938 if (otherStack != null) {
3939 otherStack.moveToFront("dismissSplitScreenMode_other");
3940 }
3941 }
3942
Evan Rosky10475742018-09-05 19:02:48 -07003943 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 }
3945 } finally {
3946 Binder.restoreCallingIdentity(ident);
3947 }
3948 }
3949
3950 /**
3951 * Dismisses Pip
3952 * @param animate True if the dismissal should be animated.
3953 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3954 * default animation duration should be used.
3955 */
3956 @Override
3957 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003958 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 final long ident = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003962 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003963 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 if (stack == null) {
3965 Slog.w(TAG, "dismissPip: pinned stack not found.");
3966 return;
3967 }
3968 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3969 throw new IllegalArgumentException("Stack: " + stack
3970 + " doesn't support animated resize.");
3971 }
3972 if (animate) {
3973 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3974 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3975 } else {
3976 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3977 }
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983
3984 @Override
3985 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 synchronized (mGlobalLock) {
3988 mSuppressResizeConfigChanges = suppress;
3989 }
3990 }
3991
3992 /**
3993 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3994 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3995 * activity and clearing the task at the same time.
3996 */
3997 @Override
3998 // TODO: API should just be about changing windowing modes...
3999 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001 "moveTasksToFullscreenStack()");
4002 synchronized (mGlobalLock) {
4003 final long origId = Binder.clearCallingIdentity();
4004 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004005 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 if (stack != null){
4007 if (!stack.isActivityTypeStandardOrUndefined()) {
4008 throw new IllegalArgumentException(
4009 "You can't move tasks from non-standard stacks.");
4010 }
4011 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(origId);
4015 }
4016 }
4017 }
4018
4019 /**
4020 * Moves the top activity in the input stackId to the pinned stack.
4021 *
4022 * @param stackId Id of stack to move the top activity to pinned stack.
4023 * @param bounds Bounds to use for pinned stack.
4024 *
4025 * @return True if the top activity of the input stack was successfully moved to the pinned
4026 * stack.
4027 */
4028 @Override
4029 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 "moveTopActivityToPinnedStack()");
4032 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4035 + "Device doesn't support picture-in-picture mode");
4036 }
4037
4038 long ident = Binder.clearCallingIdentity();
4039 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004040 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 } finally {
4042 Binder.restoreCallingIdentity(ident);
4043 }
4044 }
4045 }
4046
4047 @Override
4048 public boolean isInMultiWindowMode(IBinder token) {
4049 final long origId = Binder.clearCallingIdentity();
4050 try {
4051 synchronized (mGlobalLock) {
4052 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4053 if (r == null) {
4054 return false;
4055 }
4056 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4057 return r.inMultiWindowMode();
4058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(origId);
4061 }
4062 }
4063
4064 @Override
4065 public boolean isInPictureInPictureMode(IBinder token) {
4066 final long origId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4070 }
4071 } finally {
4072 Binder.restoreCallingIdentity(origId);
4073 }
4074 }
4075
4076 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004077 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4078 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 return false;
4080 }
4081
4082 // If we are animating to fullscreen then we have already dispatched the PIP mode
4083 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004084 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4085 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 }
4087
4088 @Override
4089 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4090 final long origId = Binder.clearCallingIdentity();
4091 try {
4092 synchronized (mGlobalLock) {
4093 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4094 "enterPictureInPictureMode", token, params);
4095
4096 // If the activity is already in picture in picture mode, then just return early
4097 if (isInPictureInPictureMode(r)) {
4098 return true;
4099 }
4100
4101 // Activity supports picture-in-picture, now check that we can enter PiP at this
4102 // point, if it is
4103 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4104 false /* beforeStopping */)) {
4105 return false;
4106 }
4107
4108 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004109 synchronized (mGlobalLock) {
4110 // Only update the saved args from the args that are set
4111 r.pictureInPictureArgs.copyOnlySet(params);
4112 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4113 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4114 // Adjust the source bounds by the insets for the transition down
4115 final Rect sourceBounds = new Rect(
4116 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004117 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004118 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004119 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 stack.setPictureInPictureAspectRatio(aspectRatio);
4121 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004122 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4123 r.info.applicationInfo.uid, r.shortComponentName,
4124 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004125 logPictureInPictureArgs(params);
4126 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 };
4128
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004129 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 // If the keyguard is showing or occluded, then try and dismiss it before
4131 // entering picture-in-picture (this will prompt the user to authenticate if the
4132 // device is currently locked).
4133 dismissKeyguard(token, new KeyguardDismissCallback() {
4134 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004135 public void onDismissSucceeded() {
4136 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004137 }
4138 }, null /* message */);
4139 } else {
4140 // Enter picture in picture immediately otherwise
4141 enterPipRunnable.run();
4142 }
4143 return true;
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(origId);
4147 }
4148 }
4149
4150 @Override
4151 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 synchronized (mGlobalLock) {
4155 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4156 "setPictureInPictureParams", token, params);
4157
4158 // Only update the saved args from the args that are set
4159 r.pictureInPictureArgs.copyOnlySet(params);
4160 if (r.inPinnedWindowingMode()) {
4161 // If the activity is already in picture-in-picture, update the pinned stack now
4162 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4163 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004164 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 if (!stack.isAnimatingBoundsToFullscreen()) {
4166 stack.setPictureInPictureAspectRatio(
4167 r.pictureInPictureArgs.getAspectRatio());
4168 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4169 }
4170 }
4171 logPictureInPictureArgs(params);
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(origId);
4175 }
4176 }
4177
4178 @Override
4179 public int getMaxNumPictureInPictureActions(IBinder token) {
4180 // Currently, this is a static constant, but later, we may change this to be dependent on
4181 // the context of the activity
4182 return 3;
4183 }
4184
4185 private void logPictureInPictureArgs(PictureInPictureParams params) {
4186 if (params.hasSetActions()) {
4187 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4188 params.getActions().size());
4189 }
4190 if (params.hasSetAspectRatio()) {
4191 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4192 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4193 MetricsLogger.action(lm);
4194 }
4195 }
4196
4197 /**
4198 * Checks the state of the system and the activity associated with the given {@param token} to
4199 * verify that picture-in-picture is supported for that activity.
4200 *
4201 * @return the activity record for the given {@param token} if all the checks pass.
4202 */
4203 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4204 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 throw new IllegalStateException(caller
4207 + ": Device doesn't support picture-in-picture mode.");
4208 }
4209
4210 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4211 if (r == null) {
4212 throw new IllegalStateException(caller
4213 + ": Can't find activity for token=" + token);
4214 }
4215
4216 if (!r.supportsPictureInPicture()) {
4217 throw new IllegalStateException(caller
4218 + ": Current activity does not support picture-in-picture.");
4219 }
4220
4221 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004222 && !mWindowManager.isValidPictureInPictureAspectRatio(
4223 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 final float minAspectRatio = mContext.getResources().getFloat(
4225 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4226 final float maxAspectRatio = mContext.getResources().getFloat(
4227 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4228 throw new IllegalArgumentException(String.format(caller
4229 + ": Aspect ratio is too extreme (must be between %f and %f).",
4230 minAspectRatio, maxAspectRatio));
4231 }
4232
4233 // Truncate the number of actions if necessary
4234 params.truncateActions(getMaxNumPictureInPictureActions(token));
4235
4236 return r;
4237 }
4238
4239 @Override
4240 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242 synchronized (mGlobalLock) {
4243 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4244 if (r == null) {
4245 throw new IllegalArgumentException("Activity does not exist; token="
4246 + activityToken);
4247 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004248 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 }
4250 }
4251
4252 @Override
4253 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4254 Rect tempDockedTaskInsetBounds,
4255 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 long ident = Binder.clearCallingIdentity();
4258 try {
4259 synchronized (mGlobalLock) {
4260 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4261 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4262 PRESERVE_WINDOWS);
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(ident);
4266 }
4267 }
4268
4269 @Override
4270 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 final long ident = Binder.clearCallingIdentity();
4273 try {
4274 synchronized (mGlobalLock) {
4275 mStackSupervisor.setSplitScreenResizing(resizing);
4276 }
4277 } finally {
4278 Binder.restoreCallingIdentity(ident);
4279 }
4280 }
4281
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 /**
4283 * Check that we have the features required for VR-related API calls, and throw an exception if
4284 * not.
4285 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004286 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 if (!mContext.getPackageManager().hasSystemFeature(
4288 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4289 throw new UnsupportedOperationException("VR mode not supported on this device!");
4290 }
4291 }
4292
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 @Override
4294 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296
4297 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4298
4299 ActivityRecord r;
4300 synchronized (mGlobalLock) {
4301 r = ActivityRecord.isInStackLocked(token);
4302 }
4303
4304 if (r == null) {
4305 throw new IllegalArgumentException();
4306 }
4307
4308 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004309 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 VrManagerInternal.NO_ERROR) {
4311 return err;
4312 }
4313
4314 // Clear the binder calling uid since this path may call moveToTask().
4315 final long callingId = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 r.requestedVrComponent = (enabled) ? packageName : null;
4319
4320 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004321 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324 return 0;
4325 }
4326 } finally {
4327 Binder.restoreCallingIdentity(callingId);
4328 }
4329 }
4330
4331 @Override
4332 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4333 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4334 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004335 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004336 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4337 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4338 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004339 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 || activity.voiceSession != null) {
4341 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4342 return;
4343 }
4344 if (activity.pendingVoiceInteractionStart) {
4345 Slog.w(TAG, "Pending start of voice interaction already.");
4346 return;
4347 }
4348 activity.pendingVoiceInteractionStart = true;
4349 }
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .startLocalVoiceInteraction(callingActivity, options);
4352 }
4353
4354 @Override
4355 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4356 LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .stopLocalVoiceInteraction(callingActivity);
4358 }
4359
4360 @Override
4361 public boolean supportsLocalVoiceInteraction() {
4362 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4363 .supportsLocalVoiceInteraction();
4364 }
4365
4366 /** Notifies all listeners when the pinned stack animation starts. */
4367 @Override
4368 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004369 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371
4372 /** Notifies all listeners when the pinned stack animation ends. */
4373 @Override
4374 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 }
4377
4378 @Override
4379 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 final long ident = Binder.clearCallingIdentity();
4382 try {
4383 synchronized (mGlobalLock) {
4384 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4385 }
4386 } finally {
4387 Binder.restoreCallingIdentity(ident);
4388 }
4389 }
4390
4391 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394
4395 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004396 if (mWindowManager == null) {
4397 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4398 return false;
4399 }
4400
4401 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 }
4405
Riddle Hsua0022cd2019-09-09 21:12:41 +08004406 mH.sendMessage(PooledLambda.obtainMessage(
4407 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4408 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409
4410 final long origId = Binder.clearCallingIdentity();
4411 try {
4412 if (values != null) {
4413 Settings.System.clearConfiguration(values);
4414 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 UserHandle.USER_NULL, false /* deferResume */,
4417 mTmpUpdateConfigurationResult);
4418 return mTmpUpdateConfigurationResult.changes != 0;
4419 } finally {
4420 Binder.restoreCallingIdentity(origId);
4421 }
4422 }
4423 }
4424
4425 @Override
4426 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4427 CharSequence message) {
4428 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004429 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4431 }
4432 final long callingId = Binder.clearCallingIdentity();
4433 try {
4434 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004435 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 }
4437 } finally {
4438 Binder.restoreCallingIdentity(callingId);
4439 }
4440 }
4441
4442 @Override
4443 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 "cancelTaskWindowTransition()");
4446 final long ident = Binder.clearCallingIdentity();
4447 try {
4448 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004449 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 MATCH_TASK_IN_STACKS_ONLY);
4451 if (task == null) {
4452 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4453 return;
4454 }
4455 task.cancelWindowTransition();
4456 }
4457 } finally {
4458 Binder.restoreCallingIdentity(ident);
4459 }
4460 }
4461
4462 @Override
4463 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004464 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 final long ident = Binder.clearCallingIdentity();
4466 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004467 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 } finally {
4469 Binder.restoreCallingIdentity(ident);
4470 }
4471 }
4472
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004473 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4474 boolean restoreFromDisk) {
4475 final TaskRecord task;
4476 synchronized (mGlobalLock) {
4477 task = mRootActivityContainer.anyTaskForId(taskId,
4478 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4479 if (task == null) {
4480 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4481 return null;
4482 }
4483 }
4484 // Don't call this while holding the lock as this operation might hit the disk.
4485 return task.getSnapshot(reducedResolution, restoreFromDisk);
4486 }
4487
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 @Override
4489 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4490 synchronized (mGlobalLock) {
4491 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4492 if (r == null) {
4493 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4494 + token);
4495 return;
4496 }
4497 final long origId = Binder.clearCallingIdentity();
4498 try {
4499 r.setDisablePreviewScreenshots(disable);
4500 } finally {
4501 Binder.restoreCallingIdentity(origId);
4502 }
4503 }
4504 }
4505
4506 /** Return the user id of the last resumed activity. */
4507 @Override
4508 public @UserIdInt
4509 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4512 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004513 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004516 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void updateLockTaskFeatures(int userId, int flags) {
4522 final int callingUid = Binder.getCallingUid();
4523 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004524 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 "updateLockTaskFeatures()");
4526 }
4527 synchronized (mGlobalLock) {
4528 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4529 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004530 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004531 }
4532 }
4533
4534 @Override
4535 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4536 synchronized (mGlobalLock) {
4537 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4538 if (r == null) {
4539 return;
4540 }
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
4543 r.setShowWhenLocked(showWhenLocked);
4544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
4549
4550 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004551 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4552 synchronized (mGlobalLock) {
4553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4554 if (r == null) {
4555 return;
4556 }
4557 final long origId = Binder.clearCallingIdentity();
4558 try {
4559 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4560 } finally {
4561 Binder.restoreCallingIdentity(origId);
4562 }
4563 }
4564 }
4565
4566 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4568 synchronized (mGlobalLock) {
4569 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4570 if (r == null) {
4571 return;
4572 }
4573 final long origId = Binder.clearCallingIdentity();
4574 try {
4575 r.setTurnScreenOn(turnScreenOn);
4576 } finally {
4577 Binder.restoreCallingIdentity(origId);
4578 }
4579 }
4580 }
4581
4582 @Override
4583 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004584 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004586 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 synchronized (mGlobalLock) {
4588 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4589 if (r == null) {
4590 return;
4591 }
4592 final long origId = Binder.clearCallingIdentity();
4593 try {
4594 r.registerRemoteAnimations(definition);
4595 } finally {
4596 Binder.restoreCallingIdentity(origId);
4597 }
4598 }
4599 }
4600
4601 @Override
4602 public void registerRemoteAnimationForNextActivityStart(String packageName,
4603 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004604 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004605 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004606 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 synchronized (mGlobalLock) {
4608 final long origId = Binder.clearCallingIdentity();
4609 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004610 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004611 packageName, adapter);
4612 } finally {
4613 Binder.restoreCallingIdentity(origId);
4614 }
4615 }
4616 }
4617
Evan Rosky966759f2019-01-15 10:33:58 -08004618 @Override
4619 public void registerRemoteAnimationsForDisplay(int displayId,
4620 RemoteAnimationDefinition definition) {
4621 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4622 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004623 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004624 synchronized (mGlobalLock) {
4625 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4626 if (display == null) {
4627 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4628 return;
4629 }
4630 final long origId = Binder.clearCallingIdentity();
4631 try {
4632 display.mDisplayContent.registerRemoteAnimations(definition);
4633 } finally {
4634 Binder.restoreCallingIdentity(origId);
4635 }
4636 }
4637 }
4638
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4640 @Override
4641 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4642 synchronized (mGlobalLock) {
4643 final long origId = Binder.clearCallingIdentity();
4644 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004645 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004651
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 @Override
4653 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004655 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004656 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004657 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004658 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 }
4660 }
4661
4662 @Override
4663 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004665 != PERMISSION_GRANTED) {
4666 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4667 + Binder.getCallingPid()
4668 + ", uid=" + Binder.getCallingUid()
4669 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4670 Slog.w(TAG, msg);
4671 throw new SecurityException(msg);
4672 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004674 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004675 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004676 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004677 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004678 }
4679 }
4680
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004681 @Override
4682 public void stopAppSwitches() {
4683 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4684 synchronized (mGlobalLock) {
4685 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004686 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 mDidAppSwitch = false;
4688 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4689 }
4690 }
4691
4692 @Override
4693 public void resumeAppSwitches() {
4694 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4695 synchronized (mGlobalLock) {
4696 // Note that we don't execute any pending app switches... we will
4697 // let those wait until either the timeout, or the next start
4698 // activity request.
4699 mAppSwitchesAllowedTime = 0;
4700 }
4701 }
4702
Ricky Wai906af482019-06-03 17:25:28 +01004703 long getLastStopAppSwitchesTime() {
4704 return mLastStopAppSwitchesTime;
4705 }
4706
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 void onStartActivitySetDidAppSwitch() {
4708 if (mDidAppSwitch) {
4709 // This is the second allowed switch since we stopped switches, so now just generally
4710 // allow switches. Use case:
4711 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4712 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4713 // anyone to switch again).
4714 mAppSwitchesAllowedTime = 0;
4715 } else {
4716 mDidAppSwitch = true;
4717 }
4718 }
4719
4720 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 boolean shouldDisableNonVrUiLocked() {
4722 return mVrController.shouldDisableNonVrUiLocked();
4723 }
4724
Wale Ogunwale53783742018-09-16 10:21:51 -07004725 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 // VR apps are expected to run in a main display. If an app is turning on VR for
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004727 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004729 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4730 + " to main display for VR");
4731 mRootActivityContainer.moveStackToDisplay(
4732 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 }
4734 mH.post(() -> {
4735 if (!mVrController.onVrModeChanged(r)) {
4736 return;
4737 }
4738 synchronized (mGlobalLock) {
4739 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4740 mWindowManager.disableNonVrUi(disableNonVrUi);
4741 if (disableNonVrUi) {
4742 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4743 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004744 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004745 }
4746 }
4747 });
4748 }
4749
Wale Ogunwale53783742018-09-16 10:21:51 -07004750 @Override
4751 public int getPackageScreenCompatMode(String packageName) {
4752 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4753 synchronized (mGlobalLock) {
4754 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4755 }
4756 }
4757
4758 @Override
4759 public void setPackageScreenCompatMode(String packageName, int mode) {
4760 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4761 "setPackageScreenCompatMode");
4762 synchronized (mGlobalLock) {
4763 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4764 }
4765 }
4766
4767 @Override
4768 public boolean getPackageAskScreenCompat(String packageName) {
4769 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4770 synchronized (mGlobalLock) {
4771 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4772 }
4773 }
4774
4775 @Override
4776 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4777 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4778 "setPackageAskScreenCompat");
4779 synchronized (mGlobalLock) {
4780 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4781 }
4782 }
4783
Wale Ogunwale64258362018-10-16 15:13:37 -07004784 public static String relaunchReasonToString(int relaunchReason) {
4785 switch (relaunchReason) {
4786 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4787 return "window_resize";
4788 case RELAUNCH_REASON_FREE_RESIZE:
4789 return "free_resize";
4790 default:
4791 return null;
4792 }
4793 }
4794
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004795 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004796 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004797 }
4798
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 /** Pokes the task persister. */
4800 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4801 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4802 }
4803
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004804 boolean isKeyguardLocked() {
4805 return mKeyguardController.isKeyguardLocked();
4806 }
4807
Garfield Tan01548632018-11-27 10:15:48 -08004808 /**
4809 * Clears launch params for the given package.
4810 * @param packageNames the names of the packages of which the launch params are to be cleared
4811 */
4812 @Override
4813 public void clearLaunchParamsForPackages(List<String> packageNames) {
4814 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4815 "clearLaunchParamsForPackages");
4816 synchronized (mGlobalLock) {
4817 for (int i = 0; i < packageNames.size(); ++i) {
4818 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4819 }
4820 }
4821 }
4822
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004823 /**
4824 * Makes the display with the given id a single task instance display. I.e the display can only
4825 * contain one task.
4826 */
4827 @Override
4828 public void setDisplayToSingleTaskInstance(int displayId) {
4829 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4830 "setDisplayToSingleTaskInstance");
4831 final long origId = Binder.clearCallingIdentity();
4832 try {
4833 final ActivityDisplay display =
4834 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4835 if (display != null) {
4836 display.setDisplayToSingleTaskInstance();
4837 }
4838 } finally {
4839 Binder.restoreCallingIdentity(origId);
4840 }
4841 }
4842
Wale Ogunwale31913b52018-10-13 08:29:31 -07004843 void dumpLastANRLocked(PrintWriter pw) {
4844 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4845 if (mLastANRState == null) {
4846 pw.println(" <no ANR has occurred since boot>");
4847 } else {
4848 pw.println(mLastANRState);
4849 }
4850 }
4851
4852 void dumpLastANRTracesLocked(PrintWriter pw) {
4853 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4854
4855 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4856 if (ArrayUtils.isEmpty(files)) {
4857 pw.println(" <no ANR has occurred since boot>");
4858 return;
4859 }
4860 // Find the latest file.
4861 File latest = null;
4862 for (File f : files) {
4863 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4864 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004865 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004866 }
4867 pw.print("File: ");
4868 pw.print(latest.getName());
4869 pw.println();
4870 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4871 String line;
4872 while ((line = in.readLine()) != null) {
4873 pw.println(line);
4874 }
4875 } catch (IOException e) {
4876 pw.print("Unable to read: ");
4877 pw.print(e);
4878 pw.println();
4879 }
4880 }
4881
4882 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4883 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4884 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4885 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4886 }
4887
4888 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4889 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4890 pw.println(header);
4891
Wale Ogunwaled32da472018-11-16 07:19:28 -08004892 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004893 dumpPackage);
4894 boolean needSep = printedAnything;
4895
4896 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004897 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004898 " ResumedActivity: ");
4899 if (printed) {
4900 printedAnything = true;
4901 needSep = false;
4902 }
4903
4904 if (dumpPackage == null) {
4905 if (needSep) {
4906 pw.println();
4907 }
4908 printedAnything = true;
4909 mStackSupervisor.dump(pw, " ");
4910 }
4911
4912 if (!printedAnything) {
4913 pw.println(" (nothing)");
4914 }
4915 }
4916
4917 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004918 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004919 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004920 pw.println(" ");
4921 }
4922
4923 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4924 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4925 getActivityStartController().dump(pw, "", dumpPackage);
4926 }
4927
4928 /**
4929 * There are three things that cmd can be:
4930 * - a flattened component name that matches an existing activity
4931 * - the cmd arg isn't the flattened component name of an existing activity:
4932 * dump all activity whose component contains the cmd as a substring
4933 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004934 * <p>
4935 * The caller should not hold lock when calling this method because it will wait for the
4936 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 *
4938 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4939 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4940 */
4941 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4942 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4943 ArrayList<ActivityRecord> activities;
4944
4945 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004946 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004947 dumpFocusedStackOnly);
4948 }
4949
4950 if (activities.size() <= 0) {
4951 return false;
4952 }
4953
4954 String[] newArgs = new String[args.length - opti];
4955 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4956
4957 TaskRecord lastTask = null;
4958 boolean needSep = false;
4959 for (int i = activities.size() - 1; i >= 0; i--) {
4960 ActivityRecord r = activities.get(i);
4961 if (needSep) {
4962 pw.println();
4963 }
4964 needSep = true;
4965 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004966 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 if (lastTask != task) {
4968 lastTask = task;
4969 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004970 pw.print(" id="); pw.print(lastTask.mTaskId);
4971 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004972 if (dumpAll) {
4973 lastTask.dump(pw, " ");
4974 }
4975 }
4976 }
4977 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4978 }
4979 return true;
4980 }
4981
4982 /**
4983 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4984 * there is a thread associated with the activity.
4985 */
4986 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4987 final ActivityRecord r, String[] args, boolean dumpAll) {
4988 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004989 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 synchronized (mGlobalLock) {
4991 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4992 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4993 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004994 if (r.hasProcess()) {
4995 pw.println(r.app.getPid());
4996 appThread = r.app.getThread();
4997 } else {
4998 pw.println("(not running)");
4999 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 if (dumpAll) {
5001 r.dump(pw, innerPrefix);
5002 }
5003 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005004 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005005 // flush anything that is already in the PrintWriter since the thread is going
5006 // to write to the file descriptor directly
5007 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005008 try (TransferPipe tp = new TransferPipe()) {
5009 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5010 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005011 } catch (IOException e) {
5012 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5013 } catch (RemoteException e) {
5014 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5015 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005016 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005017 }
5018
sanryhuang498e77e2018-12-06 14:57:01 +08005019 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5020 boolean testPssMode) {
5021 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5023 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005024 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5026 st.toString());
5027 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005028 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5029 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5030 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005031 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5032 testPssMode);
5033 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005034 }
5035
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005036 int getCurrentUserId() {
5037 return mAmInternal.getCurrentUserId();
5038 }
5039
5040 private void enforceNotIsolatedCaller(String caller) {
5041 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5042 throw new SecurityException("Isolated process not allowed to call " + caller);
5043 }
5044 }
5045
Wale Ogunwalef6733932018-06-27 05:14:34 -07005046 public Configuration getConfiguration() {
5047 Configuration ci;
5048 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005049 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005050 ci.userSetLocale = false;
5051 }
5052 return ci;
5053 }
5054
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 /**
5056 * Current global configuration information. Contains general settings for the entire system,
5057 * also corresponds to the merged configuration of the default display.
5058 */
5059 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005060 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 }
5062
5063 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5064 boolean initLocale) {
5065 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5066 }
5067
5068 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5069 boolean initLocale, boolean deferResume) {
5070 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5071 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5072 UserHandle.USER_NULL, deferResume);
5073 }
5074
Wale Ogunwale59507092018-10-29 09:00:30 -07005075 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 final long origId = Binder.clearCallingIdentity();
5077 try {
5078 synchronized (mGlobalLock) {
5079 updateConfigurationLocked(values, null, false, true, userId,
5080 false /* deferResume */);
5081 }
5082 } finally {
5083 Binder.restoreCallingIdentity(origId);
5084 }
5085 }
5086
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005087 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5088 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5089 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5090 deferResume, null /* result */);
5091 }
5092
5093 /**
5094 * Do either or both things: (1) change the current configuration, and (2)
5095 * make sure the given activity is running with the (now) current
5096 * configuration. Returns true if the activity has been left running, or
5097 * false if <var>starting</var> is being destroyed to match the new
5098 * configuration.
5099 *
5100 * @param userId is only used when persistent parameter is set to true to persist configuration
5101 * for that particular user
5102 */
5103 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5104 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5105 ActivityTaskManagerService.UpdateConfigurationResult result) {
5106 int changes = 0;
5107 boolean kept = true;
5108
Riddle Hsua0022cd2019-09-09 21:12:41 +08005109 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005110 try {
5111 if (values != null) {
5112 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5113 deferResume);
5114 }
5115
5116 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5117 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005118 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 }
5120
5121 if (result != null) {
5122 result.changes = changes;
5123 result.activityRelaunched = !kept;
5124 }
5125 return kept;
5126 }
5127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005129 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005131
5132 final ActivityDisplay defaultDisplay =
5133 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5134
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135 mTempConfig.setTo(getGlobalConfiguration());
5136 final int changes = mTempConfig.updateFrom(values);
5137 if (changes == 0) {
5138 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5139 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5140 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5141 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005142 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005143 return 0;
5144 }
5145
5146 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5147 "Updating global configuration to: " + values);
5148
5149 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5150 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5151 values.colorMode,
5152 values.densityDpi,
5153 values.fontScale,
5154 values.hardKeyboardHidden,
5155 values.keyboard,
5156 values.keyboardHidden,
5157 values.mcc,
5158 values.mnc,
5159 values.navigation,
5160 values.navigationHidden,
5161 values.orientation,
5162 values.screenHeightDp,
5163 values.screenLayout,
5164 values.screenWidthDp,
5165 values.smallestScreenWidthDp,
5166 values.touchscreen,
5167 values.uiMode);
5168
5169
5170 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5171 final LocaleList locales = values.getLocales();
5172 int bestLocaleIndex = 0;
5173 if (locales.size() > 1) {
5174 if (mSupportedSystemLocales == null) {
5175 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5176 }
5177 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5178 }
5179 SystemProperties.set("persist.sys.locale",
5180 locales.get(bestLocaleIndex).toLanguageTag());
5181 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005182
5183 final Message m = PooledLambda.obtainMessage(
5184 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5185 locales.get(bestLocaleIndex));
5186 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187 }
5188
Yunfan Chen75157d72018-07-27 14:47:21 +09005189 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005192 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193
5194 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5195 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005196 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197
5198 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005199 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005200
5201 AttributeCache ac = AttributeCache.instance();
5202 if (ac != null) {
5203 ac.updateConfiguration(mTempConfig);
5204 }
5205
5206 // Make sure all resources in our process are updated right now, so that anyone who is going
5207 // to retrieve resource values after we return will be sure to get the new ones. This is
5208 // especially important during boot, where the first config change needs to guarantee all
5209 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005210 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005211
5212 // We need another copy of global config because we're scheduling some calls instead of
5213 // running them in place. We need to be sure that object we send will be handled unchanged.
5214 final Configuration configCopy = new Configuration(mTempConfig);
5215 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005216 final Message msg = PooledLambda.obtainMessage(
5217 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5218 this, userId, configCopy);
5219 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005222 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5223 for (int i = pidMap.size() - 1; i >= 0; i--) {
5224 final int pid = pidMap.keyAt(i);
5225 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005226 if (DEBUG_CONFIGURATION) {
5227 Slog.v(TAG_CONFIGURATION, "Update process config of "
5228 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005229 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005230 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 }
5232
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005233 final Message msg = PooledLambda.obtainMessage(
5234 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5235 mAmInternal, changes, initLocale);
5236 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237
5238 // Override configuration of the default display duplicates global config, so we need to
5239 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005240 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5241 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242
5243 return changes;
5244 }
5245
Riddle Hsua0022cd2019-09-09 21:12:41 +08005246 /** @see WindowSurfacePlacer#deferLayout */
5247 void deferWindowLayout() {
5248 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5249 // Reset the reasons at the first entrance because we only care about the changes in the
5250 // deferred scope.
5251 mLayoutReasons = 0;
5252 }
5253
5254 mWindowManager.mWindowPlacerLocked.deferLayout();
5255 }
5256
5257 /** @see WindowSurfacePlacer#continueLayout */
5258 void continueWindowLayout() {
5259 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5260 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5261 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5262 }
5263 }
5264
5265 /**
5266 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5267 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5268 * defer count is gone.
5269 */
5270 void addWindowLayoutReasons(@LayoutReason int reasons) {
5271 mLayoutReasons |= reasons;
5272 }
5273
Wale Ogunwalef6733932018-06-27 05:14:34 -07005274 private void updateEventDispatchingLocked(boolean booted) {
5275 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5276 }
5277
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005278 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5279 final ContentResolver resolver = mContext.getContentResolver();
5280 Settings.System.putConfigurationForUser(resolver, config, userId);
5281 }
5282
5283 private void sendLocaleToMountDaemonMsg(Locale l) {
5284 try {
5285 IBinder service = ServiceManager.getService("mount");
5286 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5287 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5288 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5289 } catch (RemoteException e) {
5290 Log.e(TAG, "Error storing locale for decryption UI", e);
5291 }
5292 }
5293
Alison Cichowlas3e340502018-08-07 17:15:01 -04005294 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5295 mStartActivitySources.remove(permissionToken);
5296 mExpiredStartAsCallerTokens.add(permissionToken);
5297 }
5298
5299 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5300 mExpiredStartAsCallerTokens.remove(permissionToken);
5301 }
5302
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005303 boolean isActivityStartsLoggingEnabled() {
5304 return mAmInternal.isActivityStartsLoggingEnabled();
5305 }
5306
Michal Karpinski8596ded2018-11-14 14:43:48 +00005307 boolean isBackgroundActivityStartsEnabled() {
5308 return mAmInternal.isBackgroundActivityStartsEnabled();
5309 }
5310
Wale Ogunwalef6733932018-06-27 05:14:34 -07005311 void enableScreenAfterBoot(boolean booted) {
5312 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5313 SystemClock.uptimeMillis());
5314 mWindowManager.enableScreenAfterBoot();
5315
5316 synchronized (mGlobalLock) {
5317 updateEventDispatchingLocked(booted);
5318 }
5319 }
5320
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005321 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5322 if (r == null || !r.hasProcess()) {
5323 return KEY_DISPATCHING_TIMEOUT_MS;
5324 }
5325 return getInputDispatchingTimeoutLocked(r.app);
5326 }
5327
5328 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005329 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005330 }
5331
Wale Ogunwalef6733932018-06-27 05:14:34 -07005332 /**
5333 * Decide based on the configuration whether we should show the ANR,
5334 * crash, etc dialogs. The idea is that if there is no affordance to
5335 * press the on-screen buttons, or the user experience would be more
5336 * greatly impacted than the crash itself, we shouldn't show the dialog.
5337 *
5338 * A thought: SystemUI might also want to get told about this, the Power
5339 * dialog / global actions also might want different behaviors.
5340 */
5341 private void updateShouldShowDialogsLocked(Configuration config) {
5342 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5343 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5344 && config.navigation == Configuration.NAVIGATION_NONAV);
5345 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5346 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5347 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5348 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5349 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5350 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5351 HIDE_ERROR_DIALOGS, 0) != 0;
5352 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5353 }
5354
5355 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5356 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5357 FONT_SCALE, 1.0f, userId);
5358
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005359 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 if (getGlobalConfiguration().fontScale == scaleFactor) {
5361 return;
5362 }
5363
5364 final Configuration configuration
5365 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5366 configuration.fontScale = scaleFactor;
5367 updatePersistentConfiguration(configuration, userId);
5368 }
5369 }
5370
5371 // Actually is sleeping or shutting down or whatever else in the future
5372 // is an inactive state.
5373 boolean isSleepingOrShuttingDownLocked() {
5374 return isSleepingLocked() || mShuttingDown;
5375 }
5376
5377 boolean isSleepingLocked() {
5378 return mSleeping;
5379 }
5380
Riddle Hsu16567132018-08-16 21:37:47 +08005381 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005382 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005384 if (task.isActivityTypeStandard()) {
5385 if (mCurAppTimeTracker != r.appTimeTracker) {
5386 // We are switching app tracking. Complete the current one.
5387 if (mCurAppTimeTracker != null) {
5388 mCurAppTimeTracker.stop();
5389 mH.obtainMessage(
5390 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005391 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 mCurAppTimeTracker = null;
5393 }
5394 if (r.appTimeTracker != null) {
5395 mCurAppTimeTracker = r.appTimeTracker;
5396 startTimeTrackingFocusedActivityLocked();
5397 }
5398 } else {
5399 startTimeTrackingFocusedActivityLocked();
5400 }
5401 } else {
5402 r.appTimeTracker = null;
5403 }
5404 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5405 // TODO: Probably not, because we don't want to resume voice on switching
5406 // back to this activity
5407 if (task.voiceInteractor != null) {
5408 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5409 } else {
5410 finishRunningVoiceLocked();
5411
5412 if (mLastResumedActivity != null) {
5413 final IVoiceInteractionSession session;
5414
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005415 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 if (lastResumedActivityTask != null
5417 && lastResumedActivityTask.voiceSession != null) {
5418 session = lastResumedActivityTask.voiceSession;
5419 } else {
5420 session = mLastResumedActivity.voiceSession;
5421 }
5422
5423 if (session != null) {
5424 // We had been in a voice interaction session, but now focused has
5425 // move to something different. Just finish the session, we can't
5426 // return to it and retain the proper state and synchronization with
5427 // the voice interaction service.
5428 finishVoiceTask(session);
5429 }
5430 }
5431 }
5432
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005433 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5434 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 }
5436 updateResumedAppTrace(r);
5437 mLastResumedActivity = r;
5438
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005439 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440
5441 applyUpdateLockStateLocked(r);
5442 applyUpdateVrModeLocked(r);
5443
5444 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005445 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 r == null ? "NULL" : r.shortComponentName,
5447 reason);
5448 }
5449
5450 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5451 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005452 final ActivityTaskManagerInternal.SleepToken token =
5453 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 updateSleepIfNeededLocked();
5455 return token;
5456 }
5457 }
5458
5459 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005460 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 final boolean wasSleeping = mSleeping;
5462 boolean updateOomAdj = false;
5463
5464 if (!shouldSleep) {
5465 // If wasSleeping is true, we need to wake up activity manager state from when
5466 // we started sleeping. In either case, we need to apply the sleep tokens, which
5467 // will wake up stacks or put them to sleep as appropriate.
5468 if (wasSleeping) {
5469 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005470 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5471 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 startTimeTrackingFocusedActivityLocked();
5473 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005474 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5476 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005477 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005478 if (wasSleeping) {
5479 updateOomAdj = true;
5480 }
5481 } else if (!mSleeping && shouldSleep) {
5482 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005483 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5484 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485 if (mCurAppTimeTracker != null) {
5486 mCurAppTimeTracker.stop();
5487 }
5488 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005489 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490 mStackSupervisor.goingToSleepLocked();
5491 updateResumedAppTrace(null /* resumed */);
5492 updateOomAdj = true;
5493 }
5494 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005495 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005496 }
5497 }
5498
5499 void updateOomAdj() {
5500 mH.post(mAmInternal::updateOomAdj);
5501 }
5502
Wale Ogunwale53783742018-09-16 10:21:51 -07005503 void updateCpuStats() {
5504 mH.post(mAmInternal::updateCpuStats);
5505 }
5506
Hui Yu03d12402018-12-06 18:00:37 -08005507 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5508 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005509 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5510 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005511 mH.sendMessage(m);
5512 }
5513
Hui Yu03d12402018-12-06 18:00:37 -08005514 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005515 ComponentName taskRoot = null;
5516 final TaskRecord task = activity.getTaskRecord();
5517 if (task != null) {
5518 final ActivityRecord rootActivity = task.getRootActivity();
5519 if (rootActivity != null) {
5520 taskRoot = rootActivity.mActivityComponent;
5521 }
5522 }
5523
Hui Yu03d12402018-12-06 18:00:37 -08005524 final Message m = PooledLambda.obtainMessage(
5525 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005526 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005527 mH.sendMessage(m);
5528 }
5529
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005530 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5531 String hostingType) {
5532 try {
5533 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5534 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5535 + activity.processName);
5536 }
5537 // Post message to start process to avoid possible deadlock of calling into AMS with the
5538 // ATMS lock held.
5539 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5540 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5541 isTop, hostingType, activity.intent.getComponent());
5542 mH.sendMessage(m);
5543 } finally {
5544 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5545 }
5546 }
5547
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 void setBooting(boolean booting) {
5549 mAmInternal.setBooting(booting);
5550 }
5551
5552 boolean isBooting() {
5553 return mAmInternal.isBooting();
5554 }
5555
5556 void setBooted(boolean booted) {
5557 mAmInternal.setBooted(booted);
5558 }
5559
5560 boolean isBooted() {
5561 return mAmInternal.isBooted();
5562 }
5563
5564 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5565 mH.post(() -> {
5566 if (finishBooting) {
5567 mAmInternal.finishBooting();
5568 }
5569 if (enableScreen) {
5570 mInternal.enableScreenAfterBoot(isBooted());
5571 }
5572 });
5573 }
5574
5575 void setHeavyWeightProcess(ActivityRecord root) {
5576 mHeavyWeightProcess = root.app;
5577 final Message m = PooledLambda.obtainMessage(
5578 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005579 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005580 mH.sendMessage(m);
5581 }
5582
5583 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5584 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5585 return;
5586 }
5587
5588 mHeavyWeightProcess = null;
5589 final Message m = PooledLambda.obtainMessage(
5590 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5591 proc.mUserId);
5592 mH.sendMessage(m);
5593 }
5594
5595 private void cancelHeavyWeightProcessNotification(int userId) {
5596 final INotificationManager inm = NotificationManager.getService();
5597 if (inm == null) {
5598 return;
5599 }
5600 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005601 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005602 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5603 } catch (RuntimeException e) {
5604 Slog.w(TAG, "Error canceling notification for service", e);
5605 } catch (RemoteException e) {
5606 }
5607
5608 }
5609
5610 private void postHeavyWeightProcessNotification(
5611 WindowProcessController proc, Intent intent, int userId) {
5612 if (proc == null) {
5613 return;
5614 }
5615
5616 final INotificationManager inm = NotificationManager.getService();
5617 if (inm == null) {
5618 return;
5619 }
5620
5621 try {
5622 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5623 String text = mContext.getString(R.string.heavy_weight_notification,
5624 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5625 Notification notification =
5626 new Notification.Builder(context,
5627 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5628 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5629 .setWhen(0)
5630 .setOngoing(true)
5631 .setTicker(text)
5632 .setColor(mContext.getColor(
5633 com.android.internal.R.color.system_notification_accent_color))
5634 .setContentTitle(text)
5635 .setContentText(
5636 mContext.getText(R.string.heavy_weight_notification_detail))
5637 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5638 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5639 new UserHandle(userId)))
5640 .build();
5641 try {
5642 inm.enqueueNotificationWithTag("android", "android", null,
5643 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5644 } catch (RuntimeException e) {
5645 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5646 } catch (RemoteException e) {
5647 }
5648 } catch (PackageManager.NameNotFoundException e) {
5649 Slog.w(TAG, "Unable to create context for heavy notification", e);
5650 }
5651
5652 }
5653
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005654 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5655 IBinder token, String resultWho, int requestCode, Intent[] intents,
5656 String[] resolvedTypes, int flags, Bundle bOptions) {
5657
5658 ActivityRecord activity = null;
5659 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5660 activity = ActivityRecord.isInStackLocked(token);
5661 if (activity == null) {
5662 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5663 return null;
5664 }
5665 if (activity.finishing) {
5666 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5667 return null;
5668 }
5669 }
5670
5671 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5672 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5673 bOptions);
5674 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5675 if (noCreate) {
5676 return rec;
5677 }
5678 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5679 if (activity.pendingResults == null) {
5680 activity.pendingResults = new HashSet<>();
5681 }
5682 activity.pendingResults.add(rec.ref);
5683 }
5684 return rec;
5685 }
5686
Andrii Kulian52d255c2018-07-13 11:32:19 -07005687 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005688 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005689 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005690 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5691 mCurAppTimeTracker.start(resumedActivity.packageName);
5692 }
5693 }
5694
5695 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5696 if (mTracedResumedActivity != null) {
5697 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5698 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5699 }
5700 if (resumed != null) {
5701 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5702 constructResumedTraceName(resumed.packageName), 0);
5703 }
5704 mTracedResumedActivity = resumed;
5705 }
5706
5707 private String constructResumedTraceName(String packageName) {
5708 return "focused app: " + packageName;
5709 }
5710
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005711 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005712 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005713 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005714 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005715 // mainStack is null during startup.
5716 if (mainStack != null) {
5717 if (changes != 0 && starting == null) {
5718 // If the configuration changed, and the caller is not already
5719 // in the process of starting an activity, then find the top
5720 // activity to check if its configuration needs to change.
5721 starting = mainStack.topRunningActivityLocked();
5722 }
5723
5724 if (starting != null) {
5725 kept = starting.ensureActivityConfiguration(changes,
5726 false /* preserveWindow */);
5727 // And we need to make sure at this point that all other activities
5728 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005729 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005730 !PRESERVE_WINDOWS);
5731 }
5732 }
5733
5734 return kept;
5735 }
5736
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005737 void scheduleAppGcsLocked() {
5738 mH.post(() -> mAmInternal.scheduleAppGcs());
5739 }
5740
Wale Ogunwale53783742018-09-16 10:21:51 -07005741 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5742 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5743 }
5744
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005745 /**
5746 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5747 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5748 * on demand.
5749 */
5750 IPackageManager getPackageManager() {
5751 return AppGlobals.getPackageManager();
5752 }
5753
5754 PackageManagerInternal getPackageManagerInternalLocked() {
5755 if (mPmInternal == null) {
5756 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5757 }
5758 return mPmInternal;
5759 }
5760
Hai Zhangf4da9be2019-05-01 13:46:06 +08005761 PermissionPolicyInternal getPermissionPolicyInternal() {
5762 if (mPermissionPolicyInternal == null) {
5763 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5764 }
5765 return mPermissionPolicyInternal;
5766 }
5767
Wale Ogunwale008163e2018-07-23 23:11:08 -07005768 AppWarnings getAppWarningsLocked() {
5769 return mAppWarnings;
5770 }
5771
Wale Ogunwale214f3482018-10-04 11:00:47 -07005772 Intent getHomeIntent() {
5773 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5774 intent.setComponent(mTopComponent);
5775 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5776 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5777 intent.addCategory(Intent.CATEGORY_HOME);
5778 }
5779 return intent;
5780 }
5781
Chilun2ef71f72018-11-16 17:57:15 +08005782 /**
5783 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5784 * activities.
5785 *
5786 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5787 * component defined in config_secondaryHomeComponent.
5788 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5789 */
5790 Intent getSecondaryHomeIntent(String preferredPackage) {
5791 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005792 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5793 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5794 if (preferredPackage == null || useSystemProvidedLauncher) {
5795 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005796 final String secondaryHomeComponent = mContext.getResources().getString(
5797 com.android.internal.R.string.config_secondaryHomeComponent);
5798 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5799 } else {
5800 intent.setPackage(preferredPackage);
5801 }
5802 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5803 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5804 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5805 }
5806 return intent;
5807 }
5808
Wale Ogunwale214f3482018-10-04 11:00:47 -07005809 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5810 if (info == null) return null;
5811 ApplicationInfo newInfo = new ApplicationInfo(info);
5812 newInfo.initForUser(userId);
5813 return newInfo;
5814 }
5815
Wale Ogunwale9c103022018-10-18 07:44:54 -07005816 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005817 if (uid == SYSTEM_UID) {
5818 // The system gets to run in any process. If there are multiple processes with the same
5819 // uid, just pick the first (this should never happen).
5820 final SparseArray<WindowProcessController> procs =
5821 mProcessNames.getMap().get(processName);
5822 if (procs == null) return null;
5823 final int procCount = procs.size();
5824 for (int i = 0; i < procCount; i++) {
5825 final int procUid = procs.keyAt(i);
5826 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5827 // Don't use an app process or different user process for system component.
5828 continue;
5829 }
5830 return procs.valueAt(i);
5831 }
5832 }
5833
5834 return mProcessNames.get(processName, uid);
5835 }
5836
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005837 WindowProcessController getProcessController(IApplicationThread thread) {
5838 if (thread == null) {
5839 return null;
5840 }
5841
5842 final IBinder threadBinder = thread.asBinder();
5843 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5844 for (int i = pmap.size()-1; i >= 0; i--) {
5845 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5846 for (int j = procs.size() - 1; j >= 0; j--) {
5847 final WindowProcessController proc = procs.valueAt(j);
5848 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5849 return proc;
5850 }
5851 }
5852 }
5853
5854 return null;
5855 }
5856
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005857 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005858 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005859 if (proc == null) return null;
5860 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5861 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005862 }
5863 return null;
5864 }
5865
Riddle Hsua0536432019-02-16 00:38:59 +08005866 int getUidState(int uid) {
5867 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005868 }
5869
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005870 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005871 // A uid is considered to be foreground if it has a visible non-toast window.
5872 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005873 }
5874
Ricky Wai96f5c352019-04-10 18:40:17 +01005875 boolean isDeviceOwner(int uid) {
5876 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005877 }
5878
Ricky Wai96f5c352019-04-10 18:40:17 +01005879 void setDeviceOwnerUid(int uid) {
5880 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005881 }
5882
Wale Ogunwale9de19442018-10-18 19:05:03 -07005883 /**
5884 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5885 * the whitelist
5886 */
5887 String getPendingTempWhitelistTagForUidLocked(int uid) {
5888 return mPendingTempWhitelist.get(uid);
5889 }
5890
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005891 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5892 if (true || Build.IS_USER) {
5893 return;
5894 }
5895
5896 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5897 StrictMode.allowThreadDiskWrites();
5898 try {
5899 File tracesDir = new File("/data/anr");
5900 File tracesFile = null;
5901 try {
5902 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5903
5904 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005905 String timeString =
5906 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5907 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005908 sb.append(": ");
5909 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5910 sb.append(" since ");
5911 sb.append(msg);
5912 FileOutputStream fos = new FileOutputStream(tracesFile);
5913 fos.write(sb.toString().getBytes());
5914 if (app == null) {
5915 fos.write("\n*** No application process!".getBytes());
5916 }
5917 fos.close();
5918 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5919 } catch (IOException e) {
5920 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5921 return;
5922 }
5923
5924 if (app != null && app.getPid() > 0) {
5925 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5926 firstPids.add(app.getPid());
5927 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5928 }
5929
5930 File lastTracesFile = null;
5931 File curTracesFile = null;
5932 for (int i=9; i>=0; i--) {
5933 String name = String.format(Locale.US, "slow%02d.txt", i);
5934 curTracesFile = new File(tracesDir, name);
5935 if (curTracesFile.exists()) {
5936 if (lastTracesFile != null) {
5937 curTracesFile.renameTo(lastTracesFile);
5938 } else {
5939 curTracesFile.delete();
5940 }
5941 }
5942 lastTracesFile = curTracesFile;
5943 }
5944 tracesFile.renameTo(curTracesFile);
5945 } finally {
5946 StrictMode.setThreadPolicy(oldPolicy);
5947 }
5948 }
5949
Michal Karpinskida34cd42019-04-02 19:46:52 +01005950 boolean isAssociatedCompanionApp(int userId, int uid) {
5951 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5952 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005953 return false;
5954 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005955 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005956 }
5957
Issei Suzuki734bc942019-06-05 13:59:52 +02005958 void notifySingleTaskDisplayEmpty(int displayId) {
5959 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5960 }
5961
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005962 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005963 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005964
5965
Wale Ogunwale98875612018-10-12 07:53:02 -07005966 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5967 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005968
Riddle Hsud93a6c42018-11-29 21:50:06 +08005969 H(Looper looper) {
5970 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005971 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972
5973 @Override
5974 public void handleMessage(Message msg) {
5975 switch (msg.what) {
5976 case REPORT_TIME_TRACKER_MSG: {
5977 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5978 tracker.deliverResult(mContext);
5979 } break;
5980 }
5981 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005982 }
5983
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005984 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005985 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005986
5987 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005988 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005989 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005990
5991 @Override
5992 public void handleMessage(Message msg) {
5993 switch (msg.what) {
5994 case DISMISS_DIALOG_UI_MSG: {
5995 final Dialog d = (Dialog) msg.obj;
5996 d.dismiss();
5997 break;
5998 }
5999 }
6000 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006001 }
6002
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 final class LocalService extends ActivityTaskManagerInternal {
6004 @Override
6005 public SleepToken acquireSleepToken(String tag, int displayId) {
6006 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006007 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 }
6009
6010 @Override
6011 public ComponentName getHomeActivityForUser(int userId) {
6012 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006013 final ActivityRecord homeActivity =
6014 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006015 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006016 }
6017 }
6018
6019 @Override
6020 public void onLocalVoiceInteractionStarted(IBinder activity,
6021 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6022 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006023 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024 }
6025 }
6026
6027 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006028 public void notifyAppTransitionStarting(SparseIntArray reasons,
6029 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006030 synchronized (mGlobalLock) {
6031 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6032 reasons, timestamp);
6033 }
6034 }
6035
6036 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006037 public void notifySingleTaskDisplayDrawn(int displayId) {
6038 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6039 }
6040
6041 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006042 public void notifyAppTransitionFinished() {
6043 synchronized (mGlobalLock) {
6044 mStackSupervisor.notifyAppTransitionDone();
6045 }
6046 }
6047
6048 @Override
6049 public void notifyAppTransitionCancelled() {
6050 synchronized (mGlobalLock) {
6051 mStackSupervisor.notifyAppTransitionDone();
6052 }
6053 }
6054
6055 @Override
6056 public List<IBinder> getTopVisibleActivities() {
6057 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006058 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060 }
6061
6062 @Override
6063 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6064 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006065 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067 }
6068
6069 @Override
6070 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6071 Bundle bOptions) {
6072 Preconditions.checkNotNull(intents, "intents");
6073 final String[] resolvedTypes = new String[intents.length];
6074
6075 // UID of the package on user userId.
6076 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6077 // packageUid may not be initialized.
6078 int packageUid = 0;
6079 final long ident = Binder.clearCallingIdentity();
6080
6081 try {
6082 for (int i = 0; i < intents.length; i++) {
6083 resolvedTypes[i] =
6084 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6085 }
6086
6087 packageUid = AppGlobals.getPackageManager().getPackageUid(
6088 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6089 } catch (RemoteException e) {
6090 // Shouldn't happen.
6091 } finally {
6092 Binder.restoreCallingIdentity(ident);
6093 }
6094
Riddle Hsu591bf612019-02-14 17:55:31 +08006095 return getActivityStartController().startActivitiesInPackage(
6096 packageUid, packageName,
6097 intents, resolvedTypes, null /* resultTo */,
6098 SafeActivityOptions.fromBundle(bOptions), userId,
6099 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6100 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 }
6102
6103 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006104 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6105 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6106 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6107 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006108 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006109 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006110 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6111 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6112 userId, validateIncomingUser, originatingPendingIntent,
6113 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006114 }
6115 }
6116
6117 @Override
6118 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6119 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6120 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6121 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006122 PendingIntentRecord originatingPendingIntent,
6123 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006124 synchronized (mGlobalLock) {
6125 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6126 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6127 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006128 validateIncomingUser, originatingPendingIntent,
6129 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006130 }
6131 }
6132
6133 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6135 Intent intent, Bundle options, int userId) {
6136 return ActivityTaskManagerService.this.startActivityAsUser(
6137 caller, callerPacakge, intent,
6138 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6139 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6140 false /*validateIncomingUser*/);
6141 }
6142
6143 @Override
lumark588a3e82018-07-20 18:53:54 +08006144 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 synchronized (mGlobalLock) {
6146
6147 // We might change the visibilities here, so prepare an empty app transition which
6148 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006149 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006150 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006151 if (activityDisplay == null) {
6152 return;
6153 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006154 final DisplayContent dc = activityDisplay.mDisplayContent;
6155 final boolean wasTransitionSet =
6156 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006158 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006160 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161
6162 // If there was a transition set already we don't want to interfere with it as we
6163 // might be starting it too early.
6164 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006165 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167 }
6168 if (callback != null) {
6169 callback.run();
6170 }
6171 }
6172
6173 @Override
6174 public void notifyKeyguardTrustedChanged() {
6175 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006176 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006177 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179 }
6180 }
6181
6182 /**
6183 * Called after virtual display Id is updated by
6184 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6185 * {@param vrVr2dDisplayId}.
6186 */
6187 @Override
6188 public void setVr2dDisplayId(int vr2dDisplayId) {
6189 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6190 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006191 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 }
6193 }
6194
6195 @Override
6196 public void setFocusedActivity(IBinder token) {
6197 synchronized (mGlobalLock) {
6198 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6199 if (r == null) {
6200 throw new IllegalArgumentException(
6201 "setFocusedActivity: No activity record matching token=" + token);
6202 }
Louis Chang19443452018-10-09 12:10:21 +08006203 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006204 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 }
6206 }
6207 }
6208
6209 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006210 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006211 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 }
6213
6214 @Override
6215 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006216 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006217 }
6218
6219 @Override
6220 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006221 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223
6224 @Override
6225 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6226 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6227 }
6228
6229 @Override
6230 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006231 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006233
6234 @Override
6235 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6236 synchronized (mGlobalLock) {
6237 mActiveVoiceInteractionServiceComponent = component;
6238 }
6239 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006240
6241 @Override
6242 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6243 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6244 return;
6245 }
6246 synchronized (mGlobalLock) {
6247 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6248 if (types == null) {
6249 if (uid < 0) {
6250 return;
6251 }
6252 types = new ArrayMap<>();
6253 mAllowAppSwitchUids.put(userId, types);
6254 }
6255 if (uid < 0) {
6256 types.remove(type);
6257 } else {
6258 types.put(type, uid);
6259 }
6260 }
6261 }
6262
6263 @Override
6264 public void onUserStopped(int userId) {
6265 synchronized (mGlobalLock) {
6266 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6267 mAllowAppSwitchUids.remove(userId);
6268 }
6269 }
6270
6271 @Override
6272 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6273 synchronized (mGlobalLock) {
6274 return ActivityTaskManagerService.this.isGetTasksAllowed(
6275 caller, callingPid, callingUid);
6276 }
6277 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006278
Riddle Hsua0536432019-02-16 00:38:59 +08006279 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006280 @Override
6281 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006282 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006283 mProcessNames.put(proc.mName, proc.mUid, proc);
6284 }
6285 }
6286
Riddle Hsua0536432019-02-16 00:38:59 +08006287 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006288 @Override
6289 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006290 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006291 mProcessNames.remove(name, uid);
6292 }
6293 }
6294
Riddle Hsua0536432019-02-16 00:38:59 +08006295 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006296 @Override
6297 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006298 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006299 if (proc == mHomeProcess) {
6300 mHomeProcess = null;
6301 }
6302 if (proc == mPreviousProcess) {
6303 mPreviousProcess = null;
6304 }
6305 }
6306 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006307
Riddle Hsua0536432019-02-16 00:38:59 +08006308 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 @Override
6310 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006311 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 return mTopProcessState;
6313 }
6314 }
6315
Riddle Hsua0536432019-02-16 00:38:59 +08006316 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006317 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006318 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006319 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006320 return proc == mHeavyWeightProcess;
6321 }
6322 }
6323
Riddle Hsua0536432019-02-16 00:38:59 +08006324 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006325 @Override
6326 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006328 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6329 }
6330 }
6331
6332 @Override
6333 public void finishHeavyWeightApp() {
6334 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006335 if (mHeavyWeightProcess != null) {
6336 mHeavyWeightProcess.finishActivities();
6337 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006338 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6339 mHeavyWeightProcess);
6340 }
6341 }
6342
Riddle Hsua0536432019-02-16 00:38:59 +08006343 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006344 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006345 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006346 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006347 return isSleepingLocked();
6348 }
6349 }
6350
6351 @Override
6352 public boolean isShuttingDown() {
6353 synchronized (mGlobalLock) {
6354 return mShuttingDown;
6355 }
6356 }
6357
6358 @Override
6359 public boolean shuttingDown(boolean booted, int timeout) {
6360 synchronized (mGlobalLock) {
6361 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006362 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006363 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006364 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006365 return mStackSupervisor.shutdownLocked(timeout);
6366 }
6367 }
6368
6369 @Override
6370 public void enableScreenAfterBoot(boolean booted) {
6371 synchronized (mGlobalLock) {
6372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6373 SystemClock.uptimeMillis());
6374 mWindowManager.enableScreenAfterBoot();
6375 updateEventDispatchingLocked(booted);
6376 }
6377 }
6378
6379 @Override
6380 public boolean showStrictModeViolationDialog() {
6381 synchronized (mGlobalLock) {
6382 return mShowDialogs && !mSleeping && !mShuttingDown;
6383 }
6384 }
6385
6386 @Override
6387 public void showSystemReadyErrorDialogsIfNeeded() {
6388 synchronized (mGlobalLock) {
6389 try {
6390 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6391 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6392 + " data partition or your device will be unstable.");
6393 mUiHandler.post(() -> {
6394 if (mShowDialogs) {
6395 AlertDialog d = new BaseErrorDialog(mUiContext);
6396 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6397 d.setCancelable(false);
6398 d.setTitle(mUiContext.getText(R.string.android_system_label));
6399 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6400 d.setButton(DialogInterface.BUTTON_POSITIVE,
6401 mUiContext.getText(R.string.ok),
6402 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6403 d.show();
6404 }
6405 });
6406 }
6407 } catch (RemoteException e) {
6408 }
6409
6410 if (!Build.isBuildConsistent()) {
6411 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6412 mUiHandler.post(() -> {
6413 if (mShowDialogs) {
6414 AlertDialog d = new BaseErrorDialog(mUiContext);
6415 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6416 d.setCancelable(false);
6417 d.setTitle(mUiContext.getText(R.string.android_system_label));
6418 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6419 d.setButton(DialogInterface.BUTTON_POSITIVE,
6420 mUiContext.getText(R.string.ok),
6421 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6422 d.show();
6423 }
6424 });
6425 }
6426 }
6427 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006428
6429 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006430 public void onProcessMapped(int pid, WindowProcessController proc) {
6431 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006432 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006433 }
6434 }
6435
6436 @Override
6437 public void onProcessUnMapped(int pid) {
6438 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006439 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006440 }
6441 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006442
6443 @Override
6444 public void onPackageDataCleared(String name) {
6445 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006446 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006447 mAppWarnings.onPackageDataCleared(name);
6448 }
6449 }
6450
6451 @Override
6452 public void onPackageUninstalled(String name) {
6453 synchronized (mGlobalLock) {
6454 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006456 }
6457 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006458
6459 @Override
6460 public void onPackageAdded(String name, boolean replacing) {
6461 synchronized (mGlobalLock) {
6462 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6463 }
6464 }
6465
6466 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006467 public void onPackageReplaced(ApplicationInfo aInfo) {
6468 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006469 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006470 }
6471 }
6472
6473 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006474 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6475 synchronized (mGlobalLock) {
6476 return compatibilityInfoForPackageLocked(ai);
6477 }
6478 }
6479
Yunfan Chen75157d72018-07-27 14:47:21 +09006480 /**
6481 * Set the corresponding display information for the process global configuration. To be
6482 * called when we need to show IME on a different display.
6483 *
6484 * @param pid The process id associated with the IME window.
6485 * @param displayId The ID of the display showing the IME.
6486 */
6487 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006488 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006489 // Don't update process-level configuration for Multi-Client IME process since other
6490 // IMEs on other displays will also receive this configuration change due to IME
6491 // services use the same application config/context.
6492 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006493
Yunfan Chen75157d72018-07-27 14:47:21 +09006494 if (pid == MY_PID || pid < 0) {
6495 if (DEBUG_CONFIGURATION) {
6496 Slog.w(TAG,
6497 "Trying to update display configuration for system/invalid process.");
6498 }
6499 return;
6500 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006501 synchronized (mGlobalLock) {
6502 final ActivityDisplay activityDisplay =
6503 mRootActivityContainer.getActivityDisplay(displayId);
6504 if (activityDisplay == null) {
6505 // Call might come when display is not yet added or has been removed.
6506 if (DEBUG_CONFIGURATION) {
6507 Slog.w(TAG, "Trying to update display configuration for non-existing "
6508 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006509 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006510 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006511 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006512 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006513 if (process == null) {
6514 if (DEBUG_CONFIGURATION) {
6515 Slog.w(TAG, "Trying to update display configuration for invalid "
6516 + "process, pid=" + pid);
6517 }
6518 return;
6519 }
lumarkddc77fb2019-06-27 22:22:23 +08006520 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006521 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6522 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006523 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006524
6525 @Override
6526 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006527 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006528 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006529 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6530 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006531 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006532 }
6533 }
6534 }
6535
6536 @Override
6537 public void clearPendingResultForActivity(IBinder activityToken,
6538 WeakReference<PendingIntentRecord> pir) {
6539 synchronized (mGlobalLock) {
6540 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6541 if (r != null && r.pendingResults != null) {
6542 r.pendingResults.remove(pir);
6543 }
6544 }
6545 }
6546
6547 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006548 public ActivityTokens getTopActivityForTask(int taskId) {
6549 synchronized (mGlobalLock) {
6550 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6551 if (taskRecord == null) {
6552 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6553 + " Requested task not found");
6554 return null;
6555 }
6556 final ActivityRecord activity = taskRecord.getTopActivity();
6557 if (activity == null) {
6558 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6559 + " Requested activity not found");
6560 return null;
6561 }
6562 if (!activity.attachedToProcess()) {
6563 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6564 + activity);
6565 return null;
6566 }
6567 return new ActivityTokens(activity.appToken, activity.assistToken,
6568 activity.app.getThread());
6569 }
6570 }
6571
6572 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006573 public IIntentSender getIntentSender(int type, String packageName,
6574 int callingUid, int userId, IBinder token, String resultWho,
6575 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6576 Bundle bOptions) {
6577 synchronized (mGlobalLock) {
6578 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6579 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6580 }
6581 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006582
6583 @Override
6584 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6585 synchronized (mGlobalLock) {
6586 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6587 if (r == null) {
6588 return null;
6589 }
6590 if (r.mServiceConnectionsHolder == null) {
6591 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6592 ActivityTaskManagerService.this, r);
6593 }
6594
6595 return r.mServiceConnectionsHolder;
6596 }
6597 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006598
6599 @Override
6600 public Intent getHomeIntent() {
6601 synchronized (mGlobalLock) {
6602 return ActivityTaskManagerService.this.getHomeIntent();
6603 }
6604 }
6605
6606 @Override
6607 public boolean startHomeActivity(int userId, String reason) {
6608 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006609 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006610 }
6611 }
6612
6613 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006614 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006615 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006616 synchronized (mGlobalLock) {
6617 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006618 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006619 }
Chilun8b1f1be2019-03-13 17:14:36 +08006620 }
6621
6622 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006623 public boolean startHomeOnAllDisplays(int userId, String reason) {
6624 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006625 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006626 }
6627 }
6628
Riddle Hsua0536432019-02-16 00:38:59 +08006629 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006630 @Override
6631 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006632 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006633 if (mFactoryTest == FACTORY_TEST_OFF) {
6634 return false;
6635 }
6636 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6637 && wpc.mName.equals(mTopComponent.getPackageName())) {
6638 return true;
6639 }
6640 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6641 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6642 }
6643 }
6644
6645 @Override
6646 public void updateTopComponentForFactoryTest() {
6647 synchronized (mGlobalLock) {
6648 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6649 return;
6650 }
6651 final ResolveInfo ri = mContext.getPackageManager()
6652 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6653 final CharSequence errorMsg;
6654 if (ri != null) {
6655 final ActivityInfo ai = ri.activityInfo;
6656 final ApplicationInfo app = ai.applicationInfo;
6657 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6658 mTopAction = Intent.ACTION_FACTORY_TEST;
6659 mTopData = null;
6660 mTopComponent = new ComponentName(app.packageName, ai.name);
6661 errorMsg = null;
6662 } else {
6663 errorMsg = mContext.getResources().getText(
6664 com.android.internal.R.string.factorytest_not_system);
6665 }
6666 } else {
6667 errorMsg = mContext.getResources().getText(
6668 com.android.internal.R.string.factorytest_no_action);
6669 }
6670 if (errorMsg == null) {
6671 return;
6672 }
6673
6674 mTopAction = null;
6675 mTopData = null;
6676 mTopComponent = null;
6677 mUiHandler.post(() -> {
6678 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6679 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006680 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006681 });
6682 }
6683 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006684
Riddle Hsua0536432019-02-16 00:38:59 +08006685 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006686 @Override
6687 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6688 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006689 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006690 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006691 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692
6693 wpc.clearRecentTasks();
6694 wpc.clearActivities();
6695
6696 if (wpc.isInstrumenting()) {
6697 finishInstrumentationCallback.run();
6698 }
6699
Jorim Jaggid0752812018-10-16 16:07:20 +02006700 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006701 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006702 try {
6703 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6704 // If there was nothing to resume, and we are not already restarting
6705 // this process, but there is a visible activity that is hosted by the
6706 // process...then make sure all visible activities are running, taking
6707 // care of restarting this process.
6708 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6709 !PRESERVE_WINDOWS);
6710 }
6711 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006712 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714 }
6715 }
6716 }
6717
6718 @Override
6719 public void closeSystemDialogs(String reason) {
6720 enforceNotIsolatedCaller("closeSystemDialogs");
6721
6722 final int pid = Binder.getCallingPid();
6723 final int uid = Binder.getCallingUid();
6724 final long origId = Binder.clearCallingIdentity();
6725 try {
6726 synchronized (mGlobalLock) {
6727 // Only allow this from foreground processes, so that background
6728 // applications can't abuse it to prevent system UI from being shown.
6729 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006730 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 if (!proc.isPerceptible()) {
6732 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6733 + " from background process " + proc);
6734 return;
6735 }
6736 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 mWindowManager.closeSystemDialogs(reason);
6738
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006741 // Call into AM outside the synchronized block.
6742 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 } finally {
6744 Binder.restoreCallingIdentity(origId);
6745 }
6746 }
6747
6748 @Override
6749 public void cleanupDisabledPackageComponents(
6750 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6751 synchronized (mGlobalLock) {
6752 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006753 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006755 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006756 mStackSupervisor.scheduleIdleLocked();
6757 }
6758
6759 // Clean-up disabled tasks
6760 getRecentTasks().cleanupDisabledPackageTasksLocked(
6761 packageName, disabledClasses, userId);
6762 }
6763 }
6764
6765 @Override
6766 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6767 int userId) {
6768 synchronized (mGlobalLock) {
6769
6770 boolean didSomething =
6771 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006772 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 null, doit, evenPersistent, userId);
6774 return didSomething;
6775 }
6776 }
6777
6778 @Override
6779 public void resumeTopActivities(boolean scheduleIdle) {
6780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 if (scheduleIdle) {
6783 mStackSupervisor.scheduleIdleLocked();
6784 }
6785 }
6786 }
6787
Riddle Hsua0536432019-02-16 00:38:59 +08006788 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 @Override
6790 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006791 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6793 }
6794 }
6795
Riddle Hsua0536432019-02-16 00:38:59 +08006796 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 @Override
6798 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006799 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 }
6802 }
6803
6804 @Override
6805 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6806 try {
6807 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6808 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6809 }
6810 } catch (RemoteException ex) {
6811 throw new SecurityException("Fail to check is caller a privileged app", ex);
6812 }
6813
6814 synchronized (mGlobalLock) {
6815 final long ident = Binder.clearCallingIdentity();
6816 try {
6817 if (mAmInternal.shouldConfirmCredentials(userId)) {
6818 if (mKeyguardController.isKeyguardLocked()) {
6819 // Showing launcher to avoid user entering credential twice.
6820 startHomeActivity(currentUserId, "notifyLockedProfile");
6821 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006822 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 }
6824 } finally {
6825 Binder.restoreCallingIdentity(ident);
6826 }
6827 }
6828 }
6829
6830 @Override
6831 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6832 mAmInternal.enforceCallingPermission(
6833 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6834
6835 synchronized (mGlobalLock) {
6836 final long ident = Binder.clearCallingIdentity();
6837 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006838 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6839 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6842 UserHandle.CURRENT);
6843 } finally {
6844 Binder.restoreCallingIdentity(ident);
6845 }
6846 }
6847 }
6848
6849 @Override
6850 public void writeActivitiesToProto(ProtoOutputStream proto) {
6851 synchronized (mGlobalLock) {
6852 // The output proto of "activity --proto activities"
6853 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006854 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006855 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6856 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 }
6858 }
6859
6860 @Override
6861 public void saveANRState(String reason) {
6862 synchronized (mGlobalLock) {
6863 final StringWriter sw = new StringWriter();
6864 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6865 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6866 if (reason != null) {
6867 pw.println(" Reason: " + reason);
6868 }
6869 pw.println();
6870 getActivityStartController().dump(pw, " ", null);
6871 pw.println();
6872 pw.println("-------------------------------------------------------------------------------");
6873 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6874 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6875 "" /* header */);
6876 pw.println();
6877 pw.close();
6878
6879 mLastANRState = sw.toString();
6880 }
6881 }
6882
6883 @Override
6884 public void clearSavedANRState() {
6885 synchronized (mGlobalLock) {
6886 mLastANRState = null;
6887 }
6888 }
6889
6890 @Override
6891 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6892 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6893 synchronized (mGlobalLock) {
6894 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6895 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6896 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6897 dumpLastANRLocked(pw);
6898 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6899 dumpLastANRTracesLocked(pw);
6900 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6901 dumpActivityStarterLocked(pw, dumpPackage);
6902 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6903 dumpActivityContainersLocked(pw);
6904 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6905 if (getRecentTasks() != null) {
6906 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6907 }
6908 }
6909 }
6910 }
6911
6912 @Override
6913 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6914 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6915 int wakefulness) {
6916 synchronized (mGlobalLock) {
6917 if (mHomeProcess != null && (dumpPackage == null
6918 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6919 if (needSep) {
6920 pw.println();
6921 needSep = false;
6922 }
6923 pw.println(" mHomeProcess: " + mHomeProcess);
6924 }
6925 if (mPreviousProcess != null && (dumpPackage == null
6926 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6927 if (needSep) {
6928 pw.println();
6929 needSep = false;
6930 }
6931 pw.println(" mPreviousProcess: " + mPreviousProcess);
6932 }
6933 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6934 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6935 StringBuilder sb = new StringBuilder(128);
6936 sb.append(" mPreviousProcessVisibleTime: ");
6937 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6938 pw.println(sb);
6939 }
6940 if (mHeavyWeightProcess != null && (dumpPackage == null
6941 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6942 if (needSep) {
6943 pw.println();
6944 needSep = false;
6945 }
6946 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6947 }
6948 if (dumpPackage == null) {
6949 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006950 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006951 }
6952 if (dumpAll) {
6953 if (dumpPackage == null) {
6954 pw.println(" mConfigWillChange: "
6955 + getTopDisplayFocusedStack().mConfigWillChange);
6956 }
6957 if (mCompatModePackages.getPackages().size() > 0) {
6958 boolean printed = false;
6959 for (Map.Entry<String, Integer> entry
6960 : mCompatModePackages.getPackages().entrySet()) {
6961 String pkg = entry.getKey();
6962 int mode = entry.getValue();
6963 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6964 continue;
6965 }
6966 if (!printed) {
6967 pw.println(" mScreenCompatPackages:");
6968 printed = true;
6969 }
6970 pw.println(" " + pkg + ": " + mode);
6971 }
6972 }
6973 }
6974
6975 if (dumpPackage == null) {
6976 pw.println(" mWakefulness="
6977 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006978 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 if (mRunningVoice != null) {
6980 pw.println(" mRunningVoice=" + mRunningVoice);
6981 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6982 }
6983 pw.println(" mSleeping=" + mSleeping);
6984 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6985 pw.println(" mVrController=" + mVrController);
6986 }
6987 if (mCurAppTimeTracker != null) {
6988 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6989 }
6990 if (mAllowAppSwitchUids.size() > 0) {
6991 boolean printed = false;
6992 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6993 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6994 for (int j = 0; j < types.size(); j++) {
6995 if (dumpPackage == null ||
6996 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6997 if (needSep) {
6998 pw.println();
6999 needSep = false;
7000 }
7001 if (!printed) {
7002 pw.println(" mAllowAppSwitchUids:");
7003 printed = true;
7004 }
7005 pw.print(" User ");
7006 pw.print(mAllowAppSwitchUids.keyAt(i));
7007 pw.print(": Type ");
7008 pw.print(types.keyAt(j));
7009 pw.print(" = ");
7010 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7011 pw.println();
7012 }
7013 }
7014 }
7015 }
7016 if (dumpPackage == null) {
7017 if (mController != null) {
7018 pw.println(" mController=" + mController
7019 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7020 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007021 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7022 pw.println(" mLaunchingActivityWakeLock="
7023 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007024 }
7025
7026 return needSep;
7027 }
7028 }
7029
7030 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007031 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7032 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 synchronized (mGlobalLock) {
7034 if (dumpPackage == null) {
7035 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7036 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007037 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7038 if (mRunningVoice != null) {
7039 final long vrToken = proto.start(
7040 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7041 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7042 mRunningVoice.toString());
7043 mVoiceWakeLock.writeToProto(
7044 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7045 proto.end(vrToken);
7046 }
7047 mVrController.writeToProto(proto,
7048 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007049 if (mController != null) {
7050 final long token = proto.start(CONTROLLER);
7051 proto.write(CONTROLLER, mController.toString());
7052 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7053 proto.end(token);
7054 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007055 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7056 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7057 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007058 }
7059
7060 if (mHomeProcess != null && (dumpPackage == null
7061 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007062 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 }
7064
7065 if (mPreviousProcess != null && (dumpPackage == null
7066 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007067 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7069 }
7070
7071 if (mHeavyWeightProcess != null && (dumpPackage == null
7072 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007073 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007074 }
7075
7076 for (Map.Entry<String, Integer> entry
7077 : mCompatModePackages.getPackages().entrySet()) {
7078 String pkg = entry.getKey();
7079 int mode = entry.getValue();
7080 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7081 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7082 proto.write(PACKAGE, pkg);
7083 proto.write(MODE, mode);
7084 proto.end(compatToken);
7085 }
7086 }
7087
7088 if (mCurAppTimeTracker != null) {
7089 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7090 }
7091
7092 }
7093 }
7094
7095 @Override
7096 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7097 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7098 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007099 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7100 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 }
7102
7103 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007104 public void dumpForOom(PrintWriter pw) {
7105 synchronized (mGlobalLock) {
7106 pw.println(" mHomeProcess: " + mHomeProcess);
7107 pw.println(" mPreviousProcess: " + mPreviousProcess);
7108 if (mHeavyWeightProcess != null) {
7109 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7110 }
7111 }
7112 }
7113
7114 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 public boolean canGcNow() {
7116 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007117 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 }
7119 }
7120
Riddle Hsua0536432019-02-16 00:38:59 +08007121 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 @Override
7123 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007124 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007125 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007126 return top != null ? top.app : null;
7127 }
7128 }
7129
Riddle Hsua0536432019-02-16 00:38:59 +08007130 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 @Override
7132 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007133 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007134 if (mRootActivityContainer != null) {
7135 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007136 }
7137 }
7138 }
7139
7140 @Override
7141 public void scheduleDestroyAllActivities(String reason) {
7142 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007143 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007144 }
7145 }
7146
7147 @Override
7148 public void removeUser(int userId) {
7149 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007150 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152 }
7153
7154 @Override
7155 public boolean switchUser(int userId, UserState userState) {
7156 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007157 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007158 }
7159 }
7160
7161 @Override
7162 public void onHandleAppCrash(WindowProcessController wpc) {
7163 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007164 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 }
7166 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007167
7168 @Override
7169 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7170 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007171 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007172 }
7173 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007174
Riddle Hsua0536432019-02-16 00:38:59 +08007175 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007176 @Override
7177 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007178 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007179 }
7180
Riddle Hsua0536432019-02-16 00:38:59 +08007181 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007182 @Override
7183 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007184 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007185 }
7186
Riddle Hsua0536432019-02-16 00:38:59 +08007187 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007188 @Override
7189 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007190 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007191 }
7192
Riddle Hsua0536432019-02-16 00:38:59 +08007193 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007194 @Override
7195 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007196 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007197 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007198
7199 @Override
7200 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007201 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007202 mPendingTempWhitelist.put(uid, tag);
7203 }
7204 }
7205
7206 @Override
7207 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007208 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007209 mPendingTempWhitelist.remove(uid);
7210 }
7211 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007212
7213 @Override
7214 public boolean handleAppCrashInActivityController(String processName, int pid,
7215 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7216 Runnable killCrashingAppCallback) {
7217 synchronized (mGlobalLock) {
7218 if (mController == null) {
7219 return false;
7220 }
7221
7222 try {
7223 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7224 stackTrace)) {
7225 killCrashingAppCallback.run();
7226 return true;
7227 }
7228 } catch (RemoteException e) {
7229 mController = null;
7230 Watchdog.getInstance().setActivityController(null);
7231 }
7232 return false;
7233 }
7234 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007235
7236 @Override
7237 public void removeRecentTasksByPackageName(String packageName, int userId) {
7238 synchronized (mGlobalLock) {
7239 mRecentTasks.removeTasksByPackageName(packageName, userId);
7240 }
7241 }
7242
7243 @Override
7244 public void cleanupRecentTasksForUser(int userId) {
7245 synchronized (mGlobalLock) {
7246 mRecentTasks.cleanupLocked(userId);
7247 }
7248 }
7249
7250 @Override
7251 public void loadRecentTasksForUser(int userId) {
7252 synchronized (mGlobalLock) {
7253 mRecentTasks.loadUserRecentsLocked(userId);
7254 }
7255 }
7256
7257 @Override
7258 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7259 synchronized (mGlobalLock) {
7260 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7261 }
7262 }
7263
7264 @Override
7265 public void flushRecentTasks() {
7266 mRecentTasks.flush();
7267 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007268
7269 @Override
7270 public WindowProcessController getHomeProcess() {
7271 synchronized (mGlobalLock) {
7272 return mHomeProcess;
7273 }
7274 }
7275
7276 @Override
7277 public WindowProcessController getPreviousProcess() {
7278 synchronized (mGlobalLock) {
7279 return mPreviousProcess;
7280 }
7281 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007282
7283 @Override
7284 public void clearLockedTasks(String reason) {
7285 synchronized (mGlobalLock) {
7286 getLockTaskController().clearLockedTasks(reason);
7287 }
7288 }
7289
7290 @Override
7291 public void updateUserConfiguration() {
7292 synchronized (mGlobalLock) {
7293 final Configuration configuration = new Configuration(getGlobalConfiguration());
7294 final int currentUserId = mAmInternal.getCurrentUserId();
7295 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7296 configuration, currentUserId, Settings.System.canWrite(mContext));
7297 updateConfigurationLocked(configuration, null /* starting */,
7298 false /* initLocale */, false /* persistent */, currentUserId,
7299 false /* deferResume */);
7300 }
7301 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007302
7303 @Override
7304 public boolean canShowErrorDialogs() {
7305 synchronized (mGlobalLock) {
7306 return mShowDialogs && !mSleeping && !mShuttingDown
7307 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7308 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7309 mAmInternal.getCurrentUserId())
7310 && !(UserManager.isDeviceInDemoMode(mContext)
7311 && mAmInternal.getCurrentUser().isDemo());
7312 }
7313 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007314
7315 @Override
7316 public void setProfileApp(String profileApp) {
7317 synchronized (mGlobalLock) {
7318 mProfileApp = profileApp;
7319 }
7320 }
7321
7322 @Override
7323 public void setProfileProc(WindowProcessController wpc) {
7324 synchronized (mGlobalLock) {
7325 mProfileProc = wpc;
7326 }
7327 }
7328
7329 @Override
7330 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7331 synchronized (mGlobalLock) {
7332 mProfilerInfo = profilerInfo;
7333 }
7334 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007335
7336 @Override
7337 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7338 synchronized (mGlobalLock) {
7339 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7340 }
7341 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007342
7343 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007344 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7345 boolean reducedResolution) {
7346 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7347 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007348 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007349
7350 @Override
7351 public boolean isUidForeground(int uid) {
7352 synchronized (mGlobalLock) {
7353 return ActivityTaskManagerService.this.isUidForeground(uid);
7354 }
7355 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007356
7357 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007358 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007359 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007360 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007361 }
7362 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007363
7364 @Override
7365 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007366 // Translate package names into UIDs
7367 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007368 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007369 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7370 if (uid >= 0) {
7371 result.add(uid);
7372 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007373 }
7374 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007375 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007376 }
7377 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007378 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007379}