blob: a326843ccb033ae8ae1ecad03a027c567e0baf48 [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;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
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 Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
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;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800227import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100248import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800277import java.lang.annotation.ElementType;
278import java.lang.annotation.Retention;
279import java.lang.annotation.RetentionPolicy;
280import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700284import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400286import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700289import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Map;
291import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292
293/**
294 * System service for managing activities and their containers (task, stacks, displays,... ).
295 *
296 * {@hide}
297 */
298public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700299 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700301 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
302 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
303 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
304 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
305 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700306 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700307
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700309 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312
Wale Ogunwale98875612018-10-12 07:53:02 -0700313 /** Used to indicate that an app transition should be animated. */
314 static final boolean ANIMATE = true;
315
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700316 /** Hardware-reported OpenGLES version. */
317 final int GL_ES_VERSION;
318
Wale Ogunwale31913b52018-10-13 08:29:31 -0700319 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
320 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
321 public static final String DUMP_LASTANR_CMD = "lastanr" ;
322 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
323 public static final String DUMP_STARTER_CMD = "starter" ;
324 public static final String DUMP_CONTAINERS_CMD = "containers" ;
325 public static final String DUMP_RECENTS_CMD = "recents" ;
326 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
327
Wale Ogunwale64258362018-10-16 15:13:37 -0700328 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
329 public static final int RELAUNCH_REASON_NONE = 0;
330 /** This activity is being relaunched due to windowing mode change. */
331 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
332 /** This activity is being relaunched due to a free-resize operation. */
333 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
334
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700335 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700336
Wale Ogunwalef6733932018-06-27 05:14:34 -0700337 /**
338 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
339 * change at runtime. Use mContext for non-UI purposes.
340 */
341 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700342 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700343 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700345 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700346 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700347 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800348 @VisibleForTesting
349 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 PowerManagerInternal mPowerManagerInternal;
351 private UsageStatsManagerInternal mUsageStatsInternal;
352
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700353 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 IntentFirewall mIntentFirewall;
355
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700356 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800357 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800358 /**
359 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
360 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
361 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
362 *
363 * @see WindowManagerThreadPriorityBooster
364 */
365 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700366 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800367 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700368 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700369 private UserManagerService mUserManager;
370 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700371 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800372 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700373 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700374 /** All processes currently running that might have a window organized by name. */
375 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700376 /** All processes we currently have running mapped by pid */
377 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700378 /** This is the process holding what we currently consider to be the "home" activity. */
379 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700380 /** The currently running heavy-weight process, if any. */
381 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700382 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /**
384 * This is the process holding the activity the user last visited that is in a different process
385 * from the one they are currently in.
386 */
387 WindowProcessController mPreviousProcess;
388 /** The time at which the previous process was last visible. */
389 long mPreviousProcessVisibleTime;
390
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700391 /** List of intents that were used to start the most recent tasks. */
392 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700393 /** State of external calls telling us if the device is awake or asleep. */
394 private boolean mKeyguardShown = false;
395
396 // Wrapper around VoiceInteractionServiceManager
397 private AssistUtils mAssistUtils;
398
399 // VoiceInteraction session ID that changes for each new request except when
400 // being called for multi-window assist in a single session.
401 private int mViSessionId = 1000;
402
403 // How long to wait in getAssistContextExtras for the activity and foreground services
404 // to respond with the result.
405 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
406
407 // How long top wait when going through the modern assist (which doesn't need to block
408 // on getting this result before starting to launch its UI).
409 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
410
411 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
412 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
413
Alison Cichowlas3e340502018-08-07 17:15:01 -0400414 // Permission tokens are used to temporarily granted a trusted app the ability to call
415 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
416 // showing any appropriate error messages to the user.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
418 10 * MINUTE_IN_MILLIS;
419
420 // How long before the service actually expires a token. This is slightly longer than
421 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
422 // expiration exception.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
424 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
425
426 // How long the service will remember expired tokens, for the purpose of providing error
427 // messaging when a client uses an expired token.
428 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
429 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
430
Marvin Ramin830d4e32019-03-12 13:16:58 +0100431 // How long to whitelist the Services for when requested.
432 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
433
Alison Cichowlas3e340502018-08-07 17:15:01 -0400434 // Activity tokens of system activities that are delegating their call to
435 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
436 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
437
438 // Permission tokens that have expired, but we remember for error reporting.
439 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700441 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
442
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700443 // Keeps track of the active voice interaction service component, notified from
444 // VoiceInteractionManagerService
445 ComponentName mActiveVoiceInteractionServiceComponent;
446
Michal Karpinskida34cd42019-04-02 19:46:52 +0100447 // A map userId and all its companion app uids
448 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000449
Wale Ogunwalee2172292018-10-25 10:11:10 -0700450 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 KeyguardController mKeyguardController;
452 private final ClientLifecycleManager mLifecycleManager;
453 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700454 /** The controller for all operations related to locktask. */
455 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700456 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700458 boolean mSuppressResizeConfigChanges;
459
460 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
461 new UpdateConfigurationResult();
462
463 static final class UpdateConfigurationResult {
464 // Configuration changes that were updated.
465 int changes;
466 // If the activity was relaunched to match the new configuration.
467 boolean activityRelaunched;
468
469 void reset() {
470 changes = 0;
471 activityRelaunched = false;
472 }
473 }
474
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700475 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700476 private int mConfigurationSeq;
477 // To cache the list of supported system locales
478 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479
480 /**
481 * Temp object used when global and/or display override configuration is updated. It is also
482 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
483 * anyone...
484 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private Configuration mTempConfig = new Configuration();
486
Wale Ogunwalef6733932018-06-27 05:14:34 -0700487 /** Temporary to avoid allocations. */
488 final StringBuilder mStringBuilder = new StringBuilder(256);
489
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 // Amount of time after a call to stopAppSwitches() during which we will
491 // prevent further untrusted switches from happening.
492 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
493
494 /**
495 * The time at which we will allow normal application switches again,
496 * after a call to {@link #stopAppSwitches()}.
497 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700498 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 /**
500 * This is set to true after the first switch after mAppSwitchesAllowedTime
501 * is set; any switches after that will clear the time.
502 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700503 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504
505 IActivityController mController = null;
506 boolean mControllerIsAMonkey = false;
507
Wale Ogunwale214f3482018-10-04 11:00:47 -0700508 final int mFactoryTest;
509
510 /** Used to control how we initialize the service. */
511 ComponentName mTopComponent;
512 String mTopAction = Intent.ACTION_MAIN;
513 String mTopData;
514
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800515 /** Profiling app information. */
516 String mProfileApp = null;
517 WindowProcessController mProfileProc = null;
518 ProfilerInfo mProfilerInfo = null;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700521 * Dump of the activity state at the time of the last ANR. Cleared after
522 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
523 */
524 String mLastANRState;
525
526 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527 * Used to retain an update lock when the foreground activity is in
528 * immersive mode.
529 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700530 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531
532 /**
533 * Packages that are being allowed to perform unrestricted app switches. Mapping is
534 * User -> Type -> uid.
535 */
536 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
537
538 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700539 private int mThumbnailWidth;
540 private int mThumbnailHeight;
541 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542
543 /**
544 * Flag that indicates if multi-window is enabled.
545 *
546 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
547 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
548 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
549 * At least one of the forms of multi-window must be enabled in order for this flag to be
550 * initialized to 'true'.
551 *
552 * @see #mSupportsSplitScreenMultiWindow
553 * @see #mSupportsFreeformWindowManagement
554 * @see #mSupportsPictureInPicture
555 * @see #mSupportsMultiDisplay
556 */
557 boolean mSupportsMultiWindow;
558 boolean mSupportsSplitScreenMultiWindow;
559 boolean mSupportsFreeformWindowManagement;
560 boolean mSupportsPictureInPicture;
561 boolean mSupportsMultiDisplay;
562 boolean mForceResizableActivities;
563
564 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
565
566 // VR Vr2d Display Id.
567 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700568
Wale Ogunwalef6733932018-06-27 05:14:34 -0700569 /**
570 * Set while we are wanting to sleep, to prevent any
571 * activities from being started/resumed.
572 *
573 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
574 *
575 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
576 * while in the sleep state until there is a pending transition out of sleep, in which case
577 * mSleeping is set to false, and remains false while awake.
578 *
579 * Whether mSleeping can quickly toggled between true/false without the device actually
580 * display changing states is undefined.
581 */
582 private boolean mSleeping = false;
583
584 /**
585 * The process state used for processes that are running the top activities.
586 * This changes between TOP and TOP_SLEEPING to following mSleeping.
587 */
588 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
589
590 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
591 // automatically. Important for devices without direct input devices.
592 private boolean mShowDialogs = true;
593
594 /** Set if we are shutting down the system, similar to sleeping. */
595 boolean mShuttingDown = false;
596
597 /**
598 * We want to hold a wake lock while running a voice interaction session, since
599 * this may happen with the screen off and we need to keep the CPU running to
600 * be able to continue to interact with the user.
601 */
602 PowerManager.WakeLock mVoiceWakeLock;
603
604 /**
605 * Set while we are running a voice interaction. This overrides sleeping while it is active.
606 */
607 IVoiceInteractionSession mRunningVoice;
608
609 /**
610 * The last resumed activity. This is identical to the current resumed activity most
611 * of the time but could be different when we're pausing one activity before we resume
612 * another activity.
613 */
614 ActivityRecord mLastResumedActivity;
615
616 /**
617 * The activity that is currently being traced as the active resumed activity.
618 *
619 * @see #updateResumedAppTrace
620 */
621 private @Nullable ActivityRecord mTracedResumedActivity;
622
623 /** If non-null, we are tracking the time the user spends in the currently focused app. */
624 AppTimeTracker mCurAppTimeTracker;
625
Wale Ogunwale008163e2018-07-23 23:11:08 -0700626 private AppWarnings mAppWarnings;
627
Wale Ogunwale53783742018-09-16 10:21:51 -0700628 /**
629 * Packages that the user has asked to have run in screen size
630 * compatibility mode instead of filling the screen.
631 */
632 CompatModePackages mCompatModePackages;
633
Wale Ogunwalef6733932018-06-27 05:14:34 -0700634 private FontScaleSettingObserver mFontScaleSettingObserver;
635
Michal Karpinski4026cae2019-02-12 11:51:47 +0000636 private String mDeviceOwnerPackageName;
637
Wale Ogunwalef6733932018-06-27 05:14:34 -0700638 private final class FontScaleSettingObserver extends ContentObserver {
639 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
640 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
641
642 public FontScaleSettingObserver() {
643 super(mH);
644 final ContentResolver resolver = mContext.getContentResolver();
645 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
646 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
647 UserHandle.USER_ALL);
648 }
649
650 @Override
651 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
652 if (mFontScaleUri.equals(uri)) {
653 updateFontScaleIfNeeded(userId);
654 } else if (mHideErrorDialogsUri.equals(uri)) {
655 synchronized (mGlobalLock) {
656 updateShouldShowDialogsLocked(getGlobalConfiguration());
657 }
658 }
659 }
660 }
661
Riddle Hsua0536432019-02-16 00:38:59 +0800662 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
663 @Target(ElementType.METHOD)
664 @Retention(RetentionPolicy.SOURCE)
665 @interface HotPath {
666 int NONE = 0;
667 int OOM_ADJUSTMENT = 1;
668 int LRU_UPDATE = 2;
669 int PROCESS_CHANGE = 3;
670 int caller() default NONE;
671 }
672
Charles Chen8d98dd22018-12-26 17:36:54 +0800673 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
674 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700675 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700676 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700677 mSystemThread = ActivityThread.currentActivityThread();
678 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700679 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800680 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700681 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700682 }
683
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700684 public void onSystemReady() {
685 synchronized (mGlobalLock) {
686 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
687 PackageManager.FEATURE_CANT_SAVE_STATE);
688 mAssistUtils = new AssistUtils(mContext);
689 mVrController.onSystemReady();
690 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700691 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700693 }
694
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 public void onInitPowerManagement() {
696 synchronized (mGlobalLock) {
697 mStackSupervisor.initPowerManagement();
698 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
699 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
700 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
701 mVoiceWakeLock.setReferenceCounted(false);
702 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700703 }
704
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700705 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700706 mFontScaleSettingObserver = new FontScaleSettingObserver();
707 }
708
Wale Ogunwale59507092018-10-29 09:00:30 -0700709 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700710 final boolean freeformWindowManagement =
711 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
712 || Settings.Global.getInt(
713 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
714
715 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
716 final boolean supportsPictureInPicture = supportsMultiWindow &&
717 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
718 final boolean supportsSplitScreenMultiWindow =
719 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
720 final boolean supportsMultiDisplay = mContext.getPackageManager()
721 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
723 final boolean forceResizable = Settings.Global.getInt(
724 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700725 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700726
727 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900728 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729
730 final Configuration configuration = new Configuration();
731 Settings.System.getConfiguration(resolver, configuration);
732 if (forceRtl) {
733 // This will take care of setting the correct layout direction flags
734 configuration.setLayoutDirection(configuration.locale);
735 }
736
737 synchronized (mGlobalLock) {
738 mForceResizableActivities = forceResizable;
739 final boolean multiWindowFormEnabled = freeformWindowManagement
740 || supportsSplitScreenMultiWindow
741 || supportsPictureInPicture
742 || supportsMultiDisplay;
743 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
744 mSupportsMultiWindow = true;
745 mSupportsFreeformWindowManagement = freeformWindowManagement;
746 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
747 mSupportsPictureInPicture = supportsPictureInPicture;
748 mSupportsMultiDisplay = supportsMultiDisplay;
749 } else {
750 mSupportsMultiWindow = false;
751 mSupportsFreeformWindowManagement = false;
752 mSupportsSplitScreenMultiWindow = false;
753 mSupportsPictureInPicture = false;
754 mSupportsMultiDisplay = false;
755 }
756 mWindowManager.setForceResizableTasks(mForceResizableActivities);
757 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700758 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
759 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700760 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 // This happens before any activities are started, so we can change global configuration
762 // in-place.
763 updateConfigurationLocked(configuration, null, true);
764 final Configuration globalConfig = getGlobalConfiguration();
765 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
766
767 // Load resources only after the current configuration has been set.
768 final Resources res = mContext.getResources();
769 mThumbnailWidth = res.getDimensionPixelSize(
770 com.android.internal.R.dimen.thumbnail_width);
771 mThumbnailHeight = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_height);
773
774 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
775 mFullscreenThumbnailScale = (float) res
776 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
777 (float) globalConfig.screenWidthDp;
778 } else {
779 mFullscreenThumbnailScale = res.getFraction(
780 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
781 }
782 }
783 }
784
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800785 public WindowManagerGlobalLock getGlobalLock() {
786 return mGlobalLock;
787 }
788
Yunfan Chen585f2932019-01-29 16:04:45 +0900789 /** For test purpose only. */
790 @VisibleForTesting
791 public ActivityTaskManagerInternal getAtmInternal() {
792 return mInternal;
793 }
794
Riddle Hsud93a6c42018-11-29 21:50:06 +0800795 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
796 Looper looper) {
797 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700799 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700800 final File systemDir = SystemServiceManager.ensureSystemDir();
801 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
802 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700803 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804
805 mTempConfig.setToDefaults();
806 mTempConfig.setLocales(LocaleList.getDefault());
807 mConfigurationSeq = mTempConfig.seq = 1;
808 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800809 mRootActivityContainer = new RootActivityContainer(this);
810 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700811
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700812 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700814 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700815 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700816 mRecentTasks = createRecentTasks();
817 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700818 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700819 mKeyguardController = mStackSupervisor.getKeyguardController();
820 }
821
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700822 public void onActivityManagerInternalAdded() {
823 synchronized (mGlobalLock) {
824 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
825 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
826 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700827 }
828
Yunfan Chen75157d72018-07-27 14:47:21 +0900829 int increaseConfigurationSeqLocked() {
830 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
831 return mConfigurationSeq;
832 }
833
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700834 protected ActivityStackSupervisor createStackSupervisor() {
835 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
836 supervisor.initialize();
837 return supervisor;
838 }
839
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700840 public void setWindowManager(WindowManagerService wm) {
841 synchronized (mGlobalLock) {
842 mWindowManager = wm;
843 mLockTaskController.setWindowManager(wm);
844 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800845 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700846 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700847 }
848
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
850 synchronized (mGlobalLock) {
851 mUsageStatsInternal = usageStatsManager;
852 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700853 }
854
Wale Ogunwalef6733932018-06-27 05:14:34 -0700855 UserManagerService getUserManager() {
856 if (mUserManager == null) {
857 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
858 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
859 }
860 return mUserManager;
861 }
862
863 AppOpsService getAppOpsService() {
864 if (mAppOpsService == null) {
865 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
866 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
867 }
868 return mAppOpsService;
869 }
870
871 boolean hasUserRestriction(String restriction, int userId) {
872 return getUserManager().hasUserRestriction(restriction, userId);
873 }
874
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700875 protected RecentTasks createRecentTasks() {
876 return new RecentTasks(this, mStackSupervisor);
877 }
878
879 RecentTasks getRecentTasks() {
880 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700881 }
882
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700883 ClientLifecycleManager getLifecycleManager() {
884 return mLifecycleManager;
885 }
886
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700887 ActivityStartController getActivityStartController() {
888 return mActivityStartController;
889 }
890
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700891 TaskChangeNotificationController getTaskChangeNotificationController() {
892 return mTaskChangeNotificationController;
893 }
894
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700895 LockTaskController getLockTaskController() {
896 return mLockTaskController;
897 }
898
Yunfan Chen75157d72018-07-27 14:47:21 +0900899 /**
900 * Return the global configuration used by the process corresponding to the input pid. This is
901 * usually the global configuration with some overrides specific to that process.
902 */
903 Configuration getGlobalConfigurationForCallingPid() {
904 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800905 return getGlobalConfigurationForPid(pid);
906 }
907
908 /**
909 * Return the global configuration used by the process corresponding to the given pid.
910 */
911 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 if (pid == MY_PID || pid < 0) {
913 return getGlobalConfiguration();
914 }
915 synchronized (mGlobalLock) {
916 final WindowProcessController app = mPidMap.get(pid);
917 return app != null ? app.getConfiguration() : getGlobalConfiguration();
918 }
919 }
920
921 /**
922 * Return the device configuration info used by the process corresponding to the input pid.
923 * The value is consistent with the global configuration for the process.
924 */
925 @Override
926 public ConfigurationInfo getDeviceConfigurationInfo() {
927 ConfigurationInfo config = new ConfigurationInfo();
928 synchronized (mGlobalLock) {
929 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
930 config.reqTouchScreen = globalConfig.touchscreen;
931 config.reqKeyboardType = globalConfig.keyboard;
932 config.reqNavigation = globalConfig.navigation;
933 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
934 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
935 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
936 }
937 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
938 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
939 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
940 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700941 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 }
943 return config;
944 }
945
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700946 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700947 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700948 }
949
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700950 public static final class Lifecycle extends SystemService {
951 private final ActivityTaskManagerService mService;
952
953 public Lifecycle(Context context) {
954 super(context);
955 mService = new ActivityTaskManagerService(context);
956 }
957
958 @Override
959 public void onStart() {
960 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 }
963
Garfield Tan891146c2018-10-09 12:14:00 -0700964 @Override
965 public void onUnlockUser(int userId) {
966 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800967 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700968 }
969 }
970
971 @Override
972 public void onCleanupUser(int userId) {
973 synchronized (mService.getGlobalLock()) {
974 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
975 }
976 }
977
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700978 public ActivityTaskManagerService getService() {
979 return mService;
980 }
981 }
982
983 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700984 public final int startActivity(IApplicationThread caller, String callingPackage,
985 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
986 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
987 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
988 resultWho, requestCode, startFlags, profilerInfo, bOptions,
989 UserHandle.getCallingUserId());
990 }
991
992 @Override
993 public final int startActivities(IApplicationThread caller, String callingPackage,
994 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
995 int userId) {
996 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700997 enforceNotIsolatedCaller(reason);
998 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001000 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1001 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1002 reason, null /* originatingPendingIntent */,
1003 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 }
1005
1006 @Override
1007 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1008 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1009 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1010 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1011 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1012 true /*validateIncomingUser*/);
1013 }
1014
1015 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1016 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1017 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1018 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001019 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001021 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1023
1024 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001025 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 .setCaller(caller)
1027 .setCallingPackage(callingPackage)
1028 .setResolvedType(resolvedType)
1029 .setResultTo(resultTo)
1030 .setResultWho(resultWho)
1031 .setRequestCode(requestCode)
1032 .setStartFlags(startFlags)
1033 .setProfilerInfo(profilerInfo)
1034 .setActivityOptions(bOptions)
1035 .setMayWait(userId)
1036 .execute();
1037
1038 }
1039
1040 @Override
1041 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1042 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1044 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // Refuse possible leaked file descriptors
1046 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1047 throw new IllegalArgumentException("File descriptors passed in Intent");
1048 }
1049
1050 if (!(target instanceof PendingIntentRecord)) {
1051 throw new IllegalArgumentException("Bad PendingIntent object");
1052 }
1053
1054 PendingIntentRecord pir = (PendingIntentRecord)target;
1055
1056 synchronized (mGlobalLock) {
1057 // If this is coming from the currently resumed activity, it is
1058 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001059 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 if (stack.mResumedActivity != null &&
1061 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001062 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 }
1064 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 }
1068
1069 @Override
1070 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1071 Bundle bOptions) {
1072 // Refuse possible leaked file descriptors
1073 if (intent != null && intent.hasFileDescriptors()) {
1074 throw new IllegalArgumentException("File descriptors passed in Intent");
1075 }
1076 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1077
1078 synchronized (mGlobalLock) {
1079 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1080 if (r == null) {
1081 SafeActivityOptions.abort(options);
1082 return false;
1083 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001084 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 // The caller is not running... d'oh!
1086 SafeActivityOptions.abort(options);
1087 return false;
1088 }
1089 intent = new Intent(intent);
1090 // The caller is not allowed to change the data.
1091 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1092 // And we are resetting to find the next component...
1093 intent.setComponent(null);
1094
1095 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1096
1097 ActivityInfo aInfo = null;
1098 try {
1099 List<ResolveInfo> resolves =
1100 AppGlobals.getPackageManager().queryIntentActivities(
1101 intent, r.resolvedType,
1102 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1103 UserHandle.getCallingUserId()).getList();
1104
1105 // Look for the original activity in the list...
1106 final int N = resolves != null ? resolves.size() : 0;
1107 for (int i=0; i<N; i++) {
1108 ResolveInfo rInfo = resolves.get(i);
1109 if (rInfo.activityInfo.packageName.equals(r.packageName)
1110 && rInfo.activityInfo.name.equals(r.info.name)) {
1111 // We found the current one... the next matching is
1112 // after it.
1113 i++;
1114 if (i<N) {
1115 aInfo = resolves.get(i).activityInfo;
1116 }
1117 if (debug) {
1118 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1119 + "/" + r.info.name);
1120 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1121 ? "null" : aInfo.packageName + "/" + aInfo.name));
1122 }
1123 break;
1124 }
1125 }
1126 } catch (RemoteException e) {
1127 }
1128
1129 if (aInfo == null) {
1130 // Nobody who is next!
1131 SafeActivityOptions.abort(options);
1132 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1133 return false;
1134 }
1135
1136 intent.setComponent(new ComponentName(
1137 aInfo.applicationInfo.packageName, aInfo.name));
1138 intent.setFlags(intent.getFlags()&~(
1139 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1140 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1141 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1142 FLAG_ACTIVITY_NEW_TASK));
1143
1144 // Okay now we need to start the new activity, replacing the currently running activity.
1145 // This is a little tricky because we want to start the new one as if the current one is
1146 // finished, but not finish the current one first so that there is no flicker.
1147 // And thus...
1148 final boolean wasFinishing = r.finishing;
1149 r.finishing = true;
1150
1151 // Propagate reply information over to the new activity.
1152 final ActivityRecord resultTo = r.resultTo;
1153 final String resultWho = r.resultWho;
1154 final int requestCode = r.requestCode;
1155 r.resultTo = null;
1156 if (resultTo != null) {
1157 resultTo.removeResultsLocked(r, resultWho, requestCode);
1158 }
1159
1160 final long origId = Binder.clearCallingIdentity();
1161 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001162 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001163 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001164 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001165 .setResolvedType(r.resolvedType)
1166 .setActivityInfo(aInfo)
1167 .setResultTo(resultTo != null ? resultTo.appToken : null)
1168 .setResultWho(resultWho)
1169 .setRequestCode(requestCode)
1170 .setCallingPid(-1)
1171 .setCallingUid(r.launchedFromUid)
1172 .setCallingPackage(r.launchedFromPackage)
1173 .setRealCallingPid(-1)
1174 .setRealCallingUid(r.launchedFromUid)
1175 .setActivityOptions(options)
1176 .execute();
1177 Binder.restoreCallingIdentity(origId);
1178
1179 r.finishing = wasFinishing;
1180 if (res != ActivityManager.START_SUCCESS) {
1181 return false;
1182 }
1183 return true;
1184 }
1185 }
1186
1187 @Override
1188 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1189 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1190 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1191 final WaitResult res = new WaitResult();
1192 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001193 enforceNotIsolatedCaller("startActivityAndWait");
1194 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1195 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001196 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001197 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001198 .setCaller(caller)
1199 .setCallingPackage(callingPackage)
1200 .setResolvedType(resolvedType)
1201 .setResultTo(resultTo)
1202 .setResultWho(resultWho)
1203 .setRequestCode(requestCode)
1204 .setStartFlags(startFlags)
1205 .setActivityOptions(bOptions)
1206 .setMayWait(userId)
1207 .setProfilerInfo(profilerInfo)
1208 .setWaitResult(res)
1209 .execute();
1210 }
1211 return res;
1212 }
1213
1214 @Override
1215 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1216 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1217 int startFlags, Configuration config, Bundle bOptions, int userId) {
1218 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001219 enforceNotIsolatedCaller("startActivityWithConfig");
1220 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1221 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001223 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 .setCaller(caller)
1225 .setCallingPackage(callingPackage)
1226 .setResolvedType(resolvedType)
1227 .setResultTo(resultTo)
1228 .setResultWho(resultWho)
1229 .setRequestCode(requestCode)
1230 .setStartFlags(startFlags)
1231 .setGlobalConfiguration(config)
1232 .setActivityOptions(bOptions)
1233 .setMayWait(userId)
1234 .execute();
1235 }
1236 }
1237
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238
1239 @Override
1240 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1241 int callingUid = Binder.getCallingUid();
1242 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1243 throw new SecurityException("Only the system process can request a permission token, "
1244 + "received request from uid: " + callingUid);
1245 }
1246 IBinder permissionToken = new Binder();
1247 synchronized (mGlobalLock) {
1248 mStartActivitySources.put(permissionToken, delegatorToken);
1249 }
1250
1251 Message expireMsg = PooledLambda.obtainMessage(
1252 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1253 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1254
1255 Message forgetMsg = PooledLambda.obtainMessage(
1256 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1257 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1258
1259 return permissionToken;
1260 }
1261
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001262 @Override
1263 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1264 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001265 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1266 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001267 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268 // permission grants) as any app that may launch one of your own activities. So we only
1269 // allow this in two cases:
1270 // 1) The caller is an activity that is part of the core framework, and then only when it
1271 // is running as the system.
1272 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1273 // can only be requested by a system activity, which may then delegate this call to
1274 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 final ActivityRecord sourceRecord;
1276 final int targetUid;
1277 final String targetPackage;
1278 final boolean isResolver;
1279 synchronized (mGlobalLock) {
1280 if (resultTo == null) {
1281 throw new SecurityException("Must be called from an activity");
1282 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 final IBinder sourceToken;
1284 if (permissionToken != null) {
1285 // To even attempt to use a permissionToken, an app must also have this signature
1286 // permission.
1287 mAmInternal.enforceCallingPermission(
1288 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1289 "startActivityAsCaller");
1290 // If called with a permissionToken, we want the sourceRecord from the delegator
1291 // activity that requested this token.
1292 sourceToken = mStartActivitySources.remove(permissionToken);
1293 if (sourceToken == null) {
1294 // Invalid permissionToken, check if it recently expired.
1295 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1296 throw new SecurityException("Called with expired permission token: "
1297 + permissionToken);
1298 } else {
1299 throw new SecurityException("Called with invalid permission token: "
1300 + permissionToken);
1301 }
1302 }
1303 } else {
1304 // This method was called directly by the source.
1305 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307
Wale Ogunwaled32da472018-11-16 07:19:28 -08001308 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001309 if (sourceRecord == null) {
1310 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 }
1312 if (sourceRecord.app == null) {
1313 throw new SecurityException("Called without a process attached to activity");
1314 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001315
1316 // Whether called directly or from a delegate, the source activity must be from the
1317 // android package.
1318 if (!sourceRecord.info.packageName.equals("android")) {
1319 throw new SecurityException("Must be called from an activity that is "
1320 + "declared in the android package");
1321 }
1322
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001323 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 // This is still okay, as long as this activity is running under the
1325 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001326 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001328 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 + " must be system uid or original calling uid "
1330 + sourceRecord.launchedFromUid);
1331 }
1332 }
1333 if (ignoreTargetSecurity) {
1334 if (intent.getComponent() == null) {
1335 throw new SecurityException(
1336 "Component must be specified with ignoreTargetSecurity");
1337 }
1338 if (intent.getSelector() != null) {
1339 throw new SecurityException(
1340 "Selector not allowed with ignoreTargetSecurity");
1341 }
1342 }
1343 targetUid = sourceRecord.launchedFromUid;
1344 targetPackage = sourceRecord.launchedFromPackage;
1345 isResolver = sourceRecord.isResolverOrChildActivity();
1346 }
1347
1348 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001349 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 }
1351
1352 // TODO: Switch to user app stacks here.
1353 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001354 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001355 .setCallingUid(targetUid)
1356 .setCallingPackage(targetPackage)
1357 .setResolvedType(resolvedType)
1358 .setResultTo(resultTo)
1359 .setResultWho(resultWho)
1360 .setRequestCode(requestCode)
1361 .setStartFlags(startFlags)
1362 .setActivityOptions(bOptions)
1363 .setMayWait(userId)
1364 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1365 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1366 .execute();
1367 } catch (SecurityException e) {
1368 // XXX need to figure out how to propagate to original app.
1369 // A SecurityException here is generally actually a fault of the original
1370 // calling activity (such as a fairly granting permissions), so propagate it
1371 // back to them.
1372 /*
1373 StringBuilder msg = new StringBuilder();
1374 msg.append("While launching");
1375 msg.append(intent.toString());
1376 msg.append(": ");
1377 msg.append(e.getMessage());
1378 */
1379 throw e;
1380 }
1381 }
1382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1384 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1385 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1386 }
1387
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388 @Override
1389 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1390 Intent intent, String resolvedType, IVoiceInteractionSession session,
1391 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1392 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001393 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 if (session == null || interactor == null) {
1395 throw new NullPointerException("null session or interactor");
1396 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001397 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001399 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .setCallingUid(callingUid)
1401 .setCallingPackage(callingPackage)
1402 .setResolvedType(resolvedType)
1403 .setVoiceSession(session)
1404 .setVoiceInteractor(interactor)
1405 .setStartFlags(startFlags)
1406 .setProfilerInfo(profilerInfo)
1407 .setActivityOptions(bOptions)
1408 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001409 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 .execute();
1411 }
1412
1413 @Override
1414 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1415 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1417 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001419 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 .setCallingUid(callingUid)
1421 .setCallingPackage(callingPackage)
1422 .setResolvedType(resolvedType)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1431 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 final int callingPid = Binder.getCallingPid();
1434 final long origId = Binder.clearCallingIdentity();
1435 try {
1436 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001437 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1438 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439
1440 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001441 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1442 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1444 recentsUid, assistDataReceiver);
1445 }
1446 } finally {
1447 Binder.restoreCallingIdentity(origId);
1448 }
1449 }
1450
1451 @Override
1452 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 "startActivityFromRecents()");
1455
1456 final int callingPid = Binder.getCallingPid();
1457 final int callingUid = Binder.getCallingUid();
1458 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1459 final long origId = Binder.clearCallingIdentity();
1460 try {
1461 synchronized (mGlobalLock) {
1462 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1463 safeOptions);
1464 }
1465 } finally {
1466 Binder.restoreCallingIdentity(origId);
1467 }
1468 }
1469
1470 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001471 * Public API to check if the client is allowed to start an activity on specified display.
1472 *
1473 * If the target display is private or virtual, some restrictions will apply.
1474 *
1475 * @param displayId Target display id.
1476 * @param intent Intent used to launch the activity.
1477 * @param resolvedType The MIME type of the intent.
1478 * @param userId The id of the user for whom the call is made.
1479 * @return {@code true} if a call to start an activity on the target display should succeed and
1480 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1481 */
1482 @Override
1483 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1484 String resolvedType, int userId) {
1485 final int callingUid = Binder.getCallingUid();
1486 final int callingPid = Binder.getCallingPid();
1487 final long origId = Binder.clearCallingIdentity();
1488
1489 try {
1490 // Collect information about the target of the Intent.
1491 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1492 0 /* startFlags */, null /* profilerInfo */, userId,
1493 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1494 UserHandle.USER_NULL));
1495 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1496
1497 synchronized (mGlobalLock) {
1498 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1499 aInfo);
1500 }
1501 } finally {
1502 Binder.restoreCallingIdentity(origId);
1503 }
1504 }
1505
1506 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 * This is the internal entry point for handling Activity.finish().
1508 *
1509 * @param token The Binder token referencing the Activity we want to finish.
1510 * @param resultCode Result code, if any, from this Activity.
1511 * @param resultData Result data (Intent), if any, from this Activity.
1512 * @param finishTask Whether to finish the task associated with this Activity.
1513 *
1514 * @return Returns true if the activity successfully finished, or false if it is still running.
1515 */
1516 @Override
1517 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1518 int finishTask) {
1519 // Refuse possible leaked file descriptors
1520 if (resultData != null && resultData.hasFileDescriptors()) {
1521 throw new IllegalArgumentException("File descriptors passed in Intent");
1522 }
1523
1524 synchronized (mGlobalLock) {
1525 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1526 if (r == null) {
1527 return true;
1528 }
1529 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001530 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 ActivityRecord rootR = tr.getRootActivity();
1532 if (rootR == null) {
1533 Slog.w(TAG, "Finishing task with all activities already finished");
1534 }
1535 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1536 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001537 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 return false;
1539 }
1540
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001541 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1542 // We should consolidate.
1543 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001544 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001545 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 if (next != null) {
1547 // ask watcher if this is allowed
1548 boolean resumeOK = true;
1549 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001550 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001552 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 Watchdog.getInstance().setActivityController(null);
1554 }
1555
1556 if (!resumeOK) {
1557 Slog.i(TAG, "Not finishing activity because controller resumed");
1558 return false;
1559 }
1560 }
1561 }
1562 final long origId = Binder.clearCallingIdentity();
1563 try {
1564 boolean res;
1565 final boolean finishWithRootActivity =
1566 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1567 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1568 || (finishWithRootActivity && r == rootR)) {
1569 // If requested, remove the task that is associated to this activity only if it
1570 // was the root activity in the task. The result code and data is ignored
1571 // because we don't support returning them across task boundaries. Also, to
1572 // keep backwards compatibility we remove the task from recents when finishing
1573 // task with root activity.
1574 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1575 finishWithRootActivity, "finish-activity");
1576 if (!res) {
1577 Slog.i(TAG, "Removing task failed to finish activity");
1578 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001579 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001580 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 } else {
1582 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1583 resultData, "app-request", true);
1584 if (!res) {
1585 Slog.i(TAG, "Failed to finish by app-request");
1586 }
1587 }
1588 return res;
1589 } finally {
1590 Binder.restoreCallingIdentity(origId);
1591 }
1592 }
1593 }
1594
1595 @Override
1596 public boolean finishActivityAffinity(IBinder token) {
1597 synchronized (mGlobalLock) {
1598 final long origId = Binder.clearCallingIdentity();
1599 try {
1600 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1601 if (r == null) {
1602 return false;
1603 }
1604
1605 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1606 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001607 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001608 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 return false;
1610 }
1611 return task.getStack().finishActivityAffinityLocked(r);
1612 } finally {
1613 Binder.restoreCallingIdentity(origId);
1614 }
1615 }
1616 }
1617
1618 @Override
1619 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1620 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001621 try {
1622 WindowProcessController proc = null;
1623 synchronized (mGlobalLock) {
1624 ActivityStack stack = ActivityRecord.getStackLocked(token);
1625 if (stack == null) {
1626 return;
1627 }
1628 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1629 false /* fromTimeout */, false /* processPausingActivities */, config);
1630 if (r != null) {
1631 proc = r.app;
1632 }
1633 if (stopProfiling && proc != null) {
1634 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 }
1636 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001637 } finally {
1638 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001640 }
1641
1642 @Override
1643 public final void activityResumed(IBinder token) {
1644 final long origId = Binder.clearCallingIdentity();
1645 synchronized (mGlobalLock) {
1646 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001647 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 }
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651
1652 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001653 public final void activityTopResumedStateLost() {
1654 final long origId = Binder.clearCallingIdentity();
1655 synchronized (mGlobalLock) {
1656 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1657 }
1658 Binder.restoreCallingIdentity(origId);
1659 }
1660
1661 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 public final void activityPaused(IBinder token) {
1663 final long origId = Binder.clearCallingIdentity();
1664 synchronized (mGlobalLock) {
1665 ActivityStack stack = ActivityRecord.getStackLocked(token);
1666 if (stack != null) {
1667 stack.activityPausedLocked(token, false);
1668 }
1669 }
1670 Binder.restoreCallingIdentity(origId);
1671 }
1672
1673 @Override
1674 public final void activityStopped(IBinder token, Bundle icicle,
1675 PersistableBundle persistentState, CharSequence description) {
1676 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1677
1678 // Refuse possible leaked file descriptors
1679 if (icicle != null && icicle.hasFileDescriptors()) {
1680 throw new IllegalArgumentException("File descriptors passed in Bundle");
1681 }
1682
1683 final long origId = Binder.clearCallingIdentity();
1684
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001685 String restartingName = null;
1686 int restartingUid = 0;
1687 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001688 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001689 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001691 if (r.attachedToProcess()
1692 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1693 // The activity was requested to restart from
1694 // {@link #restartActivityProcessIfVisible}.
1695 restartingName = r.app.mName;
1696 restartingUid = r.app.mUid;
1697 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 r.activityStoppedLocked(icicle, persistentState, description);
1699 }
1700 }
1701
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001702 if (restartingName != null) {
1703 // In order to let the foreground activity can be restarted with its saved state from
1704 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1705 // until the activity reports stopped with the state. And the activity record will be
1706 // kept because the record state is restarting, then the activity will be restarted
1707 // immediately if it is still the top one.
1708 mStackSupervisor.removeRestartTimeouts(r);
1709 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1710 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001711 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
1717 public final void activityDestroyed(IBinder token) {
1718 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1719 synchronized (mGlobalLock) {
1720 ActivityStack stack = ActivityRecord.getStackLocked(token);
1721 if (stack != null) {
1722 stack.activityDestroyedLocked(token, "activityDestroyed");
1723 }
1724 }
1725 }
1726
1727 @Override
1728 public final void activityRelaunched(IBinder token) {
1729 final long origId = Binder.clearCallingIdentity();
1730 synchronized (mGlobalLock) {
1731 mStackSupervisor.activityRelaunchedLocked(token);
1732 }
1733 Binder.restoreCallingIdentity(origId);
1734 }
1735
1736 public final void activitySlept(IBinder token) {
1737 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1738
1739 final long origId = Binder.clearCallingIdentity();
1740
1741 synchronized (mGlobalLock) {
1742 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1743 if (r != null) {
1744 mStackSupervisor.activitySleptLocked(r);
1745 }
1746 }
1747
1748 Binder.restoreCallingIdentity(origId);
1749 }
1750
1751 @Override
1752 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1753 synchronized (mGlobalLock) {
1754 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1755 if (r == null) {
1756 return;
1757 }
1758 final long origId = Binder.clearCallingIdentity();
1759 try {
1760 r.setRequestedOrientation(requestedOrientation);
1761 } finally {
1762 Binder.restoreCallingIdentity(origId);
1763 }
1764 }
1765 }
1766
1767 @Override
1768 public int getRequestedOrientation(IBinder token) {
1769 synchronized (mGlobalLock) {
1770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1771 if (r == null) {
1772 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1773 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001774 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776 }
1777
1778 @Override
1779 public void setImmersive(IBinder token, boolean immersive) {
1780 synchronized (mGlobalLock) {
1781 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1782 if (r == null) {
1783 throw new IllegalArgumentException();
1784 }
1785 r.immersive = immersive;
1786
1787 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001788 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792 }
1793 }
1794
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001795 void applyUpdateLockStateLocked(ActivityRecord r) {
1796 // Modifications to the UpdateLock state are done on our handler, outside
1797 // the activity manager's locks. The new state is determined based on the
1798 // state *now* of the relevant activity record. The object is passed to
1799 // the handler solely for logging detail, not to be consulted/modified.
1800 final boolean nextState = r != null && r.immersive;
1801 mH.post(() -> {
1802 if (mUpdateLock.isHeld() != nextState) {
1803 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1804 "Applying new update lock state '" + nextState + "' for " + r);
1805 if (nextState) {
1806 mUpdateLock.acquire();
1807 } else {
1808 mUpdateLock.release();
1809 }
1810 }
1811 });
1812 }
1813
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 @Override
1815 public boolean isImmersive(IBinder token) {
1816 synchronized (mGlobalLock) {
1817 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 throw new IllegalArgumentException();
1820 }
1821 return r.immersive;
1822 }
1823 }
1824
1825 @Override
1826 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001829 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 return (r != null) ? r.immersive : false;
1831 }
1832 }
1833
1834 @Override
1835 public void overridePendingTransition(IBinder token, String packageName,
1836 int enterAnim, int exitAnim) {
1837 synchronized (mGlobalLock) {
1838 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1839 if (self == null) {
1840 return;
1841 }
1842
1843 final long origId = Binder.clearCallingIdentity();
1844
1845 if (self.isState(
1846 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001847 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001848 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
1850
1851 Binder.restoreCallingIdentity(origId);
1852 }
1853 }
1854
1855 @Override
1856 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001859 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 if (r == null) {
1861 return ActivityManager.COMPAT_MODE_UNKNOWN;
1862 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001863 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 }
1865 }
1866
1867 @Override
1868 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001873 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001874 if (r == null) {
1875 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1876 return;
1877 }
1878 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001879 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 }
1881 }
1882
1883 @Override
1884 public int getLaunchedFromUid(IBinder activityToken) {
1885 ActivityRecord srec;
1886 synchronized (mGlobalLock) {
1887 srec = ActivityRecord.forTokenLocked(activityToken);
1888 }
1889 if (srec == null) {
1890 return -1;
1891 }
1892 return srec.launchedFromUid;
1893 }
1894
1895 @Override
1896 public String getLaunchedFromPackage(IBinder activityToken) {
1897 ActivityRecord srec;
1898 synchronized (mGlobalLock) {
1899 srec = ActivityRecord.forTokenLocked(activityToken);
1900 }
1901 if (srec == null) {
1902 return null;
1903 }
1904 return srec.launchedFromPackage;
1905 }
1906
1907 @Override
1908 public boolean convertFromTranslucent(IBinder token) {
1909 final long origId = Binder.clearCallingIdentity();
1910 try {
1911 synchronized (mGlobalLock) {
1912 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1913 if (r == null) {
1914 return false;
1915 }
1916 final boolean translucentChanged = r.changeWindowTranslucency(true);
1917 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001918 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 return translucentChanged;
1922 }
1923 } finally {
1924 Binder.restoreCallingIdentity(origId);
1925 }
1926 }
1927
1928 @Override
1929 public boolean convertToTranslucent(IBinder token, Bundle options) {
1930 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1931 final long origId = Binder.clearCallingIdentity();
1932 try {
1933 synchronized (mGlobalLock) {
1934 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1935 if (r == null) {
1936 return false;
1937 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001938 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 int index = task.mActivities.lastIndexOf(r);
1940 if (index > 0) {
1941 ActivityRecord under = task.mActivities.get(index - 1);
1942 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1943 }
1944 final boolean translucentChanged = r.changeWindowTranslucency(false);
1945 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001946 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001948 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001949 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 return translucentChanged;
1951 }
1952 } finally {
1953 Binder.restoreCallingIdentity(origId);
1954 }
1955 }
1956
1957 @Override
1958 public void notifyActivityDrawn(IBinder token) {
1959 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1960 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001961 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001963 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 }
1967
1968 @Override
1969 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1970 synchronized (mGlobalLock) {
1971 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1972 if (r == null) {
1973 return;
1974 }
1975 r.reportFullyDrawnLocked(restoredFromBundle);
1976 }
1977 }
1978
1979 @Override
1980 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1981 synchronized (mGlobalLock) {
1982 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1983 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1984 return stack.mDisplayId;
1985 }
1986 return DEFAULT_DISPLAY;
1987 }
1988 }
1989
1990 @Override
1991 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001992 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 long ident = Binder.clearCallingIdentity();
1994 try {
1995 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001996 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001998 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 }
2000 return null;
2001 }
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006
2007 @Override
2008 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2011 final long callingId = Binder.clearCallingIdentity();
2012 try {
2013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 if (stack == null) {
2016 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2017 return;
2018 }
2019 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002020 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002021 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 }
2023 }
2024 } finally {
2025 Binder.restoreCallingIdentity(callingId);
2026 }
2027 }
2028
2029 @Override
2030 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002031 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2033 final long callingId = Binder.clearCallingIdentity();
2034 try {
2035 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002036 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002037 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (task == null) {
2039 return;
2040 }
2041 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002042 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002043 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 }
2045 }
2046 } finally {
2047 Binder.restoreCallingIdentity(callingId);
2048 }
2049 }
2050
2051 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002052 public void restartActivityProcessIfVisible(IBinder activityToken) {
2053 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2054 final long callingId = Binder.clearCallingIdentity();
2055 try {
2056 synchronized (mGlobalLock) {
2057 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2058 if (r == null) {
2059 return;
2060 }
2061 r.restartProcessIfVisible();
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(callingId);
2065 }
2066 }
2067
2068 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 synchronized (mGlobalLock) {
2072 final long ident = Binder.clearCallingIdentity();
2073 try {
2074 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2075 "remove-task");
2076 } finally {
2077 Binder.restoreCallingIdentity(ident);
2078 }
2079 }
2080 }
2081
2082 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002083 public void removeAllVisibleRecentTasks() {
2084 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2085 synchronized (mGlobalLock) {
2086 final long ident = Binder.clearCallingIdentity();
2087 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002088 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002089 } finally {
2090 Binder.restoreCallingIdentity(ident);
2091 }
2092 }
2093 }
2094
2095 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2097 synchronized (mGlobalLock) {
2098 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2099 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002100 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 }
2102 }
2103 return false;
2104 }
2105
2106 @Override
2107 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2108 Intent resultData) {
2109
2110 synchronized (mGlobalLock) {
2111 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2112 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002113 return r.getActivityStack().navigateUpToLocked(
2114 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 }
2116 return false;
2117 }
2118 }
2119
2120 /**
2121 * Attempts to move a task backwards in z-order (the order of activities within the task is
2122 * unchanged).
2123 *
2124 * There are several possible results of this call:
2125 * - if the task is locked, then we will show the lock toast
2126 * - if there is a task behind the provided task, then that task is made visible and resumed as
2127 * this task is moved to the back
2128 * - otherwise, if there are no other tasks in the stack:
2129 * - if this task is in the pinned stack, then we remove the stack completely, which will
2130 * have the effect of moving the task to the top or bottom of the fullscreen stack
2131 * (depending on whether it is visible)
2132 * - otherwise, we simply return home and hide this task
2133 *
2134 * @param token A reference to the activity we wish to move
2135 * @param nonRoot If false then this only works if the activity is the root
2136 * of a task; if true it will work for any activity in a task.
2137 * @return Returns true if the move completed, false if not.
2138 */
2139 @Override
2140 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002141 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 synchronized (mGlobalLock) {
2143 final long origId = Binder.clearCallingIdentity();
2144 try {
2145 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002146 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 if (task != null) {
2148 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2149 }
2150 } finally {
2151 Binder.restoreCallingIdentity(origId);
2152 }
2153 }
2154 return false;
2155 }
2156
2157 @Override
2158 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002159 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 long ident = Binder.clearCallingIdentity();
2161 Rect rect = new Rect();
2162 try {
2163 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002164 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2166 if (task == null) {
2167 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2168 return rect;
2169 }
2170 if (task.getStack() != null) {
2171 // Return the bounds from window manager since it will be adjusted for various
2172 // things like the presense of a docked stack for tasks that aren't resizeable.
2173 task.getWindowContainerBounds(rect);
2174 } else {
2175 // Task isn't in window manager yet since it isn't associated with a stack.
2176 // Return the persist value from activity manager
2177 if (!task.matchParentBounds()) {
2178 rect.set(task.getBounds());
2179 } else if (task.mLastNonFullscreenBounds != null) {
2180 rect.set(task.mLastNonFullscreenBounds);
2181 }
2182 }
2183 }
2184 } finally {
2185 Binder.restoreCallingIdentity(ident);
2186 }
2187 return rect;
2188 }
2189
2190 @Override
2191 public ActivityManager.TaskDescription getTaskDescription(int id) {
2192 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002195 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2197 if (tr != null) {
2198 return tr.lastTaskDescription;
2199 }
2200 }
2201 return null;
2202 }
2203
2204 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002205 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2206 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2207 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2208 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2209 return;
2210 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002211 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002212 synchronized (mGlobalLock) {
2213 final long ident = Binder.clearCallingIdentity();
2214 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002215 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002216 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002217 if (task == null) {
2218 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2219 return;
2220 }
2221
2222 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2223 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2224
2225 if (!task.isActivityTypeStandardOrUndefined()) {
2226 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2227 + " non-standard task " + taskId + " to windowing mode="
2228 + windowingMode);
2229 }
2230
2231 final ActivityStack stack = task.getStack();
2232 if (toTop) {
2233 stack.moveToFront("setTaskWindowingMode", task);
2234 }
2235 stack.setWindowingMode(windowingMode);
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
2239 }
2240 }
2241
2242 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002244 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 ActivityRecord r = getCallingRecordLocked(token);
2246 return r != null ? r.info.packageName : null;
2247 }
2248 }
2249
2250 @Override
2251 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002252 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 ActivityRecord r = getCallingRecordLocked(token);
2254 return r != null ? r.intent.getComponent() : null;
2255 }
2256 }
2257
2258 private ActivityRecord getCallingRecordLocked(IBinder token) {
2259 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2260 if (r == null) {
2261 return null;
2262 }
2263 return r.resultTo;
2264 }
2265
2266 @Override
2267 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269
2270 synchronized (mGlobalLock) {
2271 final long origId = Binder.clearCallingIdentity();
2272 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002273 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 } finally {
2275 Binder.restoreCallingIdentity(origId);
2276 }
2277 }
2278 }
2279
2280 /**
2281 * TODO: Add mController hook
2282 */
2283 @Override
2284 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286
2287 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2288 synchronized (mGlobalLock) {
2289 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2290 false /* fromRecents */);
2291 }
2292 }
2293
2294 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2295 boolean fromRecents) {
2296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 Binder.getCallingUid(), -1, -1, "Task to front")) {
2299 SafeActivityOptions.abort(options);
2300 return;
2301 }
2302 final long origId = Binder.clearCallingIdentity();
2303 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002304 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002305 if (task == null) {
2306 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002307 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 return;
2309 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002310 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002312 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 return;
2314 }
2315 ActivityOptions realOptions = options != null
2316 ? options.getOptions(mStackSupervisor)
2317 : null;
2318 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2319 false /* forceNonResizable */);
2320
2321 final ActivityRecord topActivity = task.getTopActivity();
2322 if (topActivity != null) {
2323
2324 // We are reshowing a task, use a starting window to hide the initial draw delay
2325 // so the transition can start earlier.
2326 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2327 true /* taskSwitch */, fromRecents);
2328 }
2329 } finally {
2330 Binder.restoreCallingIdentity(origId);
2331 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002332 }
2333
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002334 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2335 int callingPid, int callingUid, String name) {
2336 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2337 return true;
2338 }
2339
2340 if (getRecentTasks().isCallerRecents(sourceUid)) {
2341 return true;
2342 }
2343
2344 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2345 if (perm == PackageManager.PERMISSION_GRANTED) {
2346 return true;
2347 }
2348 if (checkAllowAppSwitchUid(sourceUid)) {
2349 return true;
2350 }
2351
2352 // If the actual IPC caller is different from the logical source, then
2353 // also see if they are allowed to control app switches.
2354 if (callingUid != -1 && callingUid != sourceUid) {
2355 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2356 if (perm == PackageManager.PERMISSION_GRANTED) {
2357 return true;
2358 }
2359 if (checkAllowAppSwitchUid(callingUid)) {
2360 return true;
2361 }
2362 }
2363
2364 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2365 return false;
2366 }
2367
2368 private boolean checkAllowAppSwitchUid(int uid) {
2369 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2370 if (types != null) {
2371 for (int i = types.size() - 1; i >= 0; i--) {
2372 if (types.valueAt(i).intValue() == uid) {
2373 return true;
2374 }
2375 }
2376 }
2377 return false;
2378 }
2379
2380 @Override
2381 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2382 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2383 "setActivityController()");
2384 synchronized (mGlobalLock) {
2385 mController = controller;
2386 mControllerIsAMonkey = imAMonkey;
2387 Watchdog.getInstance().setActivityController(controller);
2388 }
2389 }
2390
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002391 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002392 synchronized (mGlobalLock) {
2393 return mController != null && mControllerIsAMonkey;
2394 }
2395 }
2396
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 @Override
2398 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2399 synchronized (mGlobalLock) {
2400 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2401 }
2402 }
2403
2404 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002405 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2406 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2407 }
2408
2409 @Override
2410 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2411 @WindowConfiguration.ActivityType int ignoreActivityType,
2412 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2413 final int callingUid = Binder.getCallingUid();
2414 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2415
2416 synchronized (mGlobalLock) {
2417 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2418
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002419 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002420 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002421 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 ignoreWindowingMode, callingUid, allowed);
2423 }
2424
2425 return list;
2426 }
2427
2428 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002429 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2430 synchronized (mGlobalLock) {
2431 final long origId = Binder.clearCallingIdentity();
2432 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2433 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002434 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002435 }
2436 Binder.restoreCallingIdentity(origId);
2437 }
2438 }
2439
2440 @Override
2441 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002442 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002443 ActivityStack stack = ActivityRecord.getStackLocked(token);
2444 if (stack != null) {
2445 return stack.willActivityBeVisibleLocked(token);
2446 }
2447 return false;
2448 }
2449 }
2450
2451 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002452 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002454 synchronized (mGlobalLock) {
2455 final long ident = Binder.clearCallingIdentity();
2456 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002457 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002458 if (task == null) {
2459 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2460 return;
2461 }
2462
2463 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2464 + " to stackId=" + stackId + " toTop=" + toTop);
2465
Wale Ogunwaled32da472018-11-16 07:19:28 -08002466 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002467 if (stack == null) {
2468 throw new IllegalStateException(
2469 "moveTaskToStack: No stack for stackId=" + stackId);
2470 }
2471 if (!stack.isActivityTypeStandardOrUndefined()) {
2472 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2473 + taskId + " to stack " + stackId);
2474 }
2475 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002476 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002477 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2478 }
2479 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2480 "moveTaskToStack");
2481 } finally {
2482 Binder.restoreCallingIdentity(ident);
2483 }
2484 }
2485 }
2486
2487 @Override
2488 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2489 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002490 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002491
2492 final long ident = Binder.clearCallingIdentity();
2493 try {
2494 synchronized (mGlobalLock) {
2495 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002496 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 if (stack == null) {
2498 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2499 return;
2500 }
2501 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2502 throw new IllegalArgumentException("Stack: " + stackId
2503 + " doesn't support animated resize.");
2504 }
2505 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2506 animationDuration, false /* fromFullscreen */);
2507 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002508 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 if (stack == null) {
2510 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2511 return;
2512 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002513 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002514 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2515 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2516 }
2517 }
2518 } finally {
2519 Binder.restoreCallingIdentity(ident);
2520 }
2521 }
2522
wilsonshih5c4cf522019-01-25 09:03:47 +08002523 @Override
2524 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2525 int animationDuration) {
2526 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2527
2528 final long ident = Binder.clearCallingIdentity();
2529 try {
2530 synchronized (mGlobalLock) {
2531 if (xOffset == 0 && yOffset == 0) {
2532 return;
2533 }
2534 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2535 if (stack == null) {
2536 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2537 return;
2538 }
2539 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2540 throw new IllegalArgumentException("Stack: " + stackId
2541 + " doesn't support animated resize.");
2542 }
2543 final Rect destBounds = new Rect();
2544 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002545 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002546 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2547 return;
2548 }
2549 destBounds.offset(xOffset, yOffset);
2550 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2551 animationDuration, false /* fromFullscreen */);
2552 }
2553 } finally {
2554 Binder.restoreCallingIdentity(ident);
2555 }
2556 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 /**
2558 * Moves the specified task to the primary-split-screen stack.
2559 *
2560 * @param taskId Id of task to move.
2561 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2562 * exist already. See
2563 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2564 * and
2565 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2566 * @param toTop If the task and stack should be moved to the top.
2567 * @param animate Whether we should play an animation for the moving the task.
2568 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2569 * stack. Pass {@code null} to use default bounds.
2570 * @param showRecents If the recents activity should be shown on the other side of the task
2571 * going into split-screen mode.
2572 */
2573 @Override
2574 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2575 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 "setTaskWindowingModeSplitScreenPrimary()");
2578 synchronized (mGlobalLock) {
2579 final long ident = Binder.clearCallingIdentity();
2580 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002581 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002582 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583 if (task == null) {
2584 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2585 return false;
2586 }
2587 if (DEBUG_STACK) Slog.d(TAG_STACK,
2588 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2589 + " to createMode=" + createMode + " toTop=" + toTop);
2590 if (!task.isActivityTypeStandardOrUndefined()) {
2591 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2592 + " non-standard task " + taskId + " to split-screen windowing mode");
2593 }
2594
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002595 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 final int windowingMode = task.getWindowingMode();
2597 final ActivityStack stack = task.getStack();
2598 if (toTop) {
2599 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2600 }
2601 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002602 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2603 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604 return windowingMode != task.getWindowingMode();
2605 } finally {
2606 Binder.restoreCallingIdentity(ident);
2607 }
2608 }
2609 }
2610
2611 /**
2612 * Removes stacks in the input windowing modes from the system if they are of activity type
2613 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2614 */
2615 @Override
2616 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002617 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002618 "removeStacksInWindowingModes()");
2619
2620 synchronized (mGlobalLock) {
2621 final long ident = Binder.clearCallingIdentity();
2622 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002623 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 } finally {
2625 Binder.restoreCallingIdentity(ident);
2626 }
2627 }
2628 }
2629
2630 @Override
2631 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002632 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 "removeStacksWithActivityTypes()");
2634
2635 synchronized (mGlobalLock) {
2636 final long ident = Binder.clearCallingIdentity();
2637 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002638 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002639 } finally {
2640 Binder.restoreCallingIdentity(ident);
2641 }
2642 }
2643 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002644
2645 @Override
2646 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2647 int userId) {
2648 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2650 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002651 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002652 final boolean detailed = checkGetTasksPermission(
2653 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2654 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002655 == PackageManager.PERMISSION_GRANTED;
2656
2657 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002658 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002659 callingUid);
2660 }
2661 }
2662
2663 @Override
2664 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002665 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002666 long ident = Binder.clearCallingIdentity();
2667 try {
2668 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002669 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002670 }
2671 } finally {
2672 Binder.restoreCallingIdentity(ident);
2673 }
2674 }
2675
2676 @Override
2677 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002678 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002679 long ident = Binder.clearCallingIdentity();
2680 try {
2681 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002682 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002683 }
2684 } finally {
2685 Binder.restoreCallingIdentity(ident);
2686 }
2687 }
2688
2689 @Override
2690 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002691 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002692 final long callingUid = Binder.getCallingUid();
2693 final long origId = Binder.clearCallingIdentity();
2694 try {
2695 synchronized (mGlobalLock) {
2696 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002697 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2699 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2700 }
2701 } finally {
2702 Binder.restoreCallingIdentity(origId);
2703 }
2704 }
2705
2706 @Override
2707 public void startLockTaskModeByToken(IBinder token) {
2708 synchronized (mGlobalLock) {
2709 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2710 if (r == null) {
2711 return;
2712 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002713 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002714 }
2715 }
2716
2717 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002718 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002719 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 // This makes inner call to look as if it was initiated by system.
2721 long ident = Binder.clearCallingIdentity();
2722 try {
2723 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002724 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002725 MATCH_TASK_IN_STACKS_ONLY);
2726 if (task == null) {
2727 return;
2728 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729
2730 // When starting lock task mode the stack must be in front and focused
2731 task.getStack().moveToFront("startSystemLockTaskMode");
2732 startLockTaskModeLocked(task, true /* isSystemCaller */);
2733 }
2734 } finally {
2735 Binder.restoreCallingIdentity(ident);
2736 }
2737 }
2738
2739 @Override
2740 public void stopLockTaskModeByToken(IBinder token) {
2741 synchronized (mGlobalLock) {
2742 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2743 if (r == null) {
2744 return;
2745 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002746 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 }
2748 }
2749
2750 /**
2751 * This API should be called by SystemUI only when user perform certain action to dismiss
2752 * lock task mode. We should only dismiss pinned lock task mode in this case.
2753 */
2754 @Override
2755 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2758 }
2759
2760 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2761 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2762 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2763 return;
2764 }
2765
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 if (stack == null || task != stack.topTask()) {
2768 throw new IllegalArgumentException("Invalid task, not in foreground");
2769 }
2770
2771 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2772 // system or a specific app.
2773 // * System-initiated requests will only start the pinned mode (screen pinning)
2774 // * App-initiated requests
2775 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2776 // - will start the pinned mode, otherwise
2777 final int callingUid = Binder.getCallingUid();
2778 long ident = Binder.clearCallingIdentity();
2779 try {
2780 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002781 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002783 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 } finally {
2785 Binder.restoreCallingIdentity(ident);
2786 }
2787 }
2788
2789 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2790 final int callingUid = Binder.getCallingUid();
2791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002794 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2797 // task and jumping straight into a call in the case of emergency call back.
2798 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2799 if (tm != null) {
2800 tm.showInCallScreen(false);
2801 }
2802 } finally {
2803 Binder.restoreCallingIdentity(ident);
2804 }
2805 }
2806
2807 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002808 public void updateLockTaskPackages(int userId, String[] packages) {
2809 final int callingUid = Binder.getCallingUid();
2810 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2811 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2812 "updateLockTaskPackages()");
2813 }
2814 synchronized (this) {
2815 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2816 + Arrays.toString(packages));
2817 getLockTaskController().updateLockTaskPackages(userId, packages);
2818 }
2819 }
2820
2821 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 public boolean isInLockTaskMode() {
2823 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2824 }
2825
2826 @Override
2827 public int getLockTaskModeState() {
2828 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002829 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 }
2831 }
2832
2833 @Override
2834 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2835 synchronized (mGlobalLock) {
2836 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2837 if (r != null) {
2838 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002839 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002841 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 }
2844 }
2845
2846 @Override
2847 public Bundle getActivityOptions(IBinder token) {
2848 final long origId = Binder.clearCallingIdentity();
2849 try {
2850 synchronized (mGlobalLock) {
2851 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2852 if (r != null) {
2853 final ActivityOptions activityOptions = r.takeOptionsLocked();
2854 return activityOptions == null ? null : activityOptions.toBundle();
2855 }
2856 return null;
2857 }
2858 } finally {
2859 Binder.restoreCallingIdentity(origId);
2860 }
2861 }
2862
2863 @Override
2864 public List<IBinder> getAppTasks(String callingPackage) {
2865 int callingUid = Binder.getCallingUid();
2866 long ident = Binder.clearCallingIdentity();
2867 try {
2868 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002869 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(ident);
2873 }
2874 }
2875
2876 @Override
2877 public void finishVoiceTask(IVoiceInteractionSession session) {
2878 synchronized (mGlobalLock) {
2879 final long origId = Binder.clearCallingIdentity();
2880 try {
2881 // TODO: VI Consider treating local voice interactions and voice tasks
2882 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002883 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 } finally {
2885 Binder.restoreCallingIdentity(origId);
2886 }
2887 }
2888
2889 }
2890
2891 @Override
2892 public boolean isTopOfTask(IBinder token) {
2893 synchronized (mGlobalLock) {
2894 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002895 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 }
2897 }
2898
2899 @Override
2900 public void notifyLaunchTaskBehindComplete(IBinder token) {
2901 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2902 }
2903
2904 @Override
2905 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002906 mH.post(() -> {
2907 synchronized (mGlobalLock) {
2908 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002909 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002910 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002911 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002912 } catch (RemoteException e) {
2913 }
2914 }
2915 }
2916
2917 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 }
2919
2920 /** Called from an app when assist data is ready. */
2921 @Override
2922 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2923 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002924 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 synchronized (pae) {
2926 pae.result = extras;
2927 pae.structure = structure;
2928 pae.content = content;
2929 if (referrer != null) {
2930 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2931 }
2932 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002933 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002934 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2935 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936 structure.setHomeActivity(pae.isHome);
2937 }
2938 pae.haveResult = true;
2939 pae.notifyAll();
2940 if (pae.intent == null && pae.receiver == null) {
2941 // Caller is just waiting for the result.
2942 return;
2943 }
2944 }
2945 // We are now ready to launch the assist activity.
2946 IAssistDataReceiver sendReceiver = null;
2947 Bundle sendBundle = null;
2948 synchronized (mGlobalLock) {
2949 buildAssistBundleLocked(pae, extras);
2950 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002951 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 if (!exists) {
2953 // Timed out.
2954 return;
2955 }
2956
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002957 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 // Caller wants result sent back to them.
2959 sendBundle = new Bundle();
2960 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2961 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2962 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2963 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2964 }
2965 }
2966 if (sendReceiver != null) {
2967 try {
2968 sendReceiver.onHandleAssistData(sendBundle);
2969 } catch (RemoteException e) {
2970 }
2971 return;
2972 }
2973
2974 final long ident = Binder.clearCallingIdentity();
2975 try {
2976 if (TextUtils.equals(pae.intent.getAction(),
2977 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2978 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01002979
2980 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002981 } else {
2982 pae.intent.replaceExtras(pae.extras);
2983 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2984 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2985 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002986 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002987
2988 try {
2989 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2990 } catch (ActivityNotFoundException e) {
2991 Slog.w(TAG, "No activity to handle assist action.", e);
2992 }
2993 }
2994 } finally {
2995 Binder.restoreCallingIdentity(ident);
2996 }
2997 }
2998
Marvin Ramin830d4e32019-03-12 13:16:58 +01002999 /**
3000 * Workaround for historical API which starts the Assist service with a non-foreground
3001 * {@code startService()} call.
3002 */
3003 private void startVoiceInteractionServiceAsUser(
3004 Intent intent, int userHandle, String reason) {
3005 // Resolve the intent to find out which package we need to whitelist.
3006 ResolveInfo resolveInfo =
3007 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3008 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3009 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3010 return;
3011 }
3012 intent.setPackage(resolveInfo.serviceInfo.packageName);
3013
3014 // Whitelist background services temporarily.
3015 LocalServices.getService(DeviceIdleController.LocalService.class)
3016 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3017 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3018
3019 // Finally, try to start the service.
3020 try {
3021 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3022 } catch (RuntimeException e) {
3023 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3024 }
3025 }
3026
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003027 @Override
3028 public int addAppTask(IBinder activityToken, Intent intent,
3029 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3030 final int callingUid = Binder.getCallingUid();
3031 final long callingIdent = Binder.clearCallingIdentity();
3032
3033 try {
3034 synchronized (mGlobalLock) {
3035 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3036 if (r == null) {
3037 throw new IllegalArgumentException("Activity does not exist; token="
3038 + activityToken);
3039 }
3040 ComponentName comp = intent.getComponent();
3041 if (comp == null) {
3042 throw new IllegalArgumentException("Intent " + intent
3043 + " must specify explicit component");
3044 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003045 if (thumbnail.getWidth() != mThumbnailWidth
3046 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 throw new IllegalArgumentException("Bad thumbnail size: got "
3048 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003049 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 }
3051 if (intent.getSelector() != null) {
3052 intent.setSelector(null);
3053 }
3054 if (intent.getSourceBounds() != null) {
3055 intent.setSourceBounds(null);
3056 }
3057 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3058 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3059 // The caller has added this as an auto-remove task... that makes no
3060 // sense, so turn off auto-remove.
3061 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3062 }
3063 }
3064 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3065 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3066 if (ainfo.applicationInfo.uid != callingUid) {
3067 throw new SecurityException(
3068 "Can't add task for another application: target uid="
3069 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3070 }
3071
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003072 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003074 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003076 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 // The app has too many tasks already and we can't add any more
3078 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3079 return INVALID_TASK_ID;
3080 }
3081 task.lastTaskDescription.copyFrom(description);
3082
3083 // TODO: Send the thumbnail to WM to store it.
3084
3085 return task.taskId;
3086 }
3087 } finally {
3088 Binder.restoreCallingIdentity(callingIdent);
3089 }
3090 }
3091
3092 @Override
3093 public Point getAppTaskThumbnailSize() {
3094 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 }
3097 }
3098
3099 @Override
3100 public void setTaskResizeable(int taskId, int resizeableMode) {
3101 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003102 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3104 if (task == null) {
3105 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3106 return;
3107 }
3108 task.setResizeMode(resizeableMode);
3109 }
3110 }
3111
3112 @Override
3113 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003114 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 long ident = Binder.clearCallingIdentity();
3116 try {
3117 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003118 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003119 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003120 if (task == null) {
3121 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3122 return;
3123 }
3124 // Place the task in the right stack if it isn't there already based on
3125 // the requested bounds.
3126 // The stack transition logic is:
3127 // - a null bounds on a freeform task moves that task to fullscreen
3128 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3129 // that task to freeform
3130 // - otherwise the task is not moved
3131 ActivityStack stack = task.getStack();
3132 if (!task.getWindowConfiguration().canResizeTask()) {
3133 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3134 }
3135 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3136 stack = stack.getDisplay().getOrCreateStack(
3137 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3138 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3139 stack = stack.getDisplay().getOrCreateStack(
3140 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3141 }
3142
3143 // Reparent the task to the right stack if necessary
3144 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3145 if (stack != task.getStack()) {
3146 // Defer resume until the task is resized below
3147 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3148 DEFER_RESUME, "resizeTask");
3149 preserveWindow = false;
3150 }
3151
3152 // After reparenting (which only resizes the task to the stack bounds), resize the
3153 // task to the actual bounds provided
3154 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3155 }
3156 } finally {
3157 Binder.restoreCallingIdentity(ident);
3158 }
3159 }
3160
3161 @Override
3162 public boolean releaseActivityInstance(IBinder token) {
3163 synchronized (mGlobalLock) {
3164 final long origId = Binder.clearCallingIdentity();
3165 try {
3166 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3167 if (r == null) {
3168 return false;
3169 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003170 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 } finally {
3172 Binder.restoreCallingIdentity(origId);
3173 }
3174 }
3175 }
3176
3177 @Override
3178 public void releaseSomeActivities(IApplicationThread appInt) {
3179 synchronized (mGlobalLock) {
3180 final long origId = Binder.clearCallingIdentity();
3181 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003182 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003183 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003184 } finally {
3185 Binder.restoreCallingIdentity(origId);
3186 }
3187 }
3188 }
3189
3190 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003191 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003192 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 != PackageManager.PERMISSION_GRANTED) {
3194 throw new SecurityException("Requires permission "
3195 + android.Manifest.permission.DEVICE_POWER);
3196 }
3197
3198 synchronized (mGlobalLock) {
3199 long ident = Binder.clearCallingIdentity();
3200 if (mKeyguardShown != keyguardShowing) {
3201 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003202 final Message msg = PooledLambda.obtainMessage(
3203 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3204 keyguardShowing);
3205 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 }
3207 try {
wilsonshih177261f2019-02-22 12:02:18 +08003208 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 } finally {
3210 Binder.restoreCallingIdentity(ident);
3211 }
3212 }
3213
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003214 mH.post(() -> {
3215 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3216 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3217 }
3218 });
3219 }
3220
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003221 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003222 mH.post(() -> {
3223 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3224 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3225 }
3226 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228
3229 @Override
3230 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003231 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3232 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233
3234 final File passedIconFile = new File(filePath);
3235 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3236 passedIconFile.getName());
3237 if (!legitIconFile.getPath().equals(filePath)
3238 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3239 throw new IllegalArgumentException("Bad file path: " + filePath
3240 + " passed for userId " + userId);
3241 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003242 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 }
3244
3245 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3248 final ActivityOptions activityOptions = safeOptions != null
3249 ? safeOptions.getOptions(mStackSupervisor)
3250 : null;
3251 if (activityOptions == null
3252 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3253 || activityOptions.getCustomInPlaceResId() == 0) {
3254 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3255 "with valid animation");
3256 }
lumark588a3e82018-07-20 18:53:54 +08003257 // Get top display of front most application.
3258 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3259 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003260 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3261 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3262 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003263 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003264 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003265 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 }
3267
3268 @Override
3269 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003270 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 synchronized (mGlobalLock) {
3272 final long ident = Binder.clearCallingIdentity();
3273 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003274 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 if (stack == null) {
3276 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3277 return;
3278 }
3279 if (!stack.isActivityTypeStandardOrUndefined()) {
3280 throw new IllegalArgumentException(
3281 "Removing non-standard stack is not allowed.");
3282 }
3283 mStackSupervisor.removeStack(stack);
3284 } finally {
3285 Binder.restoreCallingIdentity(ident);
3286 }
3287 }
3288 }
3289
3290 @Override
3291 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293
3294 synchronized (mGlobalLock) {
3295 final long ident = Binder.clearCallingIdentity();
3296 try {
3297 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3298 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003299 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003300 } finally {
3301 Binder.restoreCallingIdentity(ident);
3302 }
3303 }
3304 }
3305
3306 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003307 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 synchronized (mGlobalLock) {
3309 long ident = Binder.clearCallingIdentity();
3310 try {
3311 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3312 if (r == null) {
3313 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003314 "toggleFreeformWindowingMode: No activity record matching token="
3315 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 }
3317
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003318 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003319 if (stack == null) {
3320 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3321 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 }
3323
Yunfan Chend967af82019-01-17 18:30:18 +09003324 if (!stack.inFreeformWindowingMode()
3325 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3326 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3327 + "toggle between fullscreen and freeform.");
3328 }
3329
3330 if (stack.inFreeformWindowingMode()) {
3331 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3332 } else {
3333 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3334 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 } finally {
3336 Binder.restoreCallingIdentity(ident);
3337 }
3338 }
3339 }
3340
3341 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3342 @Override
3343 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003346 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 }
3348
3349 /** Unregister a task stack listener so that it stops receiving callbacks. */
3350 @Override
3351 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003352 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003354 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355 }
3356
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 @Override
3358 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3359 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3360 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3361 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3362 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3363 }
3364
3365 @Override
3366 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3367 IBinder activityToken, int flags) {
3368 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3369 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3370 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3371 }
3372
3373 @Override
3374 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3375 Bundle args) {
3376 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3377 true /* focused */, true /* newSessionId */, userHandle, args,
3378 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3379 }
3380
3381 @Override
3382 public Bundle getAssistContextExtras(int requestType) {
3383 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3384 null, null, true /* focused */, true /* newSessionId */,
3385 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3386 if (pae == null) {
3387 return null;
3388 }
3389 synchronized (pae) {
3390 while (!pae.haveResult) {
3391 try {
3392 pae.wait();
3393 } catch (InterruptedException e) {
3394 }
3395 }
3396 }
3397 synchronized (mGlobalLock) {
3398 buildAssistBundleLocked(pae, pae.result);
3399 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 }
3402 return pae.extras;
3403 }
3404
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003405 /**
3406 * Binder IPC calls go through the public entry point.
3407 * This can be called with or without the global lock held.
3408 */
3409 private static int checkCallingPermission(String permission) {
3410 return checkPermission(
3411 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3412 }
3413
3414 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003415 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3417 mAmInternal.enforceCallingPermission(permission, func);
3418 }
3419 }
3420
3421 @VisibleForTesting
3422 int checkGetTasksPermission(String permission, int pid, int uid) {
3423 return checkPermission(permission, pid, uid);
3424 }
3425
3426 static int checkPermission(String permission, int pid, int uid) {
3427 if (permission == null) {
3428 return PackageManager.PERMISSION_DENIED;
3429 }
3430 return checkComponentPermission(permission, pid, uid, -1, true);
3431 }
3432
Wale Ogunwale214f3482018-10-04 11:00:47 -07003433 public static int checkComponentPermission(String permission, int pid, int uid,
3434 int owningUid, boolean exported) {
3435 return ActivityManagerService.checkComponentPermission(
3436 permission, pid, uid, owningUid, exported);
3437 }
3438
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003439 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3440 if (getRecentTasks().isCallerRecents(callingUid)) {
3441 // Always allow the recents component to get tasks
3442 return true;
3443 }
3444
3445 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3446 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3447 if (!allowed) {
3448 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3449 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3450 // Temporary compatibility: some existing apps on the system image may
3451 // still be requesting the old permission and not switched to the new
3452 // one; if so, we'll still allow them full access. This means we need
3453 // to see if they are holding the old permission and are a system app.
3454 try {
3455 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3456 allowed = true;
3457 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3458 + " is using old GET_TASKS but privileged; allowing");
3459 }
3460 } catch (RemoteException e) {
3461 }
3462 }
3463 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3464 + " does not hold REAL_GET_TASKS; limiting output");
3465 }
3466 return allowed;
3467 }
3468
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3470 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3471 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3472 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003473 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 "enqueueAssistContext()");
3475
3476 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003477 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 if (activity == null) {
3479 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3480 return null;
3481 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003482 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3484 return null;
3485 }
3486 if (focused) {
3487 if (activityToken != null) {
3488 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3489 if (activity != caller) {
3490 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3491 + " is not current top " + activity);
3492 return null;
3493 }
3494 }
3495 } else {
3496 activity = ActivityRecord.forTokenLocked(activityToken);
3497 if (activity == null) {
3498 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3499 + " couldn't be found");
3500 return null;
3501 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003502 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003503 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3504 return null;
3505 }
3506 }
3507
3508 PendingAssistExtras pae;
3509 Bundle extras = new Bundle();
3510 if (args != null) {
3511 extras.putAll(args);
3512 }
3513 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003514 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515
3516 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3517 userHandle);
3518 pae.isHome = activity.isActivityTypeHome();
3519
3520 // Increment the sessionId if necessary
3521 if (newSessionId) {
3522 mViSessionId++;
3523 }
3524 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003525 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3526 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003528 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003529 } catch (RemoteException e) {
3530 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3531 return null;
3532 }
3533 return pae;
3534 }
3535 }
3536
3537 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3538 if (result != null) {
3539 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3540 }
3541 if (pae.hint != null) {
3542 pae.extras.putBoolean(pae.hint, true);
3543 }
3544 }
3545
3546 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3547 IAssistDataReceiver receiver;
3548 synchronized (mGlobalLock) {
3549 mPendingAssistExtras.remove(pae);
3550 receiver = pae.receiver;
3551 }
3552 if (receiver != null) {
3553 // Caller wants result sent back to them.
3554 Bundle sendBundle = new Bundle();
3555 // At least return the receiver extras
3556 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3557 try {
3558 pae.receiver.onHandleAssistData(sendBundle);
3559 } catch (RemoteException e) {
3560 }
3561 }
3562 }
3563
3564 public class PendingAssistExtras extends Binder implements Runnable {
3565 public final ActivityRecord activity;
3566 public boolean isHome;
3567 public final Bundle extras;
3568 public final Intent intent;
3569 public final String hint;
3570 public final IAssistDataReceiver receiver;
3571 public final int userHandle;
3572 public boolean haveResult = false;
3573 public Bundle result = null;
3574 public AssistStructure structure = null;
3575 public AssistContent content = null;
3576 public Bundle receiverExtras;
3577
3578 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3579 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3580 int _userHandle) {
3581 activity = _activity;
3582 extras = _extras;
3583 intent = _intent;
3584 hint = _hint;
3585 receiver = _receiver;
3586 receiverExtras = _receiverExtras;
3587 userHandle = _userHandle;
3588 }
3589
3590 @Override
3591 public void run() {
3592 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3593 synchronized (this) {
3594 haveResult = true;
3595 notifyAll();
3596 }
3597 pendingAssistExtrasTimedOut(this);
3598 }
3599 }
3600
3601 @Override
3602 public boolean isAssistDataAllowedOnCurrentActivity() {
3603 int userId;
3604 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003605 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3607 return false;
3608 }
3609
3610 final ActivityRecord activity = focusedStack.getTopActivity();
3611 if (activity == null) {
3612 return false;
3613 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003614 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003615 }
3616 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3617 }
3618
3619 @Override
3620 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3621 long ident = Binder.clearCallingIdentity();
3622 try {
3623 synchronized (mGlobalLock) {
3624 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003625 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 if (top != caller) {
3627 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3628 + " is not current top " + top);
3629 return false;
3630 }
3631 if (!top.nowVisible) {
3632 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3633 + " is not visible");
3634 return false;
3635 }
3636 }
3637 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3638 token);
3639 } finally {
3640 Binder.restoreCallingIdentity(ident);
3641 }
3642 }
3643
3644 @Override
3645 public boolean isRootVoiceInteraction(IBinder token) {
3646 synchronized (mGlobalLock) {
3647 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3648 if (r == null) {
3649 return false;
3650 }
3651 return r.rootVoiceInteraction;
3652 }
3653 }
3654
Wale Ogunwalef6733932018-06-27 05:14:34 -07003655 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3656 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3657 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3658 if (activityToCallback == null) return;
3659 activityToCallback.setVoiceSessionLocked(voiceSession);
3660
3661 // Inform the activity
3662 try {
3663 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3664 voiceInteractor);
3665 long token = Binder.clearCallingIdentity();
3666 try {
3667 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3668 } finally {
3669 Binder.restoreCallingIdentity(token);
3670 }
3671 // TODO: VI Should we cache the activity so that it's easier to find later
3672 // rather than scan through all the stacks and activities?
3673 } catch (RemoteException re) {
3674 activityToCallback.clearVoiceSessionLocked();
3675 // TODO: VI Should this terminate the voice session?
3676 }
3677 }
3678
3679 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3680 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3681 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3682 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3683 boolean wasRunningVoice = mRunningVoice != null;
3684 mRunningVoice = session;
3685 if (!wasRunningVoice) {
3686 mVoiceWakeLock.acquire();
3687 updateSleepIfNeededLocked();
3688 }
3689 }
3690 }
3691
3692 void finishRunningVoiceLocked() {
3693 if (mRunningVoice != null) {
3694 mRunningVoice = null;
3695 mVoiceWakeLock.release();
3696 updateSleepIfNeededLocked();
3697 }
3698 }
3699
3700 @Override
3701 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3702 synchronized (mGlobalLock) {
3703 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3704 if (keepAwake) {
3705 mVoiceWakeLock.acquire();
3706 } else {
3707 mVoiceWakeLock.release();
3708 }
3709 }
3710 }
3711 }
3712
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 @Override
3714 public ComponentName getActivityClassForToken(IBinder token) {
3715 synchronized (mGlobalLock) {
3716 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3717 if (r == null) {
3718 return null;
3719 }
3720 return r.intent.getComponent();
3721 }
3722 }
3723
3724 @Override
3725 public String getPackageForToken(IBinder token) {
3726 synchronized (mGlobalLock) {
3727 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3728 if (r == null) {
3729 return null;
3730 }
3731 return r.packageName;
3732 }
3733 }
3734
3735 @Override
3736 public void showLockTaskEscapeMessage(IBinder token) {
3737 synchronized (mGlobalLock) {
3738 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3739 if (r == null) {
3740 return;
3741 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003742 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003743 }
3744 }
3745
3746 @Override
3747 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003748 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 final long token = Binder.clearCallingIdentity();
3750 try {
3751 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003752 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 }
3754 } finally {
3755 Binder.restoreCallingIdentity(token);
3756 }
3757 }
3758
3759 /**
3760 * Try to place task to provided position. The final position might be different depending on
3761 * current user and stacks state. The task will be moved to target stack if it's currently in
3762 * different stack.
3763 */
3764 @Override
3765 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003766 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003767 synchronized (mGlobalLock) {
3768 long ident = Binder.clearCallingIdentity();
3769 try {
3770 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3771 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003772 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 if (task == null) {
3774 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3775 + taskId);
3776 }
3777
Wale Ogunwaled32da472018-11-16 07:19:28 -08003778 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003779
3780 if (stack == null) {
3781 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3782 + stackId);
3783 }
3784 if (!stack.isActivityTypeStandardOrUndefined()) {
3785 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3786 + " the position of task " + taskId + " in/to non-standard stack");
3787 }
3788
3789 // TODO: Have the callers of this API call a separate reparent method if that is
3790 // what they intended to do vs. having this method also do reparenting.
3791 if (task.getStack() == stack) {
3792 // Change position in current stack.
3793 stack.positionChildAt(task, position);
3794 } else {
3795 // Reparent to new stack.
3796 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3797 !DEFER_RESUME, "positionTaskInStack");
3798 }
3799 } finally {
3800 Binder.restoreCallingIdentity(ident);
3801 }
3802 }
3803 }
3804
3805 @Override
3806 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3807 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3808 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3809 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3810 synchronized (mGlobalLock) {
3811 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3812 if (record == null) {
3813 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3814 + "found for: " + token);
3815 }
3816 record.setSizeConfigurations(horizontalSizeConfiguration,
3817 verticalSizeConfigurations, smallestSizeConfigurations);
3818 }
3819 }
3820
3821 /**
3822 * Dismisses split-screen multi-window mode.
3823 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3824 */
3825 @Override
3826 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003827 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3829 final long ident = Binder.clearCallingIdentity();
3830 try {
3831 synchronized (mGlobalLock) {
3832 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003833 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834 if (stack == null) {
3835 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3836 return;
3837 }
3838
3839 if (toTop) {
3840 // Caller wants the current split-screen primary stack to be the top stack after
3841 // it goes fullscreen, so move it to the front.
3842 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003843 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 // In this case the current split-screen primary stack shouldn't be the top
3845 // stack after it goes fullscreen, but it current has focus, so we move the
3846 // focus to the top-most split-screen secondary stack next to it.
3847 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3848 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3849 if (otherStack != null) {
3850 otherStack.moveToFront("dismissSplitScreenMode_other");
3851 }
3852 }
3853
Evan Rosky10475742018-09-05 19:02:48 -07003854 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 }
3856 } finally {
3857 Binder.restoreCallingIdentity(ident);
3858 }
3859 }
3860
3861 /**
3862 * Dismisses Pip
3863 * @param animate True if the dismissal should be animated.
3864 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3865 * default animation duration should be used.
3866 */
3867 @Override
3868 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003869 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 final long ident = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003873 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003874 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 if (stack == null) {
3876 Slog.w(TAG, "dismissPip: pinned stack not found.");
3877 return;
3878 }
3879 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3880 throw new IllegalArgumentException("Stack: " + stack
3881 + " doesn't support animated resize.");
3882 }
3883 if (animate) {
3884 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3885 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3886 } else {
3887 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3888 }
3889 }
3890 } finally {
3891 Binder.restoreCallingIdentity(ident);
3892 }
3893 }
3894
3895 @Override
3896 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003897 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 synchronized (mGlobalLock) {
3899 mSuppressResizeConfigChanges = suppress;
3900 }
3901 }
3902
3903 /**
3904 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3905 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3906 * activity and clearing the task at the same time.
3907 */
3908 @Override
3909 // TODO: API should just be about changing windowing modes...
3910 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 "moveTasksToFullscreenStack()");
3913 synchronized (mGlobalLock) {
3914 final long origId = Binder.clearCallingIdentity();
3915 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003916 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 if (stack != null){
3918 if (!stack.isActivityTypeStandardOrUndefined()) {
3919 throw new IllegalArgumentException(
3920 "You can't move tasks from non-standard stacks.");
3921 }
3922 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(origId);
3926 }
3927 }
3928 }
3929
3930 /**
3931 * Moves the top activity in the input stackId to the pinned stack.
3932 *
3933 * @param stackId Id of stack to move the top activity to pinned stack.
3934 * @param bounds Bounds to use for pinned stack.
3935 *
3936 * @return True if the top activity of the input stack was successfully moved to the pinned
3937 * stack.
3938 */
3939 @Override
3940 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003941 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003942 "moveTopActivityToPinnedStack()");
3943 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003944 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3946 + "Device doesn't support picture-in-picture mode");
3947 }
3948
3949 long ident = Binder.clearCallingIdentity();
3950 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003951 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 } finally {
3953 Binder.restoreCallingIdentity(ident);
3954 }
3955 }
3956 }
3957
3958 @Override
3959 public boolean isInMultiWindowMode(IBinder token) {
3960 final long origId = Binder.clearCallingIdentity();
3961 try {
3962 synchronized (mGlobalLock) {
3963 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3964 if (r == null) {
3965 return false;
3966 }
3967 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3968 return r.inMultiWindowMode();
3969 }
3970 } finally {
3971 Binder.restoreCallingIdentity(origId);
3972 }
3973 }
3974
3975 @Override
3976 public boolean isInPictureInPictureMode(IBinder token) {
3977 final long origId = Binder.clearCallingIdentity();
3978 try {
3979 synchronized (mGlobalLock) {
3980 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3981 }
3982 } finally {
3983 Binder.restoreCallingIdentity(origId);
3984 }
3985 }
3986
3987 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003988 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3989 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 return false;
3991 }
3992
3993 // If we are animating to fullscreen then we have already dispatched the PIP mode
3994 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003995 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3996 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 }
3998
3999 @Override
4000 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4001 final long origId = Binder.clearCallingIdentity();
4002 try {
4003 synchronized (mGlobalLock) {
4004 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4005 "enterPictureInPictureMode", token, params);
4006
4007 // If the activity is already in picture in picture mode, then just return early
4008 if (isInPictureInPictureMode(r)) {
4009 return true;
4010 }
4011
4012 // Activity supports picture-in-picture, now check that we can enter PiP at this
4013 // point, if it is
4014 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4015 false /* beforeStopping */)) {
4016 return false;
4017 }
4018
4019 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004020 synchronized (mGlobalLock) {
4021 // Only update the saved args from the args that are set
4022 r.pictureInPictureArgs.copyOnlySet(params);
4023 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4024 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4025 // Adjust the source bounds by the insets for the transition down
4026 final Rect sourceBounds = new Rect(
4027 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004028 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004029 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004030 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004031 stack.setPictureInPictureAspectRatio(aspectRatio);
4032 stack.setPictureInPictureActions(actions);
4033 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4034 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4035 logPictureInPictureArgs(params);
4036 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 };
4038
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004039 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 // If the keyguard is showing or occluded, then try and dismiss it before
4041 // entering picture-in-picture (this will prompt the user to authenticate if the
4042 // device is currently locked).
4043 dismissKeyguard(token, new KeyguardDismissCallback() {
4044 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 public void onDismissSucceeded() {
4046 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 }
4048 }, null /* message */);
4049 } else {
4050 // Enter picture in picture immediately otherwise
4051 enterPipRunnable.run();
4052 }
4053 return true;
4054 }
4055 } finally {
4056 Binder.restoreCallingIdentity(origId);
4057 }
4058 }
4059
4060 @Override
4061 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4062 final long origId = Binder.clearCallingIdentity();
4063 try {
4064 synchronized (mGlobalLock) {
4065 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4066 "setPictureInPictureParams", token, params);
4067
4068 // Only update the saved args from the args that are set
4069 r.pictureInPictureArgs.copyOnlySet(params);
4070 if (r.inPinnedWindowingMode()) {
4071 // If the activity is already in picture-in-picture, update the pinned stack now
4072 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4073 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004074 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 if (!stack.isAnimatingBoundsToFullscreen()) {
4076 stack.setPictureInPictureAspectRatio(
4077 r.pictureInPictureArgs.getAspectRatio());
4078 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4079 }
4080 }
4081 logPictureInPictureArgs(params);
4082 }
4083 } finally {
4084 Binder.restoreCallingIdentity(origId);
4085 }
4086 }
4087
4088 @Override
4089 public int getMaxNumPictureInPictureActions(IBinder token) {
4090 // Currently, this is a static constant, but later, we may change this to be dependent on
4091 // the context of the activity
4092 return 3;
4093 }
4094
4095 private void logPictureInPictureArgs(PictureInPictureParams params) {
4096 if (params.hasSetActions()) {
4097 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4098 params.getActions().size());
4099 }
4100 if (params.hasSetAspectRatio()) {
4101 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4102 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4103 MetricsLogger.action(lm);
4104 }
4105 }
4106
4107 /**
4108 * Checks the state of the system and the activity associated with the given {@param token} to
4109 * verify that picture-in-picture is supported for that activity.
4110 *
4111 * @return the activity record for the given {@param token} if all the checks pass.
4112 */
4113 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4114 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 throw new IllegalStateException(caller
4117 + ": Device doesn't support picture-in-picture mode.");
4118 }
4119
4120 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4121 if (r == null) {
4122 throw new IllegalStateException(caller
4123 + ": Can't find activity for token=" + token);
4124 }
4125
4126 if (!r.supportsPictureInPicture()) {
4127 throw new IllegalStateException(caller
4128 + ": Current activity does not support picture-in-picture.");
4129 }
4130
4131 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004132 && !mWindowManager.isValidPictureInPictureAspectRatio(
4133 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 final float minAspectRatio = mContext.getResources().getFloat(
4135 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4136 final float maxAspectRatio = mContext.getResources().getFloat(
4137 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4138 throw new IllegalArgumentException(String.format(caller
4139 + ": Aspect ratio is too extreme (must be between %f and %f).",
4140 minAspectRatio, maxAspectRatio));
4141 }
4142
4143 // Truncate the number of actions if necessary
4144 params.truncateActions(getMaxNumPictureInPictureActions(token));
4145
4146 return r;
4147 }
4148
4149 @Override
4150 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004151 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 synchronized (mGlobalLock) {
4153 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4154 if (r == null) {
4155 throw new IllegalArgumentException("Activity does not exist; token="
4156 + activityToken);
4157 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004158 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 }
4160 }
4161
4162 @Override
4163 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4164 Rect tempDockedTaskInsetBounds,
4165 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004166 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 long ident = Binder.clearCallingIdentity();
4168 try {
4169 synchronized (mGlobalLock) {
4170 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4171 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4172 PRESERVE_WINDOWS);
4173 }
4174 } finally {
4175 Binder.restoreCallingIdentity(ident);
4176 }
4177 }
4178
4179 @Override
4180 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 final long ident = Binder.clearCallingIdentity();
4183 try {
4184 synchronized (mGlobalLock) {
4185 mStackSupervisor.setSplitScreenResizing(resizing);
4186 }
4187 } finally {
4188 Binder.restoreCallingIdentity(ident);
4189 }
4190 }
4191
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 /**
4193 * Check that we have the features required for VR-related API calls, and throw an exception if
4194 * not.
4195 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004196 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004197 if (!mContext.getPackageManager().hasSystemFeature(
4198 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4199 throw new UnsupportedOperationException("VR mode not supported on this device!");
4200 }
4201 }
4202
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 @Override
4204 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206
4207 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4208
4209 ActivityRecord r;
4210 synchronized (mGlobalLock) {
4211 r = ActivityRecord.isInStackLocked(token);
4212 }
4213
4214 if (r == null) {
4215 throw new IllegalArgumentException();
4216 }
4217
4218 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004219 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004220 VrManagerInternal.NO_ERROR) {
4221 return err;
4222 }
4223
4224 // Clear the binder calling uid since this path may call moveToTask().
4225 final long callingId = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
4228 r.requestedVrComponent = (enabled) ? packageName : null;
4229
4230 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004231 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004232 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 }
4234 return 0;
4235 }
4236 } finally {
4237 Binder.restoreCallingIdentity(callingId);
4238 }
4239 }
4240
4241 @Override
4242 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4243 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4244 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004245 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4247 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4248 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004249 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 || activity.voiceSession != null) {
4251 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4252 return;
4253 }
4254 if (activity.pendingVoiceInteractionStart) {
4255 Slog.w(TAG, "Pending start of voice interaction already.");
4256 return;
4257 }
4258 activity.pendingVoiceInteractionStart = true;
4259 }
4260 LocalServices.getService(VoiceInteractionManagerInternal.class)
4261 .startLocalVoiceInteraction(callingActivity, options);
4262 }
4263
4264 @Override
4265 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4266 LocalServices.getService(VoiceInteractionManagerInternal.class)
4267 .stopLocalVoiceInteraction(callingActivity);
4268 }
4269
4270 @Override
4271 public boolean supportsLocalVoiceInteraction() {
4272 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4273 .supportsLocalVoiceInteraction();
4274 }
4275
4276 /** Notifies all listeners when the pinned stack animation starts. */
4277 @Override
4278 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004279 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 }
4281
4282 /** Notifies all listeners when the pinned stack animation ends. */
4283 @Override
4284 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004285 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 }
4287
4288 @Override
4289 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004290 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291 final long ident = Binder.clearCallingIdentity();
4292 try {
4293 synchronized (mGlobalLock) {
4294 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4295 }
4296 } finally {
4297 Binder.restoreCallingIdentity(ident);
4298 }
4299 }
4300
4301 @Override
4302 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004303 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304
4305 synchronized (mGlobalLock) {
4306 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004307 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 // Call might come when display is not yet added or has already been removed.
4309 if (DEBUG_CONFIGURATION) {
4310 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4311 + displayId);
4312 }
4313 return false;
4314 }
4315
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319 }
4320
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004321 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004322 final Message msg = PooledLambda.obtainMessage(
4323 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4324 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 }
4326
4327 final long origId = Binder.clearCallingIdentity();
4328 try {
4329 if (values != null) {
4330 Settings.System.clearConfiguration(values);
4331 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4334 return mTmpUpdateConfigurationResult.changes != 0;
4335 } finally {
4336 Binder.restoreCallingIdentity(origId);
4337 }
4338 }
4339 }
4340
4341 @Override
4342 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004343 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004344
4345 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004348 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 }
4350
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004352 final Message msg = PooledLambda.obtainMessage(
4353 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4354 DEFAULT_DISPLAY);
4355 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
4357
4358 final long origId = Binder.clearCallingIdentity();
4359 try {
4360 if (values != null) {
4361 Settings.System.clearConfiguration(values);
4362 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 UserHandle.USER_NULL, false /* deferResume */,
4365 mTmpUpdateConfigurationResult);
4366 return mTmpUpdateConfigurationResult.changes != 0;
4367 } finally {
4368 Binder.restoreCallingIdentity(origId);
4369 }
4370 }
4371 }
4372
4373 @Override
4374 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4375 CharSequence message) {
4376 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004377 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4379 }
4380 final long callingId = Binder.clearCallingIdentity();
4381 try {
4382 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004383 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 }
4385 } finally {
4386 Binder.restoreCallingIdentity(callingId);
4387 }
4388 }
4389
4390 @Override
4391 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 "cancelTaskWindowTransition()");
4394 final long ident = Binder.clearCallingIdentity();
4395 try {
4396 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004397 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 MATCH_TASK_IN_STACKS_ONLY);
4399 if (task == null) {
4400 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4401 return;
4402 }
4403 task.cancelWindowTransition();
4404 }
4405 } finally {
4406 Binder.restoreCallingIdentity(ident);
4407 }
4408 }
4409
4410 @Override
4411 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004412 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 final long ident = Binder.clearCallingIdentity();
4414 try {
4415 final TaskRecord task;
4416 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004417 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4419 if (task == null) {
4420 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4421 return null;
4422 }
4423 }
4424 // Don't call this while holding the lock as this operation might hit the disk.
4425 return task.getSnapshot(reducedResolution);
4426 } finally {
4427 Binder.restoreCallingIdentity(ident);
4428 }
4429 }
4430
4431 @Override
4432 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4433 synchronized (mGlobalLock) {
4434 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4435 if (r == null) {
4436 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4437 + token);
4438 return;
4439 }
4440 final long origId = Binder.clearCallingIdentity();
4441 try {
4442 r.setDisablePreviewScreenshots(disable);
4443 } finally {
4444 Binder.restoreCallingIdentity(origId);
4445 }
4446 }
4447 }
4448
4449 /** Return the user id of the last resumed activity. */
4450 @Override
4451 public @UserIdInt
4452 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4455 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004456 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004459 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 }
4461 }
4462
4463 @Override
4464 public void updateLockTaskFeatures(int userId, int flags) {
4465 final int callingUid = Binder.getCallingUid();
4466 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 "updateLockTaskFeatures()");
4469 }
4470 synchronized (mGlobalLock) {
4471 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4472 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004473 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 }
4475 }
4476
4477 @Override
4478 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4479 synchronized (mGlobalLock) {
4480 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4481 if (r == null) {
4482 return;
4483 }
4484 final long origId = Binder.clearCallingIdentity();
4485 try {
4486 r.setShowWhenLocked(showWhenLocked);
4487 } finally {
4488 Binder.restoreCallingIdentity(origId);
4489 }
4490 }
4491 }
4492
4493 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004494 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4495 synchronized (mGlobalLock) {
4496 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4497 if (r == null) {
4498 return;
4499 }
4500 final long origId = Binder.clearCallingIdentity();
4501 try {
4502 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4503 } finally {
4504 Binder.restoreCallingIdentity(origId);
4505 }
4506 }
4507 }
4508
4509 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004510 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4511 synchronized (mGlobalLock) {
4512 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4513 if (r == null) {
4514 return;
4515 }
4516 final long origId = Binder.clearCallingIdentity();
4517 try {
4518 r.setTurnScreenOn(turnScreenOn);
4519 } finally {
4520 Binder.restoreCallingIdentity(origId);
4521 }
4522 }
4523 }
4524
4525 @Override
4526 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004527 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528 "registerRemoteAnimations");
4529 definition.setCallingPid(Binder.getCallingPid());
4530 synchronized (mGlobalLock) {
4531 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4532 if (r == null) {
4533 return;
4534 }
4535 final long origId = Binder.clearCallingIdentity();
4536 try {
4537 r.registerRemoteAnimations(definition);
4538 } finally {
4539 Binder.restoreCallingIdentity(origId);
4540 }
4541 }
4542 }
4543
4544 @Override
4545 public void registerRemoteAnimationForNextActivityStart(String packageName,
4546 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 "registerRemoteAnimationForNextActivityStart");
4549 adapter.setCallingPid(Binder.getCallingPid());
4550 synchronized (mGlobalLock) {
4551 final long origId = Binder.clearCallingIdentity();
4552 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004553 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 packageName, adapter);
4555 } finally {
4556 Binder.restoreCallingIdentity(origId);
4557 }
4558 }
4559 }
4560
Evan Rosky966759f2019-01-15 10:33:58 -08004561 @Override
4562 public void registerRemoteAnimationsForDisplay(int displayId,
4563 RemoteAnimationDefinition definition) {
4564 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4565 "registerRemoteAnimations");
4566 definition.setCallingPid(Binder.getCallingPid());
4567 synchronized (mGlobalLock) {
4568 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4569 if (display == null) {
4570 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4571 return;
4572 }
4573 final long origId = Binder.clearCallingIdentity();
4574 try {
4575 display.mDisplayContent.registerRemoteAnimations(definition);
4576 } finally {
4577 Binder.restoreCallingIdentity(origId);
4578 }
4579 }
4580 }
4581
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4583 @Override
4584 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4585 synchronized (mGlobalLock) {
4586 final long origId = Binder.clearCallingIdentity();
4587 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004588 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004589 } finally {
4590 Binder.restoreCallingIdentity(origId);
4591 }
4592 }
4593 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004594
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004595 @Override
4596 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004597 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004598 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004599 final int pid = Binder.getCallingPid();
4600 final WindowProcessController wpc = mPidMap.get(pid);
4601 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004602 }
4603 }
4604
4605 @Override
4606 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004607 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004608 != PERMISSION_GRANTED) {
4609 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4610 + Binder.getCallingPid()
4611 + ", uid=" + Binder.getCallingUid()
4612 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4613 Slog.w(TAG, msg);
4614 throw new SecurityException(msg);
4615 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004616 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004617 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004618 final int pid = Binder.getCallingPid();
4619 final WindowProcessController proc = mPidMap.get(pid);
4620 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004621 }
4622 }
4623
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004624 @Override
4625 public void stopAppSwitches() {
4626 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4627 synchronized (mGlobalLock) {
4628 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4629 mDidAppSwitch = false;
4630 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4631 }
4632 }
4633
4634 @Override
4635 public void resumeAppSwitches() {
4636 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4637 synchronized (mGlobalLock) {
4638 // Note that we don't execute any pending app switches... we will
4639 // let those wait until either the timeout, or the next start
4640 // activity request.
4641 mAppSwitchesAllowedTime = 0;
4642 }
4643 }
4644
4645 void onStartActivitySetDidAppSwitch() {
4646 if (mDidAppSwitch) {
4647 // This is the second allowed switch since we stopped switches, so now just generally
4648 // allow switches. Use case:
4649 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4650 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4651 // anyone to switch again).
4652 mAppSwitchesAllowedTime = 0;
4653 } else {
4654 mDidAppSwitch = true;
4655 }
4656 }
4657
4658 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 boolean shouldDisableNonVrUiLocked() {
4660 return mVrController.shouldDisableNonVrUiLocked();
4661 }
4662
Wale Ogunwale53783742018-09-16 10:21:51 -07004663 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 // VR apps are expected to run in a main display. If an app is turning on VR for
4665 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4666 // fullscreen stack before enabling VR Mode.
4667 // TODO: The goal of this code is to keep the VR app on the main display. When the
4668 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4669 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4670 // option would be a better choice here.
4671 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4672 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4673 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004674 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004676 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004677 }
4678 mH.post(() -> {
4679 if (!mVrController.onVrModeChanged(r)) {
4680 return;
4681 }
4682 synchronized (mGlobalLock) {
4683 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4684 mWindowManager.disableNonVrUi(disableNonVrUi);
4685 if (disableNonVrUi) {
4686 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4687 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004688 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004689 }
4690 }
4691 });
4692 }
4693
Wale Ogunwale53783742018-09-16 10:21:51 -07004694 @Override
4695 public int getPackageScreenCompatMode(String packageName) {
4696 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4697 synchronized (mGlobalLock) {
4698 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4699 }
4700 }
4701
4702 @Override
4703 public void setPackageScreenCompatMode(String packageName, int mode) {
4704 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4705 "setPackageScreenCompatMode");
4706 synchronized (mGlobalLock) {
4707 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4708 }
4709 }
4710
4711 @Override
4712 public boolean getPackageAskScreenCompat(String packageName) {
4713 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4714 synchronized (mGlobalLock) {
4715 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4716 }
4717 }
4718
4719 @Override
4720 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4721 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4722 "setPackageAskScreenCompat");
4723 synchronized (mGlobalLock) {
4724 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4725 }
4726 }
4727
Wale Ogunwale64258362018-10-16 15:13:37 -07004728 public static String relaunchReasonToString(int relaunchReason) {
4729 switch (relaunchReason) {
4730 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4731 return "window_resize";
4732 case RELAUNCH_REASON_FREE_RESIZE:
4733 return "free_resize";
4734 default:
4735 return null;
4736 }
4737 }
4738
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004739 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004740 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 }
4742
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 /** Pokes the task persister. */
4744 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4745 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4746 }
4747
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 boolean isKeyguardLocked() {
4749 return mKeyguardController.isKeyguardLocked();
4750 }
4751
Garfield Tan01548632018-11-27 10:15:48 -08004752 /**
4753 * Clears launch params for the given package.
4754 * @param packageNames the names of the packages of which the launch params are to be cleared
4755 */
4756 @Override
4757 public void clearLaunchParamsForPackages(List<String> packageNames) {
4758 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4759 "clearLaunchParamsForPackages");
4760 synchronized (mGlobalLock) {
4761 for (int i = 0; i < packageNames.size(); ++i) {
4762 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4763 }
4764 }
4765 }
4766
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004767 /**
4768 * Makes the display with the given id a single task instance display. I.e the display can only
4769 * contain one task.
4770 */
4771 @Override
4772 public void setDisplayToSingleTaskInstance(int displayId) {
4773 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4774 "setDisplayToSingleTaskInstance");
4775 final long origId = Binder.clearCallingIdentity();
4776 try {
4777 final ActivityDisplay display =
4778 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4779 if (display != null) {
4780 display.setDisplayToSingleTaskInstance();
4781 }
4782 } finally {
4783 Binder.restoreCallingIdentity(origId);
4784 }
4785 }
4786
Wale Ogunwale31913b52018-10-13 08:29:31 -07004787 void dumpLastANRLocked(PrintWriter pw) {
4788 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4789 if (mLastANRState == null) {
4790 pw.println(" <no ANR has occurred since boot>");
4791 } else {
4792 pw.println(mLastANRState);
4793 }
4794 }
4795
4796 void dumpLastANRTracesLocked(PrintWriter pw) {
4797 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4798
4799 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4800 if (ArrayUtils.isEmpty(files)) {
4801 pw.println(" <no ANR has occurred since boot>");
4802 return;
4803 }
4804 // Find the latest file.
4805 File latest = null;
4806 for (File f : files) {
4807 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4808 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004809 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004810 }
4811 pw.print("File: ");
4812 pw.print(latest.getName());
4813 pw.println();
4814 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4815 String line;
4816 while ((line = in.readLine()) != null) {
4817 pw.println(line);
4818 }
4819 } catch (IOException e) {
4820 pw.print("Unable to read: ");
4821 pw.print(e);
4822 pw.println();
4823 }
4824 }
4825
4826 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4827 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4828 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4829 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4830 }
4831
4832 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4833 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4834 pw.println(header);
4835
Wale Ogunwaled32da472018-11-16 07:19:28 -08004836 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004837 dumpPackage);
4838 boolean needSep = printedAnything;
4839
4840 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004841 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004842 " ResumedActivity: ");
4843 if (printed) {
4844 printedAnything = true;
4845 needSep = false;
4846 }
4847
4848 if (dumpPackage == null) {
4849 if (needSep) {
4850 pw.println();
4851 }
4852 printedAnything = true;
4853 mStackSupervisor.dump(pw, " ");
4854 }
4855
4856 if (!printedAnything) {
4857 pw.println(" (nothing)");
4858 }
4859 }
4860
4861 void dumpActivityContainersLocked(PrintWriter pw) {
4862 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004863 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004864 pw.println(" ");
4865 }
4866
4867 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4868 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4869 getActivityStartController().dump(pw, "", dumpPackage);
4870 }
4871
4872 /**
4873 * There are three things that cmd can be:
4874 * - a flattened component name that matches an existing activity
4875 * - the cmd arg isn't the flattened component name of an existing activity:
4876 * dump all activity whose component contains the cmd as a substring
4877 * - A hex number of the ActivityRecord object instance.
4878 *
4879 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4880 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4881 */
4882 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4883 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4884 ArrayList<ActivityRecord> activities;
4885
4886 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004887 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004888 dumpFocusedStackOnly);
4889 }
4890
4891 if (activities.size() <= 0) {
4892 return false;
4893 }
4894
4895 String[] newArgs = new String[args.length - opti];
4896 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4897
4898 TaskRecord lastTask = null;
4899 boolean needSep = false;
4900 for (int i = activities.size() - 1; i >= 0; i--) {
4901 ActivityRecord r = activities.get(i);
4902 if (needSep) {
4903 pw.println();
4904 }
4905 needSep = true;
4906 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004907 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004908 if (lastTask != task) {
4909 lastTask = task;
4910 pw.print("TASK "); pw.print(lastTask.affinity);
4911 pw.print(" id="); pw.print(lastTask.taskId);
4912 pw.print(" userId="); pw.println(lastTask.userId);
4913 if (dumpAll) {
4914 lastTask.dump(pw, " ");
4915 }
4916 }
4917 }
4918 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4919 }
4920 return true;
4921 }
4922
4923 /**
4924 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4925 * there is a thread associated with the activity.
4926 */
4927 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4928 final ActivityRecord r, String[] args, boolean dumpAll) {
4929 String innerPrefix = prefix + " ";
4930 synchronized (mGlobalLock) {
4931 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4932 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4933 pw.print(" pid=");
4934 if (r.hasProcess()) pw.println(r.app.getPid());
4935 else pw.println("(not running)");
4936 if (dumpAll) {
4937 r.dump(pw, innerPrefix);
4938 }
4939 }
4940 if (r.attachedToProcess()) {
4941 // flush anything that is already in the PrintWriter since the thread is going
4942 // to write to the file descriptor directly
4943 pw.flush();
4944 try {
4945 TransferPipe tp = new TransferPipe();
4946 try {
4947 r.app.getThread().dumpActivity(tp.getWriteFd(),
4948 r.appToken, innerPrefix, args);
4949 tp.go(fd);
4950 } finally {
4951 tp.kill();
4952 }
4953 } catch (IOException e) {
4954 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4955 } catch (RemoteException e) {
4956 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4957 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004958 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004959 }
4960
sanryhuang498e77e2018-12-06 14:57:01 +08004961 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4962 boolean testPssMode) {
4963 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4964 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4965 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004966 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004967 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4968 st.toString());
4969 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004970 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4971 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4972 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004973 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4974 testPssMode);
4975 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004976 }
4977
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004978 int getCurrentUserId() {
4979 return mAmInternal.getCurrentUserId();
4980 }
4981
4982 private void enforceNotIsolatedCaller(String caller) {
4983 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4984 throw new SecurityException("Isolated process not allowed to call " + caller);
4985 }
4986 }
4987
Wale Ogunwalef6733932018-06-27 05:14:34 -07004988 public Configuration getConfiguration() {
4989 Configuration ci;
4990 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004991 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004992 ci.userSetLocale = false;
4993 }
4994 return ci;
4995 }
4996
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004997 /**
4998 * Current global configuration information. Contains general settings for the entire system,
4999 * also corresponds to the merged configuration of the default display.
5000 */
5001 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005002 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005003 }
5004
5005 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5006 boolean initLocale) {
5007 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5008 }
5009
5010 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5011 boolean initLocale, boolean deferResume) {
5012 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5013 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5014 UserHandle.USER_NULL, deferResume);
5015 }
5016
Wale Ogunwale59507092018-10-29 09:00:30 -07005017 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005018 final long origId = Binder.clearCallingIdentity();
5019 try {
5020 synchronized (mGlobalLock) {
5021 updateConfigurationLocked(values, null, false, true, userId,
5022 false /* deferResume */);
5023 }
5024 } finally {
5025 Binder.restoreCallingIdentity(origId);
5026 }
5027 }
5028
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005029 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5030 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5031 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5032 deferResume, null /* result */);
5033 }
5034
5035 /**
5036 * Do either or both things: (1) change the current configuration, and (2)
5037 * make sure the given activity is running with the (now) current
5038 * configuration. Returns true if the activity has been left running, or
5039 * false if <var>starting</var> is being destroyed to match the new
5040 * configuration.
5041 *
5042 * @param userId is only used when persistent parameter is set to true to persist configuration
5043 * for that particular user
5044 */
5045 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5046 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5047 ActivityTaskManagerService.UpdateConfigurationResult result) {
5048 int changes = 0;
5049 boolean kept = true;
5050
5051 if (mWindowManager != null) {
5052 mWindowManager.deferSurfaceLayout();
5053 }
5054 try {
5055 if (values != null) {
5056 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5057 deferResume);
5058 }
5059
5060 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5061 } finally {
5062 if (mWindowManager != null) {
5063 mWindowManager.continueSurfaceLayout();
5064 }
5065 }
5066
5067 if (result != null) {
5068 result.changes = changes;
5069 result.activityRelaunched = !kept;
5070 }
5071 return kept;
5072 }
5073
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005074 /** Update default (global) configuration and notify listeners about changes. */
5075 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5076 boolean persistent, int userId, boolean deferResume) {
5077 mTempConfig.setTo(getGlobalConfiguration());
5078 final int changes = mTempConfig.updateFrom(values);
5079 if (changes == 0) {
5080 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5081 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5082 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5083 // (even if there are no actual changes) to unfreeze the window.
5084 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5085 return 0;
5086 }
5087
5088 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5089 "Updating global configuration to: " + values);
5090
5091 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5092 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5093 values.colorMode,
5094 values.densityDpi,
5095 values.fontScale,
5096 values.hardKeyboardHidden,
5097 values.keyboard,
5098 values.keyboardHidden,
5099 values.mcc,
5100 values.mnc,
5101 values.navigation,
5102 values.navigationHidden,
5103 values.orientation,
5104 values.screenHeightDp,
5105 values.screenLayout,
5106 values.screenWidthDp,
5107 values.smallestScreenWidthDp,
5108 values.touchscreen,
5109 values.uiMode);
5110
5111
5112 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5113 final LocaleList locales = values.getLocales();
5114 int bestLocaleIndex = 0;
5115 if (locales.size() > 1) {
5116 if (mSupportedSystemLocales == null) {
5117 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5118 }
5119 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5120 }
5121 SystemProperties.set("persist.sys.locale",
5122 locales.get(bestLocaleIndex).toLanguageTag());
5123 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005124
5125 final Message m = PooledLambda.obtainMessage(
5126 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5127 locales.get(bestLocaleIndex));
5128 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 }
5130
Yunfan Chen75157d72018-07-27 14:47:21 +09005131 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132
5133 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005134 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005135
5136 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5137 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005138 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139
5140 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005141 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142
5143 AttributeCache ac = AttributeCache.instance();
5144 if (ac != null) {
5145 ac.updateConfiguration(mTempConfig);
5146 }
5147
5148 // Make sure all resources in our process are updated right now, so that anyone who is going
5149 // to retrieve resource values after we return will be sure to get the new ones. This is
5150 // especially important during boot, where the first config change needs to guarantee all
5151 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005152 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005153
5154 // We need another copy of global config because we're scheduling some calls instead of
5155 // running them in place. We need to be sure that object we send will be handled unchanged.
5156 final Configuration configCopy = new Configuration(mTempConfig);
5157 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005158 final Message msg = PooledLambda.obtainMessage(
5159 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5160 this, userId, configCopy);
5161 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005162 }
5163
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005164 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005165 final int pid = mPidMap.keyAt(i);
5166 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005167 if (DEBUG_CONFIGURATION) {
5168 Slog.v(TAG_CONFIGURATION, "Update process config of "
5169 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005170 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005171 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 }
5173
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005174 final Message msg = PooledLambda.obtainMessage(
5175 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5176 mAmInternal, changes, initLocale);
5177 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178
5179 // Override configuration of the default display duplicates global config, so we need to
5180 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005181 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182 DEFAULT_DISPLAY);
5183
5184 return changes;
5185 }
5186
5187 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5188 boolean deferResume, int displayId) {
5189 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5190 displayId, null /* result */);
5191 }
5192
5193 /**
5194 * Updates override configuration specific for the selected display. If no config is provided,
5195 * new one will be computed in WM based on current display info.
5196 */
5197 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5198 ActivityRecord starting, boolean deferResume, int displayId,
5199 ActivityTaskManagerService.UpdateConfigurationResult result) {
5200 int changes = 0;
5201 boolean kept = true;
5202
5203 if (mWindowManager != null) {
5204 mWindowManager.deferSurfaceLayout();
5205 }
5206 try {
5207 if (values != null) {
5208 if (displayId == DEFAULT_DISPLAY) {
5209 // Override configuration of the default display duplicates global config, so
5210 // we're calling global config update instead for default display. It will also
5211 // apply the correct override config.
5212 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5213 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5214 } else {
5215 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5216 }
5217 }
5218
5219 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5220 } finally {
5221 if (mWindowManager != null) {
5222 mWindowManager.continueSurfaceLayout();
5223 }
5224 }
5225
5226 if (result != null) {
5227 result.changes = changes;
5228 result.activityRelaunched = !kept;
5229 }
5230 return kept;
5231 }
5232
5233 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5234 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005235 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 final int changes = mTempConfig.updateFrom(values);
5237 if (changes != 0) {
5238 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5239 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005240 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241
5242 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5243 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005244 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245
Wale Ogunwale5c918702018-10-18 11:06:33 -07005246 // Post message to start process to avoid possible deadlock of calling into AMS with
5247 // the ATMS lock held.
5248 final Message msg = PooledLambda.obtainMessage(
5249 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005250 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005251 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 }
5253 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005254 return changes;
5255 }
5256
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 private void updateEventDispatchingLocked(boolean booted) {
5258 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5259 }
5260
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005261 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5262 final ContentResolver resolver = mContext.getContentResolver();
5263 Settings.System.putConfigurationForUser(resolver, config, userId);
5264 }
5265
5266 private void sendLocaleToMountDaemonMsg(Locale l) {
5267 try {
5268 IBinder service = ServiceManager.getService("mount");
5269 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5270 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5271 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5272 } catch (RemoteException e) {
5273 Log.e(TAG, "Error storing locale for decryption UI", e);
5274 }
5275 }
5276
Alison Cichowlas3e340502018-08-07 17:15:01 -04005277 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5278 mStartActivitySources.remove(permissionToken);
5279 mExpiredStartAsCallerTokens.add(permissionToken);
5280 }
5281
5282 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5283 mExpiredStartAsCallerTokens.remove(permissionToken);
5284 }
5285
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005286 boolean isActivityStartsLoggingEnabled() {
5287 return mAmInternal.isActivityStartsLoggingEnabled();
5288 }
5289
Michal Karpinski8596ded2018-11-14 14:43:48 +00005290 boolean isBackgroundActivityStartsEnabled() {
5291 return mAmInternal.isBackgroundActivityStartsEnabled();
5292 }
5293
Michal Karpinski666631b2019-02-26 16:59:11 +00005294 boolean isPackageNameWhitelistedForBgActivityStarts(String packageName) {
5295 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5296 }
5297
Wale Ogunwalef6733932018-06-27 05:14:34 -07005298 void enableScreenAfterBoot(boolean booted) {
5299 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5300 SystemClock.uptimeMillis());
5301 mWindowManager.enableScreenAfterBoot();
5302
5303 synchronized (mGlobalLock) {
5304 updateEventDispatchingLocked(booted);
5305 }
5306 }
5307
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005308 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5309 if (r == null || !r.hasProcess()) {
5310 return KEY_DISPATCHING_TIMEOUT_MS;
5311 }
5312 return getInputDispatchingTimeoutLocked(r.app);
5313 }
5314
5315 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005316 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005317 }
5318
Wale Ogunwalef6733932018-06-27 05:14:34 -07005319 /**
5320 * Decide based on the configuration whether we should show the ANR,
5321 * crash, etc dialogs. The idea is that if there is no affordance to
5322 * press the on-screen buttons, or the user experience would be more
5323 * greatly impacted than the crash itself, we shouldn't show the dialog.
5324 *
5325 * A thought: SystemUI might also want to get told about this, the Power
5326 * dialog / global actions also might want different behaviors.
5327 */
5328 private void updateShouldShowDialogsLocked(Configuration config) {
5329 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5330 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5331 && config.navigation == Configuration.NAVIGATION_NONAV);
5332 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5333 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5334 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5335 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5336 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5337 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5338 HIDE_ERROR_DIALOGS, 0) != 0;
5339 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5340 }
5341
5342 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5343 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5344 FONT_SCALE, 1.0f, userId);
5345
5346 synchronized (this) {
5347 if (getGlobalConfiguration().fontScale == scaleFactor) {
5348 return;
5349 }
5350
5351 final Configuration configuration
5352 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5353 configuration.fontScale = scaleFactor;
5354 updatePersistentConfiguration(configuration, userId);
5355 }
5356 }
5357
5358 // Actually is sleeping or shutting down or whatever else in the future
5359 // is an inactive state.
5360 boolean isSleepingOrShuttingDownLocked() {
5361 return isSleepingLocked() || mShuttingDown;
5362 }
5363
5364 boolean isSleepingLocked() {
5365 return mSleeping;
5366 }
5367
Riddle Hsu16567132018-08-16 21:37:47 +08005368 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005369 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005370 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005371 if (task.isActivityTypeStandard()) {
5372 if (mCurAppTimeTracker != r.appTimeTracker) {
5373 // We are switching app tracking. Complete the current one.
5374 if (mCurAppTimeTracker != null) {
5375 mCurAppTimeTracker.stop();
5376 mH.obtainMessage(
5377 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005378 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005379 mCurAppTimeTracker = null;
5380 }
5381 if (r.appTimeTracker != null) {
5382 mCurAppTimeTracker = r.appTimeTracker;
5383 startTimeTrackingFocusedActivityLocked();
5384 }
5385 } else {
5386 startTimeTrackingFocusedActivityLocked();
5387 }
5388 } else {
5389 r.appTimeTracker = null;
5390 }
5391 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5392 // TODO: Probably not, because we don't want to resume voice on switching
5393 // back to this activity
5394 if (task.voiceInteractor != null) {
5395 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5396 } else {
5397 finishRunningVoiceLocked();
5398
5399 if (mLastResumedActivity != null) {
5400 final IVoiceInteractionSession session;
5401
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005402 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005403 if (lastResumedActivityTask != null
5404 && lastResumedActivityTask.voiceSession != null) {
5405 session = lastResumedActivityTask.voiceSession;
5406 } else {
5407 session = mLastResumedActivity.voiceSession;
5408 }
5409
5410 if (session != null) {
5411 // We had been in a voice interaction session, but now focused has
5412 // move to something different. Just finish the session, we can't
5413 // return to it and retain the proper state and synchronization with
5414 // the voice interaction service.
5415 finishVoiceTask(session);
5416 }
5417 }
5418 }
5419
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005420 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5421 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 }
5423 updateResumedAppTrace(r);
5424 mLastResumedActivity = r;
5425
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005426 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005427
5428 applyUpdateLockStateLocked(r);
5429 applyUpdateVrModeLocked(r);
5430
5431 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005432 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 r == null ? "NULL" : r.shortComponentName,
5434 reason);
5435 }
5436
5437 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5438 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005439 final ActivityTaskManagerInternal.SleepToken token =
5440 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005441 updateSleepIfNeededLocked();
5442 return token;
5443 }
5444 }
5445
5446 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005447 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 final boolean wasSleeping = mSleeping;
5449 boolean updateOomAdj = false;
5450
5451 if (!shouldSleep) {
5452 // If wasSleeping is true, we need to wake up activity manager state from when
5453 // we started sleeping. In either case, we need to apply the sleep tokens, which
5454 // will wake up stacks or put them to sleep as appropriate.
5455 if (wasSleeping) {
5456 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005457 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5458 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 startTimeTrackingFocusedActivityLocked();
5460 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005461 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5463 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005464 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 if (wasSleeping) {
5466 updateOomAdj = true;
5467 }
5468 } else if (!mSleeping && shouldSleep) {
5469 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005470 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5471 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 if (mCurAppTimeTracker != null) {
5473 mCurAppTimeTracker.stop();
5474 }
5475 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005476 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005477 mStackSupervisor.goingToSleepLocked();
5478 updateResumedAppTrace(null /* resumed */);
5479 updateOomAdj = true;
5480 }
5481 if (updateOomAdj) {
5482 mH.post(mAmInternal::updateOomAdj);
5483 }
5484 }
5485
5486 void updateOomAdj() {
5487 mH.post(mAmInternal::updateOomAdj);
5488 }
5489
Wale Ogunwale53783742018-09-16 10:21:51 -07005490 void updateCpuStats() {
5491 mH.post(mAmInternal::updateCpuStats);
5492 }
5493
Hui Yu03d12402018-12-06 18:00:37 -08005494 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5495 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005496 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5497 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005498 mH.sendMessage(m);
5499 }
5500
Hui Yu03d12402018-12-06 18:00:37 -08005501 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005502 ComponentName taskRoot = null;
5503 final TaskRecord task = activity.getTaskRecord();
5504 if (task != null) {
5505 final ActivityRecord rootActivity = task.getRootActivity();
5506 if (rootActivity != null) {
5507 taskRoot = rootActivity.mActivityComponent;
5508 }
5509 }
5510
Hui Yu03d12402018-12-06 18:00:37 -08005511 final Message m = PooledLambda.obtainMessage(
5512 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005513 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005514 mH.sendMessage(m);
5515 }
5516
Wale Ogunwale53783742018-09-16 10:21:51 -07005517 void setBooting(boolean booting) {
5518 mAmInternal.setBooting(booting);
5519 }
5520
5521 boolean isBooting() {
5522 return mAmInternal.isBooting();
5523 }
5524
5525 void setBooted(boolean booted) {
5526 mAmInternal.setBooted(booted);
5527 }
5528
5529 boolean isBooted() {
5530 return mAmInternal.isBooted();
5531 }
5532
5533 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5534 mH.post(() -> {
5535 if (finishBooting) {
5536 mAmInternal.finishBooting();
5537 }
5538 if (enableScreen) {
5539 mInternal.enableScreenAfterBoot(isBooted());
5540 }
5541 });
5542 }
5543
5544 void setHeavyWeightProcess(ActivityRecord root) {
5545 mHeavyWeightProcess = root.app;
5546 final Message m = PooledLambda.obtainMessage(
5547 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005548 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005549 mH.sendMessage(m);
5550 }
5551
5552 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5553 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5554 return;
5555 }
5556
5557 mHeavyWeightProcess = null;
5558 final Message m = PooledLambda.obtainMessage(
5559 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5560 proc.mUserId);
5561 mH.sendMessage(m);
5562 }
5563
5564 private void cancelHeavyWeightProcessNotification(int userId) {
5565 final INotificationManager inm = NotificationManager.getService();
5566 if (inm == null) {
5567 return;
5568 }
5569 try {
5570 inm.cancelNotificationWithTag("android", null,
5571 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5572 } catch (RuntimeException e) {
5573 Slog.w(TAG, "Error canceling notification for service", e);
5574 } catch (RemoteException e) {
5575 }
5576
5577 }
5578
5579 private void postHeavyWeightProcessNotification(
5580 WindowProcessController proc, Intent intent, int userId) {
5581 if (proc == null) {
5582 return;
5583 }
5584
5585 final INotificationManager inm = NotificationManager.getService();
5586 if (inm == null) {
5587 return;
5588 }
5589
5590 try {
5591 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5592 String text = mContext.getString(R.string.heavy_weight_notification,
5593 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5594 Notification notification =
5595 new Notification.Builder(context,
5596 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5597 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5598 .setWhen(0)
5599 .setOngoing(true)
5600 .setTicker(text)
5601 .setColor(mContext.getColor(
5602 com.android.internal.R.color.system_notification_accent_color))
5603 .setContentTitle(text)
5604 .setContentText(
5605 mContext.getText(R.string.heavy_weight_notification_detail))
5606 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5607 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5608 new UserHandle(userId)))
5609 .build();
5610 try {
5611 inm.enqueueNotificationWithTag("android", "android", null,
5612 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5613 } catch (RuntimeException e) {
5614 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5615 } catch (RemoteException e) {
5616 }
5617 } catch (PackageManager.NameNotFoundException e) {
5618 Slog.w(TAG, "Unable to create context for heavy notification", e);
5619 }
5620
5621 }
5622
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005623 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5624 IBinder token, String resultWho, int requestCode, Intent[] intents,
5625 String[] resolvedTypes, int flags, Bundle bOptions) {
5626
5627 ActivityRecord activity = null;
5628 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5629 activity = ActivityRecord.isInStackLocked(token);
5630 if (activity == null) {
5631 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5632 return null;
5633 }
5634 if (activity.finishing) {
5635 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5636 return null;
5637 }
5638 }
5639
5640 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5641 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5642 bOptions);
5643 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5644 if (noCreate) {
5645 return rec;
5646 }
5647 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5648 if (activity.pendingResults == null) {
5649 activity.pendingResults = new HashSet<>();
5650 }
5651 activity.pendingResults.add(rec.ref);
5652 }
5653 return rec;
5654 }
5655
Andrii Kulian52d255c2018-07-13 11:32:19 -07005656 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005657 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005658 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5660 mCurAppTimeTracker.start(resumedActivity.packageName);
5661 }
5662 }
5663
5664 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5665 if (mTracedResumedActivity != null) {
5666 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5667 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5668 }
5669 if (resumed != null) {
5670 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5671 constructResumedTraceName(resumed.packageName), 0);
5672 }
5673 mTracedResumedActivity = resumed;
5674 }
5675
5676 private String constructResumedTraceName(String packageName) {
5677 return "focused app: " + packageName;
5678 }
5679
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005680 /** Applies latest configuration and/or visibility updates if needed. */
5681 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5682 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005683 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005684 // mainStack is null during startup.
5685 if (mainStack != null) {
5686 if (changes != 0 && starting == null) {
5687 // If the configuration changed, and the caller is not already
5688 // in the process of starting an activity, then find the top
5689 // activity to check if its configuration needs to change.
5690 starting = mainStack.topRunningActivityLocked();
5691 }
5692
5693 if (starting != null) {
5694 kept = starting.ensureActivityConfiguration(changes,
5695 false /* preserveWindow */);
5696 // And we need to make sure at this point that all other activities
5697 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005698 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005699 !PRESERVE_WINDOWS);
5700 }
5701 }
5702
5703 return kept;
5704 }
5705
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005706 void scheduleAppGcsLocked() {
5707 mH.post(() -> mAmInternal.scheduleAppGcs());
5708 }
5709
Wale Ogunwale53783742018-09-16 10:21:51 -07005710 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5711 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5712 }
5713
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005714 /**
5715 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5716 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5717 * on demand.
5718 */
5719 IPackageManager getPackageManager() {
5720 return AppGlobals.getPackageManager();
5721 }
5722
5723 PackageManagerInternal getPackageManagerInternalLocked() {
5724 if (mPmInternal == null) {
5725 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5726 }
5727 return mPmInternal;
5728 }
5729
Wale Ogunwale008163e2018-07-23 23:11:08 -07005730 AppWarnings getAppWarningsLocked() {
5731 return mAppWarnings;
5732 }
5733
Wale Ogunwale214f3482018-10-04 11:00:47 -07005734 Intent getHomeIntent() {
5735 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5736 intent.setComponent(mTopComponent);
5737 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5738 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5739 intent.addCategory(Intent.CATEGORY_HOME);
5740 }
5741 return intent;
5742 }
5743
Chilun2ef71f72018-11-16 17:57:15 +08005744 /**
5745 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5746 * activities.
5747 *
5748 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5749 * component defined in config_secondaryHomeComponent.
5750 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5751 */
5752 Intent getSecondaryHomeIntent(String preferredPackage) {
5753 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5754 if (preferredPackage == null) {
5755 // Using the component stored in config if no package name.
5756 final String secondaryHomeComponent = mContext.getResources().getString(
5757 com.android.internal.R.string.config_secondaryHomeComponent);
5758 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5759 } else {
5760 intent.setPackage(preferredPackage);
5761 }
5762 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5763 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5764 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5765 }
5766 return intent;
5767 }
5768
Wale Ogunwale214f3482018-10-04 11:00:47 -07005769 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5770 if (info == null) return null;
5771 ApplicationInfo newInfo = new ApplicationInfo(info);
5772 newInfo.initForUser(userId);
5773 return newInfo;
5774 }
5775
Wale Ogunwale9c103022018-10-18 07:44:54 -07005776 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005777 if (uid == SYSTEM_UID) {
5778 // The system gets to run in any process. If there are multiple processes with the same
5779 // uid, just pick the first (this should never happen).
5780 final SparseArray<WindowProcessController> procs =
5781 mProcessNames.getMap().get(processName);
5782 if (procs == null) return null;
5783 final int procCount = procs.size();
5784 for (int i = 0; i < procCount; i++) {
5785 final int procUid = procs.keyAt(i);
5786 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5787 // Don't use an app process or different user process for system component.
5788 continue;
5789 }
5790 return procs.valueAt(i);
5791 }
5792 }
5793
5794 return mProcessNames.get(processName, uid);
5795 }
5796
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005797 WindowProcessController getProcessController(IApplicationThread thread) {
5798 if (thread == null) {
5799 return null;
5800 }
5801
5802 final IBinder threadBinder = thread.asBinder();
5803 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5804 for (int i = pmap.size()-1; i >= 0; i--) {
5805 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5806 for (int j = procs.size() - 1; j >= 0; j--) {
5807 final WindowProcessController proc = procs.valueAt(j);
5808 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5809 return proc;
5810 }
5811 }
5812 }
5813
5814 return null;
5815 }
5816
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005817 WindowProcessController getProcessController(int pid, int uid) {
Yunfan Chen8546b212019-04-01 15:34:44 +09005818 final WindowProcessController proc = mPidMap.get(pid);
5819 if (proc == null) return null;
5820 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5821 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005822 }
5823 return null;
5824 }
5825
Riddle Hsua0536432019-02-16 00:38:59 +08005826 int getUidState(int uid) {
5827 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005828 }
5829
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005830 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005831 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005832 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5833 }
5834
Michal Karpinski4026cae2019-02-12 11:51:47 +00005835 boolean isDeviceOwner(String packageName) {
5836 if (packageName == null) {
5837 return false;
5838 }
5839 return packageName.equals(mDeviceOwnerPackageName);
5840 }
5841
5842 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5843 mDeviceOwnerPackageName = deviceOwnerPkg;
5844 }
5845
Wale Ogunwale9de19442018-10-18 19:05:03 -07005846 /**
5847 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5848 * the whitelist
5849 */
5850 String getPendingTempWhitelistTagForUidLocked(int uid) {
5851 return mPendingTempWhitelist.get(uid);
5852 }
5853
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005854 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5855 if (true || Build.IS_USER) {
5856 return;
5857 }
5858
5859 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5860 StrictMode.allowThreadDiskWrites();
5861 try {
5862 File tracesDir = new File("/data/anr");
5863 File tracesFile = null;
5864 try {
5865 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5866
5867 StringBuilder sb = new StringBuilder();
5868 Time tobj = new Time();
5869 tobj.set(System.currentTimeMillis());
5870 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5871 sb.append(": ");
5872 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5873 sb.append(" since ");
5874 sb.append(msg);
5875 FileOutputStream fos = new FileOutputStream(tracesFile);
5876 fos.write(sb.toString().getBytes());
5877 if (app == null) {
5878 fos.write("\n*** No application process!".getBytes());
5879 }
5880 fos.close();
5881 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5882 } catch (IOException e) {
5883 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5884 return;
5885 }
5886
5887 if (app != null && app.getPid() > 0) {
5888 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5889 firstPids.add(app.getPid());
5890 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5891 }
5892
5893 File lastTracesFile = null;
5894 File curTracesFile = null;
5895 for (int i=9; i>=0; i--) {
5896 String name = String.format(Locale.US, "slow%02d.txt", i);
5897 curTracesFile = new File(tracesDir, name);
5898 if (curTracesFile.exists()) {
5899 if (lastTracesFile != null) {
5900 curTracesFile.renameTo(lastTracesFile);
5901 } else {
5902 curTracesFile.delete();
5903 }
5904 }
5905 lastTracesFile = curTracesFile;
5906 }
5907 tracesFile.renameTo(curTracesFile);
5908 } finally {
5909 StrictMode.setThreadPolicy(oldPolicy);
5910 }
5911 }
5912
Michal Karpinskida34cd42019-04-02 19:46:52 +01005913 boolean isAssociatedCompanionApp(int userId, int uid) {
5914 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5915 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005916 return false;
5917 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005918 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005919 }
5920
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005921 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005922 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005923
5924
Wale Ogunwale98875612018-10-12 07:53:02 -07005925 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5926 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005927
Riddle Hsud93a6c42018-11-29 21:50:06 +08005928 H(Looper looper) {
5929 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005930 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005931
5932 @Override
5933 public void handleMessage(Message msg) {
5934 switch (msg.what) {
5935 case REPORT_TIME_TRACKER_MSG: {
5936 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5937 tracker.deliverResult(mContext);
5938 } break;
5939 }
5940 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005941 }
5942
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005943 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005944 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005945
5946 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005947 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005949
5950 @Override
5951 public void handleMessage(Message msg) {
5952 switch (msg.what) {
5953 case DISMISS_DIALOG_UI_MSG: {
5954 final Dialog d = (Dialog) msg.obj;
5955 d.dismiss();
5956 break;
5957 }
5958 }
5959 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005960 }
5961
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005962 final class LocalService extends ActivityTaskManagerInternal {
5963 @Override
5964 public SleepToken acquireSleepToken(String tag, int displayId) {
5965 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005966 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005967 }
5968
5969 @Override
5970 public ComponentName getHomeActivityForUser(int userId) {
5971 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005972 final ActivityRecord homeActivity =
5973 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005974 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005975 }
5976 }
5977
5978 @Override
5979 public void onLocalVoiceInteractionStarted(IBinder activity,
5980 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5981 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005982 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005983 }
5984 }
5985
5986 @Override
5987 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5988 synchronized (mGlobalLock) {
5989 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5990 reasons, timestamp);
5991 }
5992 }
5993
5994 @Override
5995 public void notifyAppTransitionFinished() {
5996 synchronized (mGlobalLock) {
5997 mStackSupervisor.notifyAppTransitionDone();
5998 }
5999 }
6000
6001 @Override
6002 public void notifyAppTransitionCancelled() {
6003 synchronized (mGlobalLock) {
6004 mStackSupervisor.notifyAppTransitionDone();
6005 }
6006 }
6007
6008 @Override
6009 public List<IBinder> getTopVisibleActivities() {
6010 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006011 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006012 }
6013 }
6014
6015 @Override
6016 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6017 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006018 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006019 }
6020 }
6021
6022 @Override
6023 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6024 Bundle bOptions) {
6025 Preconditions.checkNotNull(intents, "intents");
6026 final String[] resolvedTypes = new String[intents.length];
6027
6028 // UID of the package on user userId.
6029 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6030 // packageUid may not be initialized.
6031 int packageUid = 0;
6032 final long ident = Binder.clearCallingIdentity();
6033
6034 try {
6035 for (int i = 0; i < intents.length; i++) {
6036 resolvedTypes[i] =
6037 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6038 }
6039
6040 packageUid = AppGlobals.getPackageManager().getPackageUid(
6041 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6042 } catch (RemoteException e) {
6043 // Shouldn't happen.
6044 } finally {
6045 Binder.restoreCallingIdentity(ident);
6046 }
6047
Riddle Hsu591bf612019-02-14 17:55:31 +08006048 return getActivityStartController().startActivitiesInPackage(
6049 packageUid, packageName,
6050 intents, resolvedTypes, null /* resultTo */,
6051 SafeActivityOptions.fromBundle(bOptions), userId,
6052 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6053 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006054 }
6055
6056 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006057 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6058 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6059 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6060 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006061 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006062 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006063 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6064 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6065 userId, validateIncomingUser, originatingPendingIntent,
6066 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006067 }
6068 }
6069
6070 @Override
6071 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6072 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6073 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6074 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006075 PendingIntentRecord originatingPendingIntent,
6076 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006077 synchronized (mGlobalLock) {
6078 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6079 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6080 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006081 validateIncomingUser, originatingPendingIntent,
6082 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006083 }
6084 }
6085
6086 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6088 Intent intent, Bundle options, int userId) {
6089 return ActivityTaskManagerService.this.startActivityAsUser(
6090 caller, callerPacakge, intent,
6091 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6092 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6093 false /*validateIncomingUser*/);
6094 }
6095
6096 @Override
lumark588a3e82018-07-20 18:53:54 +08006097 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 synchronized (mGlobalLock) {
6099
6100 // We might change the visibilities here, so prepare an empty app transition which
6101 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006102 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006103 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006104 if (activityDisplay == null) {
6105 return;
6106 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006107 final DisplayContent dc = activityDisplay.mDisplayContent;
6108 final boolean wasTransitionSet =
6109 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006111 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006112 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006113 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006114
6115 // If there was a transition set already we don't want to interfere with it as we
6116 // might be starting it too early.
6117 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006118 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 }
6120 }
6121 if (callback != null) {
6122 callback.run();
6123 }
6124 }
6125
6126 @Override
6127 public void notifyKeyguardTrustedChanged() {
6128 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006129 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006130 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 }
6132 }
6133 }
6134
6135 /**
6136 * Called after virtual display Id is updated by
6137 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6138 * {@param vrVr2dDisplayId}.
6139 */
6140 @Override
6141 public void setVr2dDisplayId(int vr2dDisplayId) {
6142 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6143 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006144 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 }
6146 }
6147
6148 @Override
6149 public void setFocusedActivity(IBinder token) {
6150 synchronized (mGlobalLock) {
6151 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6152 if (r == null) {
6153 throw new IllegalArgumentException(
6154 "setFocusedActivity: No activity record matching token=" + token);
6155 }
Louis Chang19443452018-10-09 12:10:21 +08006156 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006157 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006158 }
6159 }
6160 }
6161
6162 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006163 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006164 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006165 }
6166
6167 @Override
6168 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006169 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170 }
6171
6172 @Override
6173 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006174 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176
6177 @Override
6178 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6179 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6180 }
6181
6182 @Override
6183 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006184 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006185 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006186
6187 @Override
6188 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6189 synchronized (mGlobalLock) {
6190 mActiveVoiceInteractionServiceComponent = component;
6191 }
6192 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006193
6194 @Override
6195 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6196 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6197 return;
6198 }
6199 synchronized (mGlobalLock) {
6200 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6201 if (types == null) {
6202 if (uid < 0) {
6203 return;
6204 }
6205 types = new ArrayMap<>();
6206 mAllowAppSwitchUids.put(userId, types);
6207 }
6208 if (uid < 0) {
6209 types.remove(type);
6210 } else {
6211 types.put(type, uid);
6212 }
6213 }
6214 }
6215
6216 @Override
6217 public void onUserStopped(int userId) {
6218 synchronized (mGlobalLock) {
6219 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6220 mAllowAppSwitchUids.remove(userId);
6221 }
6222 }
6223
6224 @Override
6225 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6226 synchronized (mGlobalLock) {
6227 return ActivityTaskManagerService.this.isGetTasksAllowed(
6228 caller, callingPid, callingUid);
6229 }
6230 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006231
Riddle Hsua0536432019-02-16 00:38:59 +08006232 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006233 @Override
6234 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006235 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006236 mProcessNames.put(proc.mName, proc.mUid, proc);
6237 }
6238 }
6239
Riddle Hsua0536432019-02-16 00:38:59 +08006240 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006241 @Override
6242 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006243 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006244 mProcessNames.remove(name, uid);
6245 }
6246 }
6247
Riddle Hsua0536432019-02-16 00:38:59 +08006248 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006249 @Override
6250 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006251 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 if (proc == mHomeProcess) {
6253 mHomeProcess = null;
6254 }
6255 if (proc == mPreviousProcess) {
6256 mPreviousProcess = null;
6257 }
6258 }
6259 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006260
Riddle Hsua0536432019-02-16 00:38:59 +08006261 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006262 @Override
6263 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006264 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006265 return mTopProcessState;
6266 }
6267 }
6268
Riddle Hsua0536432019-02-16 00:38:59 +08006269 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006270 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006271 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006272 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006273 return proc == mHeavyWeightProcess;
6274 }
6275 }
6276
Riddle Hsua0536432019-02-16 00:38:59 +08006277 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006278 @Override
6279 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006280 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6282 }
6283 }
6284
6285 @Override
6286 public void finishHeavyWeightApp() {
6287 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006288 if (mHeavyWeightProcess != null) {
6289 mHeavyWeightProcess.finishActivities();
6290 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006291 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6292 mHeavyWeightProcess);
6293 }
6294 }
6295
Riddle Hsua0536432019-02-16 00:38:59 +08006296 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006297 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006298 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006299 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006300 return isSleepingLocked();
6301 }
6302 }
6303
6304 @Override
6305 public boolean isShuttingDown() {
6306 synchronized (mGlobalLock) {
6307 return mShuttingDown;
6308 }
6309 }
6310
6311 @Override
6312 public boolean shuttingDown(boolean booted, int timeout) {
6313 synchronized (mGlobalLock) {
6314 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006315 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006316 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006317 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006318 return mStackSupervisor.shutdownLocked(timeout);
6319 }
6320 }
6321
6322 @Override
6323 public void enableScreenAfterBoot(boolean booted) {
6324 synchronized (mGlobalLock) {
6325 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6326 SystemClock.uptimeMillis());
6327 mWindowManager.enableScreenAfterBoot();
6328 updateEventDispatchingLocked(booted);
6329 }
6330 }
6331
6332 @Override
6333 public boolean showStrictModeViolationDialog() {
6334 synchronized (mGlobalLock) {
6335 return mShowDialogs && !mSleeping && !mShuttingDown;
6336 }
6337 }
6338
6339 @Override
6340 public void showSystemReadyErrorDialogsIfNeeded() {
6341 synchronized (mGlobalLock) {
6342 try {
6343 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6344 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6345 + " data partition or your device will be unstable.");
6346 mUiHandler.post(() -> {
6347 if (mShowDialogs) {
6348 AlertDialog d = new BaseErrorDialog(mUiContext);
6349 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6350 d.setCancelable(false);
6351 d.setTitle(mUiContext.getText(R.string.android_system_label));
6352 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6353 d.setButton(DialogInterface.BUTTON_POSITIVE,
6354 mUiContext.getText(R.string.ok),
6355 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6356 d.show();
6357 }
6358 });
6359 }
6360 } catch (RemoteException e) {
6361 }
6362
6363 if (!Build.isBuildConsistent()) {
6364 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6365 mUiHandler.post(() -> {
6366 if (mShowDialogs) {
6367 AlertDialog d = new BaseErrorDialog(mUiContext);
6368 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6369 d.setCancelable(false);
6370 d.setTitle(mUiContext.getText(R.string.android_system_label));
6371 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6372 d.setButton(DialogInterface.BUTTON_POSITIVE,
6373 mUiContext.getText(R.string.ok),
6374 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6375 d.show();
6376 }
6377 });
6378 }
6379 }
6380 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006381
6382 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006383 public void onProcessMapped(int pid, WindowProcessController proc) {
6384 synchronized (mGlobalLock) {
6385 mPidMap.put(pid, proc);
6386 }
6387 }
6388
6389 @Override
6390 public void onProcessUnMapped(int pid) {
6391 synchronized (mGlobalLock) {
6392 mPidMap.remove(pid);
6393 }
6394 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006395
6396 @Override
6397 public void onPackageDataCleared(String name) {
6398 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006399 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006400 mAppWarnings.onPackageDataCleared(name);
6401 }
6402 }
6403
6404 @Override
6405 public void onPackageUninstalled(String name) {
6406 synchronized (mGlobalLock) {
6407 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006408 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006409 }
6410 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006411
6412 @Override
6413 public void onPackageAdded(String name, boolean replacing) {
6414 synchronized (mGlobalLock) {
6415 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6416 }
6417 }
6418
6419 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006420 public void onPackageReplaced(ApplicationInfo aInfo) {
6421 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006422 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006423 }
6424 }
6425
6426 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006427 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6428 synchronized (mGlobalLock) {
6429 return compatibilityInfoForPackageLocked(ai);
6430 }
6431 }
6432
Yunfan Chen75157d72018-07-27 14:47:21 +09006433 /**
6434 * Set the corresponding display information for the process global configuration. To be
6435 * called when we need to show IME on a different display.
6436 *
6437 * @param pid The process id associated with the IME window.
6438 * @param displayId The ID of the display showing the IME.
6439 */
6440 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006441 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark5df49512019-04-02 14:56:46 +08006442 // Update display configuration for IME process only when Single-client IME window
6443 // moving to another display.
6444 if (!InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
6445
Yunfan Chen75157d72018-07-27 14:47:21 +09006446 if (pid == MY_PID || pid < 0) {
6447 if (DEBUG_CONFIGURATION) {
6448 Slog.w(TAG,
6449 "Trying to update display configuration for system/invalid process.");
6450 }
6451 return;
6452 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006453 synchronized (mGlobalLock) {
6454 final ActivityDisplay activityDisplay =
6455 mRootActivityContainer.getActivityDisplay(displayId);
6456 if (activityDisplay == null) {
6457 // Call might come when display is not yet added or has been removed.
6458 if (DEBUG_CONFIGURATION) {
6459 Slog.w(TAG, "Trying to update display configuration for non-existing "
6460 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006461 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006462 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006463 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006464 final WindowProcessController process = mPidMap.get(pid);
6465 if (process == null) {
6466 if (DEBUG_CONFIGURATION) {
6467 Slog.w(TAG, "Trying to update display configuration for invalid "
6468 + "process, pid=" + pid);
6469 }
6470 return;
6471 }
6472 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6473 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006474 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006475
6476 @Override
6477 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6478 int requestCode, int resultCode, Intent data) {
6479 synchronized (mGlobalLock) {
6480 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006481 if (r != null && r.getActivityStack() != null) {
6482 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6483 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006484 }
6485 }
6486 }
6487
6488 @Override
6489 public void clearPendingResultForActivity(IBinder activityToken,
6490 WeakReference<PendingIntentRecord> pir) {
6491 synchronized (mGlobalLock) {
6492 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6493 if (r != null && r.pendingResults != null) {
6494 r.pendingResults.remove(pir);
6495 }
6496 }
6497 }
6498
6499 @Override
6500 public IIntentSender getIntentSender(int type, String packageName,
6501 int callingUid, int userId, IBinder token, String resultWho,
6502 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6503 Bundle bOptions) {
6504 synchronized (mGlobalLock) {
6505 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6506 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6507 }
6508 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006509
6510 @Override
6511 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6512 synchronized (mGlobalLock) {
6513 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6514 if (r == null) {
6515 return null;
6516 }
6517 if (r.mServiceConnectionsHolder == null) {
6518 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6519 ActivityTaskManagerService.this, r);
6520 }
6521
6522 return r.mServiceConnectionsHolder;
6523 }
6524 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006525
6526 @Override
6527 public Intent getHomeIntent() {
6528 synchronized (mGlobalLock) {
6529 return ActivityTaskManagerService.this.getHomeIntent();
6530 }
6531 }
6532
6533 @Override
6534 public boolean startHomeActivity(int userId, String reason) {
6535 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006536 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006537 }
6538 }
6539
6540 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006541 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006542 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006543 synchronized (mGlobalLock) {
6544 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006545 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006546 }
Chilun8b1f1be2019-03-13 17:14:36 +08006547 }
6548
6549 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006550 public boolean startHomeOnAllDisplays(int userId, String reason) {
6551 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006552 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006553 }
6554 }
6555
Riddle Hsua0536432019-02-16 00:38:59 +08006556 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006557 @Override
6558 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006559 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006560 if (mFactoryTest == FACTORY_TEST_OFF) {
6561 return false;
6562 }
6563 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6564 && wpc.mName.equals(mTopComponent.getPackageName())) {
6565 return true;
6566 }
6567 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6568 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6569 }
6570 }
6571
6572 @Override
6573 public void updateTopComponentForFactoryTest() {
6574 synchronized (mGlobalLock) {
6575 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6576 return;
6577 }
6578 final ResolveInfo ri = mContext.getPackageManager()
6579 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6580 final CharSequence errorMsg;
6581 if (ri != null) {
6582 final ActivityInfo ai = ri.activityInfo;
6583 final ApplicationInfo app = ai.applicationInfo;
6584 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6585 mTopAction = Intent.ACTION_FACTORY_TEST;
6586 mTopData = null;
6587 mTopComponent = new ComponentName(app.packageName, ai.name);
6588 errorMsg = null;
6589 } else {
6590 errorMsg = mContext.getResources().getText(
6591 com.android.internal.R.string.factorytest_not_system);
6592 }
6593 } else {
6594 errorMsg = mContext.getResources().getText(
6595 com.android.internal.R.string.factorytest_no_action);
6596 }
6597 if (errorMsg == null) {
6598 return;
6599 }
6600
6601 mTopAction = null;
6602 mTopData = null;
6603 mTopComponent = null;
6604 mUiHandler.post(() -> {
6605 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6606 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006607 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006608 });
6609 }
6610 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006611
Riddle Hsua0536432019-02-16 00:38:59 +08006612 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006613 @Override
6614 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6615 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006616 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006617 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006618 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006619
6620 wpc.clearRecentTasks();
6621 wpc.clearActivities();
6622
6623 if (wpc.isInstrumenting()) {
6624 finishInstrumentationCallback.run();
6625 }
6626
Jorim Jaggid0752812018-10-16 16:07:20 +02006627 if (!restarting && hasVisibleActivities) {
6628 mWindowManager.deferSurfaceLayout();
6629 try {
6630 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6631 // If there was nothing to resume, and we are not already restarting
6632 // this process, but there is a visible activity that is hosted by the
6633 // process...then make sure all visible activities are running, taking
6634 // care of restarting this process.
6635 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6636 !PRESERVE_WINDOWS);
6637 }
6638 } finally {
6639 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006640 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006641 }
6642 }
6643 }
6644
6645 @Override
6646 public void closeSystemDialogs(String reason) {
6647 enforceNotIsolatedCaller("closeSystemDialogs");
6648
6649 final int pid = Binder.getCallingPid();
6650 final int uid = Binder.getCallingUid();
6651 final long origId = Binder.clearCallingIdentity();
6652 try {
6653 synchronized (mGlobalLock) {
6654 // Only allow this from foreground processes, so that background
6655 // applications can't abuse it to prevent system UI from being shown.
6656 if (uid >= FIRST_APPLICATION_UID) {
6657 final WindowProcessController proc = mPidMap.get(pid);
6658 if (!proc.isPerceptible()) {
6659 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6660 + " from background process " + proc);
6661 return;
6662 }
6663 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006664 mWindowManager.closeSystemDialogs(reason);
6665
Wale Ogunwaled32da472018-11-16 07:19:28 -08006666 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006667 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006668 // Call into AM outside the synchronized block.
6669 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006670 } finally {
6671 Binder.restoreCallingIdentity(origId);
6672 }
6673 }
6674
6675 @Override
6676 public void cleanupDisabledPackageComponents(
6677 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6678 synchronized (mGlobalLock) {
6679 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006680 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006681 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006682 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 mStackSupervisor.scheduleIdleLocked();
6684 }
6685
6686 // Clean-up disabled tasks
6687 getRecentTasks().cleanupDisabledPackageTasksLocked(
6688 packageName, disabledClasses, userId);
6689 }
6690 }
6691
6692 @Override
6693 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6694 int userId) {
6695 synchronized (mGlobalLock) {
6696
6697 boolean didSomething =
6698 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006699 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006700 null, doit, evenPersistent, userId);
6701 return didSomething;
6702 }
6703 }
6704
6705 @Override
6706 public void resumeTopActivities(boolean scheduleIdle) {
6707 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 if (scheduleIdle) {
6710 mStackSupervisor.scheduleIdleLocked();
6711 }
6712 }
6713 }
6714
Riddle Hsua0536432019-02-16 00:38:59 +08006715 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 @Override
6717 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006718 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006719 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6720 }
6721 }
6722
Riddle Hsua0536432019-02-16 00:38:59 +08006723 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006724 @Override
6725 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006726 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006727 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006728 }
6729 }
6730
6731 @Override
6732 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6733 try {
6734 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6735 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6736 }
6737 } catch (RemoteException ex) {
6738 throw new SecurityException("Fail to check is caller a privileged app", ex);
6739 }
6740
6741 synchronized (mGlobalLock) {
6742 final long ident = Binder.clearCallingIdentity();
6743 try {
6744 if (mAmInternal.shouldConfirmCredentials(userId)) {
6745 if (mKeyguardController.isKeyguardLocked()) {
6746 // Showing launcher to avoid user entering credential twice.
6747 startHomeActivity(currentUserId, "notifyLockedProfile");
6748 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006749 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006750 }
6751 } finally {
6752 Binder.restoreCallingIdentity(ident);
6753 }
6754 }
6755 }
6756
6757 @Override
6758 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6759 mAmInternal.enforceCallingPermission(
6760 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6761
6762 synchronized (mGlobalLock) {
6763 final long ident = Binder.clearCallingIdentity();
6764 try {
6765 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6766 FLAG_ACTIVITY_TASK_ON_HOME);
6767 ActivityOptions activityOptions = options != null
6768 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006769 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006771 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006772 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006773 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6775 UserHandle.CURRENT);
6776 } finally {
6777 Binder.restoreCallingIdentity(ident);
6778 }
6779 }
6780 }
6781
6782 @Override
6783 public void writeActivitiesToProto(ProtoOutputStream proto) {
6784 synchronized (mGlobalLock) {
6785 // The output proto of "activity --proto activities"
6786 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006787 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006788 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6789 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 }
6791 }
6792
6793 @Override
6794 public void saveANRState(String reason) {
6795 synchronized (mGlobalLock) {
6796 final StringWriter sw = new StringWriter();
6797 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6798 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6799 if (reason != null) {
6800 pw.println(" Reason: " + reason);
6801 }
6802 pw.println();
6803 getActivityStartController().dump(pw, " ", null);
6804 pw.println();
6805 pw.println("-------------------------------------------------------------------------------");
6806 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6807 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6808 "" /* header */);
6809 pw.println();
6810 pw.close();
6811
6812 mLastANRState = sw.toString();
6813 }
6814 }
6815
6816 @Override
6817 public void clearSavedANRState() {
6818 synchronized (mGlobalLock) {
6819 mLastANRState = null;
6820 }
6821 }
6822
6823 @Override
6824 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6825 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6826 synchronized (mGlobalLock) {
6827 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6828 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6829 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6830 dumpLastANRLocked(pw);
6831 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6832 dumpLastANRTracesLocked(pw);
6833 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6834 dumpActivityStarterLocked(pw, dumpPackage);
6835 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6836 dumpActivityContainersLocked(pw);
6837 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6838 if (getRecentTasks() != null) {
6839 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6840 }
6841 }
6842 }
6843 }
6844
6845 @Override
6846 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6847 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6848 int wakefulness) {
6849 synchronized (mGlobalLock) {
6850 if (mHomeProcess != null && (dumpPackage == null
6851 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6852 if (needSep) {
6853 pw.println();
6854 needSep = false;
6855 }
6856 pw.println(" mHomeProcess: " + mHomeProcess);
6857 }
6858 if (mPreviousProcess != null && (dumpPackage == null
6859 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6860 if (needSep) {
6861 pw.println();
6862 needSep = false;
6863 }
6864 pw.println(" mPreviousProcess: " + mPreviousProcess);
6865 }
6866 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6867 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6868 StringBuilder sb = new StringBuilder(128);
6869 sb.append(" mPreviousProcessVisibleTime: ");
6870 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6871 pw.println(sb);
6872 }
6873 if (mHeavyWeightProcess != null && (dumpPackage == null
6874 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6875 if (needSep) {
6876 pw.println();
6877 needSep = false;
6878 }
6879 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6880 }
6881 if (dumpPackage == null) {
6882 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006883 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 }
6885 if (dumpAll) {
6886 if (dumpPackage == null) {
6887 pw.println(" mConfigWillChange: "
6888 + getTopDisplayFocusedStack().mConfigWillChange);
6889 }
6890 if (mCompatModePackages.getPackages().size() > 0) {
6891 boolean printed = false;
6892 for (Map.Entry<String, Integer> entry
6893 : mCompatModePackages.getPackages().entrySet()) {
6894 String pkg = entry.getKey();
6895 int mode = entry.getValue();
6896 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6897 continue;
6898 }
6899 if (!printed) {
6900 pw.println(" mScreenCompatPackages:");
6901 printed = true;
6902 }
6903 pw.println(" " + pkg + ": " + mode);
6904 }
6905 }
6906 }
6907
6908 if (dumpPackage == null) {
6909 pw.println(" mWakefulness="
6910 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 if (mRunningVoice != null) {
6913 pw.println(" mRunningVoice=" + mRunningVoice);
6914 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6915 }
6916 pw.println(" mSleeping=" + mSleeping);
6917 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6918 pw.println(" mVrController=" + mVrController);
6919 }
6920 if (mCurAppTimeTracker != null) {
6921 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6922 }
6923 if (mAllowAppSwitchUids.size() > 0) {
6924 boolean printed = false;
6925 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6926 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6927 for (int j = 0; j < types.size(); j++) {
6928 if (dumpPackage == null ||
6929 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6930 if (needSep) {
6931 pw.println();
6932 needSep = false;
6933 }
6934 if (!printed) {
6935 pw.println(" mAllowAppSwitchUids:");
6936 printed = true;
6937 }
6938 pw.print(" User ");
6939 pw.print(mAllowAppSwitchUids.keyAt(i));
6940 pw.print(": Type ");
6941 pw.print(types.keyAt(j));
6942 pw.print(" = ");
6943 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6944 pw.println();
6945 }
6946 }
6947 }
6948 }
6949 if (dumpPackage == null) {
6950 if (mController != null) {
6951 pw.println(" mController=" + mController
6952 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6953 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006954 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6955 pw.println(" mLaunchingActivityWakeLock="
6956 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006957 }
6958
6959 return needSep;
6960 }
6961 }
6962
6963 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006964 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6965 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006966 synchronized (mGlobalLock) {
6967 if (dumpPackage == null) {
6968 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6969 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006970 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6971 if (mRunningVoice != null) {
6972 final long vrToken = proto.start(
6973 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6974 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6975 mRunningVoice.toString());
6976 mVoiceWakeLock.writeToProto(
6977 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6978 proto.end(vrToken);
6979 }
6980 mVrController.writeToProto(proto,
6981 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 if (mController != null) {
6983 final long token = proto.start(CONTROLLER);
6984 proto.write(CONTROLLER, mController.toString());
6985 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6986 proto.end(token);
6987 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006988 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6989 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6990 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006991 }
6992
6993 if (mHomeProcess != null && (dumpPackage == null
6994 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006995 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006996 }
6997
6998 if (mPreviousProcess != null && (dumpPackage == null
6999 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007000 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007001 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7002 }
7003
7004 if (mHeavyWeightProcess != null && (dumpPackage == null
7005 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007006 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 }
7008
7009 for (Map.Entry<String, Integer> entry
7010 : mCompatModePackages.getPackages().entrySet()) {
7011 String pkg = entry.getKey();
7012 int mode = entry.getValue();
7013 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7014 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7015 proto.write(PACKAGE, pkg);
7016 proto.write(MODE, mode);
7017 proto.end(compatToken);
7018 }
7019 }
7020
7021 if (mCurAppTimeTracker != null) {
7022 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7023 }
7024
7025 }
7026 }
7027
7028 @Override
7029 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7030 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7031 boolean dumpFocusedStackOnly) {
7032 synchronized (mGlobalLock) {
7033 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7034 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7035 }
7036 }
7037
7038 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007039 public void dumpForOom(PrintWriter pw) {
7040 synchronized (mGlobalLock) {
7041 pw.println(" mHomeProcess: " + mHomeProcess);
7042 pw.println(" mPreviousProcess: " + mPreviousProcess);
7043 if (mHeavyWeightProcess != null) {
7044 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7045 }
7046 }
7047 }
7048
7049 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 public boolean canGcNow() {
7051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007052 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007053 }
7054 }
7055
Riddle Hsua0536432019-02-16 00:38:59 +08007056 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007057 @Override
7058 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007059 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007060 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007061 return top != null ? top.app : null;
7062 }
7063 }
7064
Riddle Hsua0536432019-02-16 00:38:59 +08007065 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007066 @Override
7067 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007068 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007069 if (mRootActivityContainer != null) {
7070 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007071 }
7072 }
7073 }
7074
7075 @Override
7076 public void scheduleDestroyAllActivities(String reason) {
7077 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007078 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 }
7080 }
7081
7082 @Override
7083 public void removeUser(int userId) {
7084 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007085 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 }
7087 }
7088
7089 @Override
7090 public boolean switchUser(int userId, UserState userState) {
7091 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007092 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094 }
7095
7096 @Override
7097 public void onHandleAppCrash(WindowProcessController wpc) {
7098 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007099 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 }
7101 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007102
7103 @Override
7104 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7105 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007106 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007107 }
7108 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007109
Riddle Hsua0536432019-02-16 00:38:59 +08007110 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007111 @Override
7112 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007113 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007114 }
7115
Riddle Hsua0536432019-02-16 00:38:59 +08007116 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007117 @Override
7118 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007119 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007120 }
7121
Riddle Hsua0536432019-02-16 00:38:59 +08007122 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007123 @Override
7124 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007125 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007126 }
7127
Riddle Hsua0536432019-02-16 00:38:59 +08007128 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007129 @Override
7130 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007131 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007132 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007133
7134 @Override
7135 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007136 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007137 mPendingTempWhitelist.put(uid, tag);
7138 }
7139 }
7140
7141 @Override
7142 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007143 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007144 mPendingTempWhitelist.remove(uid);
7145 }
7146 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007147
7148 @Override
7149 public boolean handleAppCrashInActivityController(String processName, int pid,
7150 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7151 Runnable killCrashingAppCallback) {
7152 synchronized (mGlobalLock) {
7153 if (mController == null) {
7154 return false;
7155 }
7156
7157 try {
7158 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7159 stackTrace)) {
7160 killCrashingAppCallback.run();
7161 return true;
7162 }
7163 } catch (RemoteException e) {
7164 mController = null;
7165 Watchdog.getInstance().setActivityController(null);
7166 }
7167 return false;
7168 }
7169 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007170
7171 @Override
7172 public void removeRecentTasksByPackageName(String packageName, int userId) {
7173 synchronized (mGlobalLock) {
7174 mRecentTasks.removeTasksByPackageName(packageName, userId);
7175 }
7176 }
7177
7178 @Override
7179 public void cleanupRecentTasksForUser(int userId) {
7180 synchronized (mGlobalLock) {
7181 mRecentTasks.cleanupLocked(userId);
7182 }
7183 }
7184
7185 @Override
7186 public void loadRecentTasksForUser(int userId) {
7187 synchronized (mGlobalLock) {
7188 mRecentTasks.loadUserRecentsLocked(userId);
7189 }
7190 }
7191
7192 @Override
7193 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7194 synchronized (mGlobalLock) {
7195 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7196 }
7197 }
7198
7199 @Override
7200 public void flushRecentTasks() {
7201 mRecentTasks.flush();
7202 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007203
7204 @Override
7205 public WindowProcessController getHomeProcess() {
7206 synchronized (mGlobalLock) {
7207 return mHomeProcess;
7208 }
7209 }
7210
7211 @Override
7212 public WindowProcessController getPreviousProcess() {
7213 synchronized (mGlobalLock) {
7214 return mPreviousProcess;
7215 }
7216 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007217
7218 @Override
7219 public void clearLockedTasks(String reason) {
7220 synchronized (mGlobalLock) {
7221 getLockTaskController().clearLockedTasks(reason);
7222 }
7223 }
7224
7225 @Override
7226 public void updateUserConfiguration() {
7227 synchronized (mGlobalLock) {
7228 final Configuration configuration = new Configuration(getGlobalConfiguration());
7229 final int currentUserId = mAmInternal.getCurrentUserId();
7230 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7231 configuration, currentUserId, Settings.System.canWrite(mContext));
7232 updateConfigurationLocked(configuration, null /* starting */,
7233 false /* initLocale */, false /* persistent */, currentUserId,
7234 false /* deferResume */);
7235 }
7236 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007237
7238 @Override
7239 public boolean canShowErrorDialogs() {
7240 synchronized (mGlobalLock) {
7241 return mShowDialogs && !mSleeping && !mShuttingDown
7242 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7243 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7244 mAmInternal.getCurrentUserId())
7245 && !(UserManager.isDeviceInDemoMode(mContext)
7246 && mAmInternal.getCurrentUser().isDemo());
7247 }
7248 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007249
7250 @Override
7251 public void setProfileApp(String profileApp) {
7252 synchronized (mGlobalLock) {
7253 mProfileApp = profileApp;
7254 }
7255 }
7256
7257 @Override
7258 public void setProfileProc(WindowProcessController wpc) {
7259 synchronized (mGlobalLock) {
7260 mProfileProc = wpc;
7261 }
7262 }
7263
7264 @Override
7265 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7266 synchronized (mGlobalLock) {
7267 mProfilerInfo = profilerInfo;
7268 }
7269 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007270
7271 @Override
7272 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7273 synchronized (mGlobalLock) {
7274 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7275 }
7276 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007277
7278 @Override
7279 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7280 synchronized (mGlobalLock) {
7281 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7282 }
7283 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007284
7285 @Override
7286 public boolean isUidForeground(int uid) {
7287 synchronized (mGlobalLock) {
7288 return ActivityTaskManagerService.this.isUidForeground(uid);
7289 }
7290 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007291
7292 @Override
7293 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7294 synchronized (mGlobalLock) {
7295 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7296 }
7297 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007298
7299 @Override
7300 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007301 // Translate package names into UIDs
7302 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007303 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007304 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7305 if (uid >= 0) {
7306 result.add(uid);
7307 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007308 }
7309 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007310 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007311 }
7312 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007313 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007314}