blob: 7bc9600f50b45fcc2c2807423149fe3500ab6b80 [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;
Sunny Goyald40c3452019-03-20 12:46:55 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
Sunny Goyald40c3452019-03-20 12:46:55 -0700116import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_TASK_ID;
wilsonshihe7903ea2018-09-26 16:17:59 +0800117import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
118import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700119import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
120import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
122import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800123import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
124import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
125import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700126
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700215import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
217import android.util.EventLog;
218import android.util.Log;
Sunny Goyald40c3452019-03-20 12:46:55 -0700219import android.util.Pair;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700220import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700222import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700229import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800230import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100251import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.LocalServices;
253import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700254import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800255import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700257import com.android.server.am.ActivityManagerService;
258import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
259import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
260import com.android.server.am.AppTimeTracker;
261import com.android.server.am.BaseErrorDialog;
262import com.android.server.am.EventLogTags;
263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900266import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315
Wale Ogunwale98875612018-10-12 07:53:02 -0700316 /** Used to indicate that an app transition should be animated. */
317 static final boolean ANIMATE = true;
318
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700319 /** Hardware-reported OpenGLES version. */
320 final int GL_ES_VERSION;
321
Wale Ogunwale31913b52018-10-13 08:29:31 -0700322 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
323 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
324 public static final String DUMP_LASTANR_CMD = "lastanr" ;
325 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
326 public static final String DUMP_STARTER_CMD = "starter" ;
327 public static final String DUMP_CONTAINERS_CMD = "containers" ;
328 public static final String DUMP_RECENTS_CMD = "recents" ;
329 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
330
Wale Ogunwale64258362018-10-16 15:13:37 -0700331 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
332 public static final int RELAUNCH_REASON_NONE = 0;
333 /** This activity is being relaunched due to windowing mode change. */
334 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
335 /** This activity is being relaunched due to a free-resize operation. */
336 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
337
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700338 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700339
Wale Ogunwalef6733932018-06-27 05:14:34 -0700340 /**
341 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
342 * change at runtime. Use mContext for non-UI purposes.
343 */
344 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700346 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700347 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700349 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700350 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800351 @VisibleForTesting
352 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 PowerManagerInternal mPowerManagerInternal;
354 private UsageStatsManagerInternal mUsageStatsInternal;
355
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700356 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 IntentFirewall mIntentFirewall;
358
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700359 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800360 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800361 /**
362 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
363 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
364 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
365 *
366 * @see WindowManagerThreadPriorityBooster
367 */
368 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700369 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800370 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700371 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700372 private UserManagerService mUserManager;
373 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700374 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800375 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700376 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /** All processes currently running that might have a window organized by name. */
378 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100379 /** All processes we currently have running mapped by pid and uid */
380 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** This is the process holding what we currently consider to be the "home" activity. */
382 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700383 /** The currently running heavy-weight process, if any. */
384 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700385 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /**
387 * This is the process holding the activity the user last visited that is in a different process
388 * from the one they are currently in.
389 */
390 WindowProcessController mPreviousProcess;
391 /** The time at which the previous process was last visible. */
392 long mPreviousProcessVisibleTime;
393
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700394 /** List of intents that were used to start the most recent tasks. */
395 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700396 /** State of external calls telling us if the device is awake or asleep. */
397 private boolean mKeyguardShown = false;
398
399 // Wrapper around VoiceInteractionServiceManager
400 private AssistUtils mAssistUtils;
401
402 // VoiceInteraction session ID that changes for each new request except when
403 // being called for multi-window assist in a single session.
404 private int mViSessionId = 1000;
405
406 // How long to wait in getAssistContextExtras for the activity and foreground services
407 // to respond with the result.
408 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
409
410 // How long top wait when going through the modern assist (which doesn't need to block
411 // on getting this result before starting to launch its UI).
412 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
413
414 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
415 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
416
Alison Cichowlas3e340502018-08-07 17:15:01 -0400417 // Permission tokens are used to temporarily granted a trusted app the ability to call
418 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
419 // showing any appropriate error messages to the user.
420 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
421 10 * MINUTE_IN_MILLIS;
422
423 // How long before the service actually expires a token. This is slightly longer than
424 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
425 // expiration exception.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
427 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
428
429 // How long the service will remember expired tokens, for the purpose of providing error
430 // messaging when a client uses an expired token.
431 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
432 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
433
Marvin Ramin830d4e32019-03-12 13:16:58 +0100434 // How long to whitelist the Services for when requested.
435 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
436
Alison Cichowlas3e340502018-08-07 17:15:01 -0400437 // Activity tokens of system activities that are delegating their call to
438 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
439 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
440
441 // Permission tokens that have expired, but we remember for error reporting.
442 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
443
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700444 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
445
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700446 // Keeps track of the active voice interaction service component, notified from
447 // VoiceInteractionManagerService
448 ComponentName mActiveVoiceInteractionServiceComponent;
449
Michal Karpinskida34cd42019-04-02 19:46:52 +0100450 // A map userId and all its companion app uids
451 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000452
Wale Ogunwalee2172292018-10-25 10:11:10 -0700453 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 KeyguardController mKeyguardController;
455 private final ClientLifecycleManager mLifecycleManager;
456 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700457 /** The controller for all operations related to locktask. */
458 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700459 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700461 boolean mSuppressResizeConfigChanges;
462
463 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
464 new UpdateConfigurationResult();
465
466 static final class UpdateConfigurationResult {
467 // Configuration changes that were updated.
468 int changes;
469 // If the activity was relaunched to match the new configuration.
470 boolean activityRelaunched;
471
472 void reset() {
473 changes = 0;
474 activityRelaunched = false;
475 }
476 }
477
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 private int mConfigurationSeq;
480 // To cache the list of supported system locales
481 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482
483 /**
484 * Temp object used when global and/or display override configuration is updated. It is also
485 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
486 * anyone...
487 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private Configuration mTempConfig = new Configuration();
489
Wale Ogunwalef6733932018-06-27 05:14:34 -0700490 /** Temporary to avoid allocations. */
491 final StringBuilder mStringBuilder = new StringBuilder(256);
492
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 // Amount of time after a call to stopAppSwitches() during which we will
494 // prevent further untrusted switches from happening.
495 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
496
497 /**
498 * The time at which we will allow normal application switches again,
499 * after a call to {@link #stopAppSwitches()}.
500 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
503 * This is set to true after the first switch after mAppSwitchesAllowedTime
504 * is set; any switches after that will clear the time.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507
508 IActivityController mController = null;
509 boolean mControllerIsAMonkey = false;
510
Wale Ogunwale214f3482018-10-04 11:00:47 -0700511 final int mFactoryTest;
512
513 /** Used to control how we initialize the service. */
514 ComponentName mTopComponent;
515 String mTopAction = Intent.ACTION_MAIN;
516 String mTopData;
517
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800518 /** Profiling app information. */
519 String mProfileApp = null;
520 WindowProcessController mProfileProc = null;
521 ProfilerInfo mProfilerInfo = null;
522
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700524 * Dump of the activity state at the time of the last ANR. Cleared after
525 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
526 */
527 String mLastANRState;
528
529 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 * Used to retain an update lock when the foreground activity is in
531 * immersive mode.
532 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700533 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534
535 /**
536 * Packages that are being allowed to perform unrestricted app switches. Mapping is
537 * User -> Type -> uid.
538 */
539 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
540
541 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private int mThumbnailWidth;
543 private int mThumbnailHeight;
544 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Flag that indicates if multi-window is enabled.
548 *
549 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
550 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
551 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
552 * At least one of the forms of multi-window must be enabled in order for this flag to be
553 * initialized to 'true'.
554 *
555 * @see #mSupportsSplitScreenMultiWindow
556 * @see #mSupportsFreeformWindowManagement
557 * @see #mSupportsPictureInPicture
558 * @see #mSupportsMultiDisplay
559 */
560 boolean mSupportsMultiWindow;
561 boolean mSupportsSplitScreenMultiWindow;
562 boolean mSupportsFreeformWindowManagement;
563 boolean mSupportsPictureInPicture;
564 boolean mSupportsMultiDisplay;
565 boolean mForceResizableActivities;
566
567 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
568
569 // VR Vr2d Display Id.
570 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700571
Wale Ogunwalef6733932018-06-27 05:14:34 -0700572 /**
573 * Set while we are wanting to sleep, to prevent any
574 * activities from being started/resumed.
575 *
576 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
577 *
578 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
579 * while in the sleep state until there is a pending transition out of sleep, in which case
580 * mSleeping is set to false, and remains false while awake.
581 *
582 * Whether mSleeping can quickly toggled between true/false without the device actually
583 * display changing states is undefined.
584 */
585 private boolean mSleeping = false;
586
587 /**
588 * The process state used for processes that are running the top activities.
589 * This changes between TOP and TOP_SLEEPING to following mSleeping.
590 */
591 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
592
593 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
594 // automatically. Important for devices without direct input devices.
595 private boolean mShowDialogs = true;
596
597 /** Set if we are shutting down the system, similar to sleeping. */
598 boolean mShuttingDown = false;
599
600 /**
601 * We want to hold a wake lock while running a voice interaction session, since
602 * this may happen with the screen off and we need to keep the CPU running to
603 * be able to continue to interact with the user.
604 */
605 PowerManager.WakeLock mVoiceWakeLock;
606
607 /**
608 * Set while we are running a voice interaction. This overrides sleeping while it is active.
609 */
610 IVoiceInteractionSession mRunningVoice;
611
612 /**
613 * The last resumed activity. This is identical to the current resumed activity most
614 * of the time but could be different when we're pausing one activity before we resume
615 * another activity.
616 */
617 ActivityRecord mLastResumedActivity;
618
619 /**
620 * The activity that is currently being traced as the active resumed activity.
621 *
622 * @see #updateResumedAppTrace
623 */
624 private @Nullable ActivityRecord mTracedResumedActivity;
625
626 /** If non-null, we are tracking the time the user spends in the currently focused app. */
627 AppTimeTracker mCurAppTimeTracker;
628
Wale Ogunwale008163e2018-07-23 23:11:08 -0700629 private AppWarnings mAppWarnings;
630
Wale Ogunwale53783742018-09-16 10:21:51 -0700631 /**
632 * Packages that the user has asked to have run in screen size
633 * compatibility mode instead of filling the screen.
634 */
635 CompatModePackages mCompatModePackages;
636
Wale Ogunwalef6733932018-06-27 05:14:34 -0700637 private FontScaleSettingObserver mFontScaleSettingObserver;
638
Ricky Wai96f5c352019-04-10 18:40:17 +0100639 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000640
Wale Ogunwalef6733932018-06-27 05:14:34 -0700641 private final class FontScaleSettingObserver extends ContentObserver {
642 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
643 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
644
645 public FontScaleSettingObserver() {
646 super(mH);
647 final ContentResolver resolver = mContext.getContentResolver();
648 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
649 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
650 UserHandle.USER_ALL);
651 }
652
653 @Override
654 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
655 if (mFontScaleUri.equals(uri)) {
656 updateFontScaleIfNeeded(userId);
657 } else if (mHideErrorDialogsUri.equals(uri)) {
658 synchronized (mGlobalLock) {
659 updateShouldShowDialogsLocked(getGlobalConfiguration());
660 }
661 }
662 }
663 }
664
Riddle Hsua0536432019-02-16 00:38:59 +0800665 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
666 @Target(ElementType.METHOD)
667 @Retention(RetentionPolicy.SOURCE)
668 @interface HotPath {
669 int NONE = 0;
670 int OOM_ADJUSTMENT = 1;
671 int LRU_UPDATE = 2;
672 int PROCESS_CHANGE = 3;
673 int caller() default NONE;
674 }
675
Charles Chen8d98dd22018-12-26 17:36:54 +0800676 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
677 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700678 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700679 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700680 mSystemThread = ActivityThread.currentActivityThread();
681 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700682 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800683 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700684 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700685 }
686
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700687 public void onSystemReady() {
688 synchronized (mGlobalLock) {
689 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
690 PackageManager.FEATURE_CANT_SAVE_STATE);
691 mAssistUtils = new AssistUtils(mContext);
692 mVrController.onSystemReady();
693 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700694 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700696 }
697
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700698 public void onInitPowerManagement() {
699 synchronized (mGlobalLock) {
700 mStackSupervisor.initPowerManagement();
701 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
702 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
703 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
704 mVoiceWakeLock.setReferenceCounted(false);
705 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700709 mFontScaleSettingObserver = new FontScaleSettingObserver();
710 }
711
Wale Ogunwale59507092018-10-29 09:00:30 -0700712 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700713 final boolean freeformWindowManagement =
714 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
715 || Settings.Global.getInt(
716 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
717
718 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
719 final boolean supportsPictureInPicture = supportsMultiWindow &&
720 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
721 final boolean supportsSplitScreenMultiWindow =
722 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
723 final boolean supportsMultiDisplay = mContext.getPackageManager()
724 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
726 final boolean forceResizable = Settings.Global.getInt(
727 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700728 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729
730 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900731 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732
733 final Configuration configuration = new Configuration();
734 Settings.System.getConfiguration(resolver, configuration);
735 if (forceRtl) {
736 // This will take care of setting the correct layout direction flags
737 configuration.setLayoutDirection(configuration.locale);
738 }
739
740 synchronized (mGlobalLock) {
741 mForceResizableActivities = forceResizable;
742 final boolean multiWindowFormEnabled = freeformWindowManagement
743 || supportsSplitScreenMultiWindow
744 || supportsPictureInPicture
745 || supportsMultiDisplay;
746 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
747 mSupportsMultiWindow = true;
748 mSupportsFreeformWindowManagement = freeformWindowManagement;
749 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
750 mSupportsPictureInPicture = supportsPictureInPicture;
751 mSupportsMultiDisplay = supportsMultiDisplay;
752 } else {
753 mSupportsMultiWindow = false;
754 mSupportsFreeformWindowManagement = false;
755 mSupportsSplitScreenMultiWindow = false;
756 mSupportsPictureInPicture = false;
757 mSupportsMultiDisplay = false;
758 }
759 mWindowManager.setForceResizableTasks(mForceResizableActivities);
760 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700761 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
762 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700763 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 // This happens before any activities are started, so we can change global configuration
765 // in-place.
766 updateConfigurationLocked(configuration, null, true);
767 final Configuration globalConfig = getGlobalConfiguration();
768 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
769
770 // Load resources only after the current configuration has been set.
771 final Resources res = mContext.getResources();
772 mThumbnailWidth = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_width);
774 mThumbnailHeight = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_height);
776
777 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
778 mFullscreenThumbnailScale = (float) res
779 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
780 (float) globalConfig.screenWidthDp;
781 } else {
782 mFullscreenThumbnailScale = res.getFraction(
783 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
784 }
785 }
786 }
787
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800788 public WindowManagerGlobalLock getGlobalLock() {
789 return mGlobalLock;
790 }
791
Yunfan Chen585f2932019-01-29 16:04:45 +0900792 /** For test purpose only. */
793 @VisibleForTesting
794 public ActivityTaskManagerInternal getAtmInternal() {
795 return mInternal;
796 }
797
Riddle Hsud93a6c42018-11-29 21:50:06 +0800798 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
799 Looper looper) {
800 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700803 final File systemDir = SystemServiceManager.ensureSystemDir();
804 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
805 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
808 mTempConfig.setToDefaults();
809 mTempConfig.setLocales(LocaleList.getDefault());
810 mConfigurationSeq = mTempConfig.seq = 1;
811 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800812 mRootActivityContainer = new RootActivityContainer(this);
813 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700817 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700819 mRecentTasks = createRecentTasks();
820 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700822 mKeyguardController = mStackSupervisor.getKeyguardController();
823 }
824
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700825 public void onActivityManagerInternalAdded() {
826 synchronized (mGlobalLock) {
827 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
828 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
829 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700830 }
831
Yunfan Chen75157d72018-07-27 14:47:21 +0900832 int increaseConfigurationSeqLocked() {
833 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
834 return mConfigurationSeq;
835 }
836
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 protected ActivityStackSupervisor createStackSupervisor() {
838 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
839 supervisor.initialize();
840 return supervisor;
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void setWindowManager(WindowManagerService wm) {
844 synchronized (mGlobalLock) {
845 mWindowManager = wm;
846 mLockTaskController.setWindowManager(wm);
847 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800848 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
853 synchronized (mGlobalLock) {
854 mUsageStatsInternal = usageStatsManager;
855 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700856 }
857
Wale Ogunwalef6733932018-06-27 05:14:34 -0700858 UserManagerService getUserManager() {
859 if (mUserManager == null) {
860 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
861 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
862 }
863 return mUserManager;
864 }
865
866 AppOpsService getAppOpsService() {
867 if (mAppOpsService == null) {
868 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
869 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
870 }
871 return mAppOpsService;
872 }
873
874 boolean hasUserRestriction(String restriction, int userId) {
875 return getUserManager().hasUserRestriction(restriction, userId);
876 }
877
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 protected RecentTasks createRecentTasks() {
879 return new RecentTasks(this, mStackSupervisor);
880 }
881
882 RecentTasks getRecentTasks() {
883 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700884 }
885
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700886 ClientLifecycleManager getLifecycleManager() {
887 return mLifecycleManager;
888 }
889
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700890 ActivityStartController getActivityStartController() {
891 return mActivityStartController;
892 }
893
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700894 TaskChangeNotificationController getTaskChangeNotificationController() {
895 return mTaskChangeNotificationController;
896 }
897
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700898 LockTaskController getLockTaskController() {
899 return mLockTaskController;
900 }
901
Yunfan Chen75157d72018-07-27 14:47:21 +0900902 /**
903 * Return the global configuration used by the process corresponding to the input pid. This is
904 * usually the global configuration with some overrides specific to that process.
905 */
906 Configuration getGlobalConfigurationForCallingPid() {
907 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800908 return getGlobalConfigurationForPid(pid);
909 }
910
911 /**
912 * Return the global configuration used by the process corresponding to the given pid.
913 */
914 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900915 if (pid == MY_PID || pid < 0) {
916 return getGlobalConfiguration();
917 }
918 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100919 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900920 return app != null ? app.getConfiguration() : getGlobalConfiguration();
921 }
922 }
923
924 /**
925 * Return the device configuration info used by the process corresponding to the input pid.
926 * The value is consistent with the global configuration for the process.
927 */
928 @Override
929 public ConfigurationInfo getDeviceConfigurationInfo() {
930 ConfigurationInfo config = new ConfigurationInfo();
931 synchronized (mGlobalLock) {
932 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
933 config.reqTouchScreen = globalConfig.touchscreen;
934 config.reqKeyboardType = globalConfig.keyboard;
935 config.reqNavigation = globalConfig.navigation;
936 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
937 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
938 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
939 }
940 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
941 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
942 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
943 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700944 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900945 }
946 return config;
947 }
948
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700949 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700950 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700951 }
952
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700953 public static final class Lifecycle extends SystemService {
954 private final ActivityTaskManagerService mService;
955
956 public Lifecycle(Context context) {
957 super(context);
958 mService = new ActivityTaskManagerService(context);
959 }
960
961 @Override
962 public void onStart() {
963 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700965 }
966
Garfield Tan891146c2018-10-09 12:14:00 -0700967 @Override
968 public void onUnlockUser(int userId) {
969 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800970 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700971 }
972 }
973
974 @Override
975 public void onCleanupUser(int userId) {
976 synchronized (mService.getGlobalLock()) {
977 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
978 }
979 }
980
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700981 public ActivityTaskManagerService getService() {
982 return mService;
983 }
984 }
985
986 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700987 public final int startActivity(IApplicationThread caller, String callingPackage,
988 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
989 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
990 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
991 resultWho, requestCode, startFlags, profilerInfo, bOptions,
992 UserHandle.getCallingUserId());
993 }
994
995 @Override
996 public final int startActivities(IApplicationThread caller, String callingPackage,
997 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
998 int userId) {
999 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001000 enforceNotIsolatedCaller(reason);
1001 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001002 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001003 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1004 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1005 reason, null /* originatingPendingIntent */,
1006 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001007 }
1008
1009 @Override
1010 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1011 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1012 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1013 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1014 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1015 true /*validateIncomingUser*/);
1016 }
1017
1018 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1019 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1020 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1021 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001024 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1026
1027 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001028 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 .setCaller(caller)
1030 .setCallingPackage(callingPackage)
1031 .setResolvedType(resolvedType)
1032 .setResultTo(resultTo)
1033 .setResultWho(resultWho)
1034 .setRequestCode(requestCode)
1035 .setStartFlags(startFlags)
1036 .setProfilerInfo(profilerInfo)
1037 .setActivityOptions(bOptions)
1038 .setMayWait(userId)
1039 .execute();
1040
1041 }
1042
1043 @Override
1044 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1045 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001046 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1047 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 // Refuse possible leaked file descriptors
1049 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1050 throw new IllegalArgumentException("File descriptors passed in Intent");
1051 }
1052
1053 if (!(target instanceof PendingIntentRecord)) {
1054 throw new IllegalArgumentException("Bad PendingIntent object");
1055 }
1056
1057 PendingIntentRecord pir = (PendingIntentRecord)target;
1058
1059 synchronized (mGlobalLock) {
1060 // If this is coming from the currently resumed activity, it is
1061 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001062 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 if (stack.mResumedActivity != null &&
1064 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 }
1067 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001068 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070 }
1071
1072 @Override
1073 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1074 Bundle bOptions) {
1075 // Refuse possible leaked file descriptors
1076 if (intent != null && intent.hasFileDescriptors()) {
1077 throw new IllegalArgumentException("File descriptors passed in Intent");
1078 }
1079 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1080
1081 synchronized (mGlobalLock) {
1082 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1083 if (r == null) {
1084 SafeActivityOptions.abort(options);
1085 return false;
1086 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001087 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001088 // The caller is not running... d'oh!
1089 SafeActivityOptions.abort(options);
1090 return false;
1091 }
1092 intent = new Intent(intent);
1093 // The caller is not allowed to change the data.
1094 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1095 // And we are resetting to find the next component...
1096 intent.setComponent(null);
1097
1098 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1099
1100 ActivityInfo aInfo = null;
1101 try {
1102 List<ResolveInfo> resolves =
1103 AppGlobals.getPackageManager().queryIntentActivities(
1104 intent, r.resolvedType,
1105 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1106 UserHandle.getCallingUserId()).getList();
1107
1108 // Look for the original activity in the list...
1109 final int N = resolves != null ? resolves.size() : 0;
1110 for (int i=0; i<N; i++) {
1111 ResolveInfo rInfo = resolves.get(i);
1112 if (rInfo.activityInfo.packageName.equals(r.packageName)
1113 && rInfo.activityInfo.name.equals(r.info.name)) {
1114 // We found the current one... the next matching is
1115 // after it.
1116 i++;
1117 if (i<N) {
1118 aInfo = resolves.get(i).activityInfo;
1119 }
1120 if (debug) {
1121 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1122 + "/" + r.info.name);
1123 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1124 ? "null" : aInfo.packageName + "/" + aInfo.name));
1125 }
1126 break;
1127 }
1128 }
1129 } catch (RemoteException e) {
1130 }
1131
1132 if (aInfo == null) {
1133 // Nobody who is next!
1134 SafeActivityOptions.abort(options);
1135 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1136 return false;
1137 }
1138
1139 intent.setComponent(new ComponentName(
1140 aInfo.applicationInfo.packageName, aInfo.name));
1141 intent.setFlags(intent.getFlags()&~(
1142 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1143 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1144 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1145 FLAG_ACTIVITY_NEW_TASK));
1146
1147 // Okay now we need to start the new activity, replacing the currently running activity.
1148 // This is a little tricky because we want to start the new one as if the current one is
1149 // finished, but not finish the current one first so that there is no flicker.
1150 // And thus...
1151 final boolean wasFinishing = r.finishing;
1152 r.finishing = true;
1153
1154 // Propagate reply information over to the new activity.
1155 final ActivityRecord resultTo = r.resultTo;
1156 final String resultWho = r.resultWho;
1157 final int requestCode = r.requestCode;
1158 r.resultTo = null;
1159 if (resultTo != null) {
1160 resultTo.removeResultsLocked(r, resultWho, requestCode);
1161 }
1162
1163 final long origId = Binder.clearCallingIdentity();
1164 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001165 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001167 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 .setResolvedType(r.resolvedType)
1169 .setActivityInfo(aInfo)
1170 .setResultTo(resultTo != null ? resultTo.appToken : null)
1171 .setResultWho(resultWho)
1172 .setRequestCode(requestCode)
1173 .setCallingPid(-1)
1174 .setCallingUid(r.launchedFromUid)
1175 .setCallingPackage(r.launchedFromPackage)
1176 .setRealCallingPid(-1)
1177 .setRealCallingUid(r.launchedFromUid)
1178 .setActivityOptions(options)
1179 .execute();
1180 Binder.restoreCallingIdentity(origId);
1181
1182 r.finishing = wasFinishing;
1183 if (res != ActivityManager.START_SUCCESS) {
1184 return false;
1185 }
1186 return true;
1187 }
1188 }
1189
1190 @Override
1191 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1192 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1193 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1194 final WaitResult res = new WaitResult();
1195 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001196 enforceNotIsolatedCaller("startActivityAndWait");
1197 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1198 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001200 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001201 .setCaller(caller)
1202 .setCallingPackage(callingPackage)
1203 .setResolvedType(resolvedType)
1204 .setResultTo(resultTo)
1205 .setResultWho(resultWho)
1206 .setRequestCode(requestCode)
1207 .setStartFlags(startFlags)
1208 .setActivityOptions(bOptions)
1209 .setMayWait(userId)
1210 .setProfilerInfo(profilerInfo)
1211 .setWaitResult(res)
1212 .execute();
1213 }
1214 return res;
1215 }
1216
1217 @Override
1218 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1219 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1220 int startFlags, Configuration config, Bundle bOptions, int userId) {
1221 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001222 enforceNotIsolatedCaller("startActivityWithConfig");
1223 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1224 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001226 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 .setCaller(caller)
1228 .setCallingPackage(callingPackage)
1229 .setResolvedType(resolvedType)
1230 .setResultTo(resultTo)
1231 .setResultWho(resultWho)
1232 .setRequestCode(requestCode)
1233 .setStartFlags(startFlags)
1234 .setGlobalConfiguration(config)
1235 .setActivityOptions(bOptions)
1236 .setMayWait(userId)
1237 .execute();
1238 }
1239 }
1240
Alison Cichowlas3e340502018-08-07 17:15:01 -04001241
1242 @Override
1243 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1244 int callingUid = Binder.getCallingUid();
1245 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1246 throw new SecurityException("Only the system process can request a permission token, "
1247 + "received request from uid: " + callingUid);
1248 }
1249 IBinder permissionToken = new Binder();
1250 synchronized (mGlobalLock) {
1251 mStartActivitySources.put(permissionToken, delegatorToken);
1252 }
1253
1254 Message expireMsg = PooledLambda.obtainMessage(
1255 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1256 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1257
1258 Message forgetMsg = PooledLambda.obtainMessage(
1259 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1260 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1261
1262 return permissionToken;
1263 }
1264
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001265 @Override
1266 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1267 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1269 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001271 // permission grants) as any app that may launch one of your own activities. So we only
1272 // allow this in two cases:
1273 // 1) The caller is an activity that is part of the core framework, and then only when it
1274 // is running as the system.
1275 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1276 // can only be requested by a system activity, which may then delegate this call to
1277 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 final ActivityRecord sourceRecord;
1279 final int targetUid;
1280 final String targetPackage;
1281 final boolean isResolver;
1282 synchronized (mGlobalLock) {
1283 if (resultTo == null) {
1284 throw new SecurityException("Must be called from an activity");
1285 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 final IBinder sourceToken;
1287 if (permissionToken != null) {
1288 // To even attempt to use a permissionToken, an app must also have this signature
1289 // permission.
1290 mAmInternal.enforceCallingPermission(
1291 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1292 "startActivityAsCaller");
1293 // If called with a permissionToken, we want the sourceRecord from the delegator
1294 // activity that requested this token.
1295 sourceToken = mStartActivitySources.remove(permissionToken);
1296 if (sourceToken == null) {
1297 // Invalid permissionToken, check if it recently expired.
1298 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1299 throw new SecurityException("Called with expired permission token: "
1300 + permissionToken);
1301 } else {
1302 throw new SecurityException("Called with invalid permission token: "
1303 + permissionToken);
1304 }
1305 }
1306 } else {
1307 // This method was called directly by the source.
1308 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310
Wale Ogunwaled32da472018-11-16 07:19:28 -08001311 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001312 if (sourceRecord == null) {
1313 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 }
1315 if (sourceRecord.app == null) {
1316 throw new SecurityException("Called without a process attached to activity");
1317 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001318
1319 // Whether called directly or from a delegate, the source activity must be from the
1320 // android package.
1321 if (!sourceRecord.info.packageName.equals("android")) {
1322 throw new SecurityException("Must be called from an activity that is "
1323 + "declared in the android package");
1324 }
1325
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001326 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 // This is still okay, as long as this activity is running under the
1328 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001329 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001330 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001331 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001332 + " must be system uid or original calling uid "
1333 + sourceRecord.launchedFromUid);
1334 }
1335 }
1336 if (ignoreTargetSecurity) {
1337 if (intent.getComponent() == null) {
1338 throw new SecurityException(
1339 "Component must be specified with ignoreTargetSecurity");
1340 }
1341 if (intent.getSelector() != null) {
1342 throw new SecurityException(
1343 "Selector not allowed with ignoreTargetSecurity");
1344 }
1345 }
1346 targetUid = sourceRecord.launchedFromUid;
1347 targetPackage = sourceRecord.launchedFromPackage;
1348 isResolver = sourceRecord.isResolverOrChildActivity();
1349 }
1350
1351 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001352 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 }
1354
1355 // TODO: Switch to user app stacks here.
1356 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001357 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 .setCallingUid(targetUid)
1359 .setCallingPackage(targetPackage)
1360 .setResolvedType(resolvedType)
1361 .setResultTo(resultTo)
1362 .setResultWho(resultWho)
1363 .setRequestCode(requestCode)
1364 .setStartFlags(startFlags)
1365 .setActivityOptions(bOptions)
1366 .setMayWait(userId)
1367 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1368 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1369 .execute();
1370 } catch (SecurityException e) {
1371 // XXX need to figure out how to propagate to original app.
1372 // A SecurityException here is generally actually a fault of the original
1373 // calling activity (such as a fairly granting permissions), so propagate it
1374 // back to them.
1375 /*
1376 StringBuilder msg = new StringBuilder();
1377 msg.append("While launching");
1378 msg.append(intent.toString());
1379 msg.append(": ");
1380 msg.append(e.getMessage());
1381 */
1382 throw e;
1383 }
1384 }
1385
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1387 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1388 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1389 }
1390
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 @Override
1392 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1393 Intent intent, String resolvedType, IVoiceInteractionSession session,
1394 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1395 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001396 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 if (session == null || interactor == null) {
1398 throw new NullPointerException("null session or interactor");
1399 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001402 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 .setCallingUid(callingUid)
1404 .setCallingPackage(callingPackage)
1405 .setResolvedType(resolvedType)
1406 .setVoiceSession(session)
1407 .setVoiceInteractor(interactor)
1408 .setStartFlags(startFlags)
1409 .setProfilerInfo(profilerInfo)
1410 .setActivityOptions(bOptions)
1411 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001412 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 .execute();
1414 }
1415
1416 @Override
1417 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1418 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001419 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1420 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001422 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 .setCallingUid(callingUid)
1424 .setCallingPackage(callingPackage)
1425 .setResolvedType(resolvedType)
1426 .setActivityOptions(bOptions)
1427 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001428 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 .execute();
1430 }
1431
1432 @Override
1433 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1434 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 final int callingPid = Binder.getCallingPid();
1437 final long origId = Binder.clearCallingIdentity();
1438 try {
1439 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001440 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1441 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442
1443 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001444 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1445 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1447 recentsUid, assistDataReceiver);
1448 }
1449 } finally {
1450 Binder.restoreCallingIdentity(origId);
1451 }
1452 }
1453
1454 @Override
1455 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 "startActivityFromRecents()");
1458
1459 final int callingPid = Binder.getCallingPid();
1460 final int callingUid = Binder.getCallingUid();
1461 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1462 final long origId = Binder.clearCallingIdentity();
1463 try {
1464 synchronized (mGlobalLock) {
1465 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1466 safeOptions);
1467 }
1468 } finally {
1469 Binder.restoreCallingIdentity(origId);
1470 }
1471 }
1472
1473 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001474 * Public API to check if the client is allowed to start an activity on specified display.
1475 *
1476 * If the target display is private or virtual, some restrictions will apply.
1477 *
1478 * @param displayId Target display id.
1479 * @param intent Intent used to launch the activity.
1480 * @param resolvedType The MIME type of the intent.
1481 * @param userId The id of the user for whom the call is made.
1482 * @return {@code true} if a call to start an activity on the target display should succeed and
1483 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1484 */
1485 @Override
1486 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1487 String resolvedType, int userId) {
1488 final int callingUid = Binder.getCallingUid();
1489 final int callingPid = Binder.getCallingPid();
1490 final long origId = Binder.clearCallingIdentity();
1491
1492 try {
1493 // Collect information about the target of the Intent.
1494 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1495 0 /* startFlags */, null /* profilerInfo */, userId,
1496 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1497 UserHandle.USER_NULL));
1498 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1499
1500 synchronized (mGlobalLock) {
1501 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1502 aInfo);
1503 }
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508
1509 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 * This is the internal entry point for handling Activity.finish().
1511 *
1512 * @param token The Binder token referencing the Activity we want to finish.
1513 * @param resultCode Result code, if any, from this Activity.
1514 * @param resultData Result data (Intent), if any, from this Activity.
1515 * @param finishTask Whether to finish the task associated with this Activity.
1516 *
1517 * @return Returns true if the activity successfully finished, or false if it is still running.
1518 */
1519 @Override
1520 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1521 int finishTask) {
1522 // Refuse possible leaked file descriptors
1523 if (resultData != null && resultData.hasFileDescriptors()) {
1524 throw new IllegalArgumentException("File descriptors passed in Intent");
1525 }
1526
1527 synchronized (mGlobalLock) {
1528 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1529 if (r == null) {
1530 return true;
1531 }
1532 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001533 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 ActivityRecord rootR = tr.getRootActivity();
1535 if (rootR == null) {
1536 Slog.w(TAG, "Finishing task with all activities already finished");
1537 }
1538 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1539 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001540 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 return false;
1542 }
1543
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001544 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1545 // We should consolidate.
1546 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001548 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001549 if (next != null) {
1550 // ask watcher if this is allowed
1551 boolean resumeOK = true;
1552 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001553 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001554 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001555 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 Watchdog.getInstance().setActivityController(null);
1557 }
1558
1559 if (!resumeOK) {
1560 Slog.i(TAG, "Not finishing activity because controller resumed");
1561 return false;
1562 }
1563 }
1564 }
1565 final long origId = Binder.clearCallingIdentity();
1566 try {
1567 boolean res;
1568 final boolean finishWithRootActivity =
1569 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1570 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1571 || (finishWithRootActivity && r == rootR)) {
1572 // If requested, remove the task that is associated to this activity only if it
1573 // was the root activity in the task. The result code and data is ignored
1574 // because we don't support returning them across task boundaries. Also, to
1575 // keep backwards compatibility we remove the task from recents when finishing
1576 // task with root activity.
1577 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1578 finishWithRootActivity, "finish-activity");
1579 if (!res) {
1580 Slog.i(TAG, "Removing task failed to finish activity");
1581 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001582 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001583 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 } else {
1585 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1586 resultData, "app-request", true);
1587 if (!res) {
1588 Slog.i(TAG, "Failed to finish by app-request");
1589 }
1590 }
1591 return res;
1592 } finally {
1593 Binder.restoreCallingIdentity(origId);
1594 }
1595 }
1596 }
1597
1598 @Override
1599 public boolean finishActivityAffinity(IBinder token) {
1600 synchronized (mGlobalLock) {
1601 final long origId = Binder.clearCallingIdentity();
1602 try {
1603 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1604 if (r == null) {
1605 return false;
1606 }
1607
1608 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1609 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001610 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001611 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 return false;
1613 }
1614 return task.getStack().finishActivityAffinityLocked(r);
1615 } finally {
1616 Binder.restoreCallingIdentity(origId);
1617 }
1618 }
1619 }
1620
1621 @Override
1622 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1623 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001624 try {
1625 WindowProcessController proc = null;
1626 synchronized (mGlobalLock) {
1627 ActivityStack stack = ActivityRecord.getStackLocked(token);
1628 if (stack == null) {
1629 return;
1630 }
1631 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1632 false /* fromTimeout */, false /* processPausingActivities */, config);
1633 if (r != null) {
1634 proc = r.app;
1635 }
1636 if (stopProfiling && proc != null) {
1637 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 }
1639 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001640 } finally {
1641 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 }
1644
1645 @Override
1646 public final void activityResumed(IBinder token) {
1647 final long origId = Binder.clearCallingIdentity();
1648 synchronized (mGlobalLock) {
1649 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001650 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
1652 Binder.restoreCallingIdentity(origId);
1653 }
1654
1655 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001656 public final void activityTopResumedStateLost() {
1657 final long origId = Binder.clearCallingIdentity();
1658 synchronized (mGlobalLock) {
1659 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1660 }
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663
1664 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001665 public final void activityPaused(IBinder token) {
1666 final long origId = Binder.clearCallingIdentity();
1667 synchronized (mGlobalLock) {
1668 ActivityStack stack = ActivityRecord.getStackLocked(token);
1669 if (stack != null) {
1670 stack.activityPausedLocked(token, false);
1671 }
1672 }
1673 Binder.restoreCallingIdentity(origId);
1674 }
1675
1676 @Override
1677 public final void activityStopped(IBinder token, Bundle icicle,
1678 PersistableBundle persistentState, CharSequence description) {
1679 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1680
1681 // Refuse possible leaked file descriptors
1682 if (icicle != null && icicle.hasFileDescriptors()) {
1683 throw new IllegalArgumentException("File descriptors passed in Bundle");
1684 }
1685
1686 final long origId = Binder.clearCallingIdentity();
1687
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001688 String restartingName = null;
1689 int restartingUid = 0;
1690 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001691 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001692 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001694 if (r.attachedToProcess()
1695 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1696 // The activity was requested to restart from
1697 // {@link #restartActivityProcessIfVisible}.
1698 restartingName = r.app.mName;
1699 restartingUid = r.app.mUid;
1700 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 r.activityStoppedLocked(icicle, persistentState, description);
1702 }
1703 }
1704
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001705 if (restartingName != null) {
1706 // In order to let the foreground activity can be restarted with its saved state from
1707 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1708 // until the activity reports stopped with the state. And the activity record will be
1709 // kept because the record state is restarting, then the activity will be restarted
1710 // immediately if it is still the top one.
1711 mStackSupervisor.removeRestartTimeouts(r);
1712 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1713 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001714 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715
1716 Binder.restoreCallingIdentity(origId);
1717 }
1718
1719 @Override
1720 public final void activityDestroyed(IBinder token) {
1721 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1722 synchronized (mGlobalLock) {
1723 ActivityStack stack = ActivityRecord.getStackLocked(token);
1724 if (stack != null) {
1725 stack.activityDestroyedLocked(token, "activityDestroyed");
1726 }
1727 }
1728 }
1729
1730 @Override
1731 public final void activityRelaunched(IBinder token) {
1732 final long origId = Binder.clearCallingIdentity();
1733 synchronized (mGlobalLock) {
1734 mStackSupervisor.activityRelaunchedLocked(token);
1735 }
1736 Binder.restoreCallingIdentity(origId);
1737 }
1738
1739 public final void activitySlept(IBinder token) {
1740 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1741
1742 final long origId = Binder.clearCallingIdentity();
1743
1744 synchronized (mGlobalLock) {
1745 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1746 if (r != null) {
1747 mStackSupervisor.activitySleptLocked(r);
1748 }
1749 }
1750
1751 Binder.restoreCallingIdentity(origId);
1752 }
1753
1754 @Override
1755 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1756 synchronized (mGlobalLock) {
1757 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1758 if (r == null) {
1759 return;
1760 }
1761 final long origId = Binder.clearCallingIdentity();
1762 try {
1763 r.setRequestedOrientation(requestedOrientation);
1764 } finally {
1765 Binder.restoreCallingIdentity(origId);
1766 }
1767 }
1768 }
1769
1770 @Override
1771 public int getRequestedOrientation(IBinder token) {
1772 synchronized (mGlobalLock) {
1773 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1774 if (r == null) {
1775 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1776 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001777 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 }
1779 }
1780
1781 @Override
1782 public void setImmersive(IBinder token, boolean immersive) {
1783 synchronized (mGlobalLock) {
1784 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1785 if (r == null) {
1786 throw new IllegalArgumentException();
1787 }
1788 r.immersive = immersive;
1789
1790 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001791 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001792 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001793 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794 }
1795 }
1796 }
1797
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001798 void applyUpdateLockStateLocked(ActivityRecord r) {
1799 // Modifications to the UpdateLock state are done on our handler, outside
1800 // the activity manager's locks. The new state is determined based on the
1801 // state *now* of the relevant activity record. The object is passed to
1802 // the handler solely for logging detail, not to be consulted/modified.
1803 final boolean nextState = r != null && r.immersive;
1804 mH.post(() -> {
1805 if (mUpdateLock.isHeld() != nextState) {
1806 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1807 "Applying new update lock state '" + nextState + "' for " + r);
1808 if (nextState) {
1809 mUpdateLock.acquire();
1810 } else {
1811 mUpdateLock.release();
1812 }
1813 }
1814 });
1815 }
1816
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 @Override
1818 public boolean isImmersive(IBinder token) {
1819 synchronized (mGlobalLock) {
1820 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r == null) {
1822 throw new IllegalArgumentException();
1823 }
1824 return r.immersive;
1825 }
1826 }
1827
1828 @Override
1829 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001830 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001831 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001832 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 return (r != null) ? r.immersive : false;
1834 }
1835 }
1836
1837 @Override
1838 public void overridePendingTransition(IBinder token, String packageName,
1839 int enterAnim, int exitAnim) {
1840 synchronized (mGlobalLock) {
1841 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1842 if (self == null) {
1843 return;
1844 }
1845
1846 final long origId = Binder.clearCallingIdentity();
1847
1848 if (self.isState(
1849 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001850 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001851 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 }
1853
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857
1858 @Override
1859 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001862 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001863 if (r == null) {
1864 return ActivityManager.COMPAT_MODE_UNKNOWN;
1865 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001866 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 }
1868 }
1869
1870 @Override
1871 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001873 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001874 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001876 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001877 if (r == null) {
1878 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1879 return;
1880 }
1881 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001882 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001883 }
1884 }
1885
1886 @Override
1887 public int getLaunchedFromUid(IBinder activityToken) {
1888 ActivityRecord srec;
1889 synchronized (mGlobalLock) {
1890 srec = ActivityRecord.forTokenLocked(activityToken);
1891 }
1892 if (srec == null) {
1893 return -1;
1894 }
1895 return srec.launchedFromUid;
1896 }
1897
1898 @Override
1899 public String getLaunchedFromPackage(IBinder activityToken) {
1900 ActivityRecord srec;
1901 synchronized (mGlobalLock) {
1902 srec = ActivityRecord.forTokenLocked(activityToken);
1903 }
1904 if (srec == null) {
1905 return null;
1906 }
1907 return srec.launchedFromPackage;
1908 }
1909
1910 @Override
1911 public boolean convertFromTranslucent(IBinder token) {
1912 final long origId = Binder.clearCallingIdentity();
1913 try {
1914 synchronized (mGlobalLock) {
1915 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1916 if (r == null) {
1917 return false;
1918 }
1919 final boolean translucentChanged = r.changeWindowTranslucency(true);
1920 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001921 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001923 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 return translucentChanged;
1925 }
1926 } finally {
1927 Binder.restoreCallingIdentity(origId);
1928 }
1929 }
1930
1931 @Override
1932 public boolean convertToTranslucent(IBinder token, Bundle options) {
1933 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1934 final long origId = Binder.clearCallingIdentity();
1935 try {
1936 synchronized (mGlobalLock) {
1937 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1938 if (r == null) {
1939 return false;
1940 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001941 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 int index = task.mActivities.lastIndexOf(r);
1943 if (index > 0) {
1944 ActivityRecord under = task.mActivities.get(index - 1);
1945 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1946 }
1947 final boolean translucentChanged = r.changeWindowTranslucency(false);
1948 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001949 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001951 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001952 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001953 return translucentChanged;
1954 }
1955 } finally {
1956 Binder.restoreCallingIdentity(origId);
1957 }
1958 }
1959
1960 @Override
1961 public void notifyActivityDrawn(IBinder token) {
1962 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001964 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001966 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 }
1968 }
1969 }
1970
1971 @Override
1972 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1973 synchronized (mGlobalLock) {
1974 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1975 if (r == null) {
1976 return;
1977 }
1978 r.reportFullyDrawnLocked(restoredFromBundle);
1979 }
1980 }
1981
1982 @Override
1983 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1984 synchronized (mGlobalLock) {
1985 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1986 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1987 return stack.mDisplayId;
1988 }
1989 return DEFAULT_DISPLAY;
1990 }
1991 }
1992
1993 @Override
1994 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 long ident = Binder.clearCallingIdentity();
1997 try {
1998 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001999 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002001 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002002 }
2003 return null;
2004 }
2005 } finally {
2006 Binder.restoreCallingIdentity(ident);
2007 }
2008 }
2009
2010 @Override
2011 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2014 final long callingId = Binder.clearCallingIdentity();
2015 try {
2016 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002017 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002018 if (stack == null) {
2019 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2020 return;
2021 }
2022 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002023 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002024 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 }
2026 }
2027 } finally {
2028 Binder.restoreCallingIdentity(callingId);
2029 }
2030 }
2031
2032 @Override
2033 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002034 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2036 final long callingId = Binder.clearCallingIdentity();
2037 try {
2038 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002040 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002041 if (task == null) {
2042 return;
2043 }
2044 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002045 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 }
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(callingId);
2051 }
2052 }
2053
2054 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002055 public void restartActivityProcessIfVisible(IBinder activityToken) {
2056 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2057 final long callingId = Binder.clearCallingIdentity();
2058 try {
2059 synchronized (mGlobalLock) {
2060 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2061 if (r == null) {
2062 return;
2063 }
2064 r.restartProcessIfVisible();
2065 }
2066 } finally {
2067 Binder.restoreCallingIdentity(callingId);
2068 }
2069 }
2070
2071 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002073 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 synchronized (mGlobalLock) {
2075 final long ident = Binder.clearCallingIdentity();
2076 try {
2077 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2078 "remove-task");
2079 } finally {
2080 Binder.restoreCallingIdentity(ident);
2081 }
2082 }
2083 }
2084
2085 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002086 public void removeAllVisibleRecentTasks() {
2087 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2088 synchronized (mGlobalLock) {
2089 final long ident = Binder.clearCallingIdentity();
2090 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002091 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002092 } finally {
2093 Binder.restoreCallingIdentity(ident);
2094 }
2095 }
2096 }
2097
2098 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2100 synchronized (mGlobalLock) {
2101 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2102 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002103 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002104 }
2105 }
2106 return false;
2107 }
2108
2109 @Override
2110 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2111 Intent resultData) {
2112
2113 synchronized (mGlobalLock) {
2114 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2115 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002116 return r.getActivityStack().navigateUpToLocked(
2117 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 }
2119 return false;
2120 }
2121 }
2122
2123 /**
2124 * Attempts to move a task backwards in z-order (the order of activities within the task is
2125 * unchanged).
2126 *
2127 * There are several possible results of this call:
2128 * - if the task is locked, then we will show the lock toast
2129 * - if there is a task behind the provided task, then that task is made visible and resumed as
2130 * this task is moved to the back
2131 * - otherwise, if there are no other tasks in the stack:
2132 * - if this task is in the pinned stack, then we remove the stack completely, which will
2133 * have the effect of moving the task to the top or bottom of the fullscreen stack
2134 * (depending on whether it is visible)
2135 * - otherwise, we simply return home and hide this task
2136 *
2137 * @param token A reference to the activity we wish to move
2138 * @param nonRoot If false then this only works if the activity is the root
2139 * of a task; if true it will work for any activity in a task.
2140 * @return Returns true if the move completed, false if not.
2141 */
2142 @Override
2143 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002144 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 synchronized (mGlobalLock) {
2146 final long origId = Binder.clearCallingIdentity();
2147 try {
2148 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002149 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002150 if (task != null) {
2151 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2152 }
2153 } finally {
2154 Binder.restoreCallingIdentity(origId);
2155 }
2156 }
2157 return false;
2158 }
2159
2160 @Override
2161 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 long ident = Binder.clearCallingIdentity();
2164 Rect rect = new Rect();
2165 try {
2166 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002167 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2169 if (task == null) {
2170 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2171 return rect;
2172 }
2173 if (task.getStack() != null) {
2174 // Return the bounds from window manager since it will be adjusted for various
2175 // things like the presense of a docked stack for tasks that aren't resizeable.
2176 task.getWindowContainerBounds(rect);
2177 } else {
2178 // Task isn't in window manager yet since it isn't associated with a stack.
2179 // Return the persist value from activity manager
2180 if (!task.matchParentBounds()) {
2181 rect.set(task.getBounds());
2182 } else if (task.mLastNonFullscreenBounds != null) {
2183 rect.set(task.mLastNonFullscreenBounds);
2184 }
2185 }
2186 }
2187 } finally {
2188 Binder.restoreCallingIdentity(ident);
2189 }
2190 return rect;
2191 }
2192
2193 @Override
2194 public ActivityManager.TaskDescription getTaskDescription(int id) {
2195 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002196 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002198 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2200 if (tr != null) {
2201 return tr.lastTaskDescription;
2202 }
2203 }
2204 return null;
2205 }
2206
2207 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002208 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2209 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2210 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2211 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2212 return;
2213 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002214 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002215 synchronized (mGlobalLock) {
2216 final long ident = Binder.clearCallingIdentity();
2217 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002218 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002219 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002220 if (task == null) {
2221 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2222 return;
2223 }
2224
2225 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2226 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2227
2228 if (!task.isActivityTypeStandardOrUndefined()) {
2229 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2230 + " non-standard task " + taskId + " to windowing mode="
2231 + windowingMode);
2232 }
2233
2234 final ActivityStack stack = task.getStack();
2235 if (toTop) {
2236 stack.moveToFront("setTaskWindowingMode", task);
2237 }
2238 stack.setWindowingMode(windowingMode);
2239 } finally {
2240 Binder.restoreCallingIdentity(ident);
2241 }
2242 }
2243 }
2244
2245 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 ActivityRecord r = getCallingRecordLocked(token);
2249 return r != null ? r.info.packageName : null;
2250 }
2251 }
2252
2253 @Override
2254 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002255 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002256 ActivityRecord r = getCallingRecordLocked(token);
2257 return r != null ? r.intent.getComponent() : null;
2258 }
2259 }
2260
2261 private ActivityRecord getCallingRecordLocked(IBinder token) {
2262 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2263 if (r == null) {
2264 return null;
2265 }
2266 return r.resultTo;
2267 }
2268
2269 @Override
2270 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002271 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002272
2273 synchronized (mGlobalLock) {
2274 final long origId = Binder.clearCallingIdentity();
2275 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002276 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 } finally {
2278 Binder.restoreCallingIdentity(origId);
2279 }
2280 }
2281 }
2282
2283 /**
2284 * TODO: Add mController hook
2285 */
2286 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002287 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2288 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290
2291 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2292 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002293 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2294 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 }
2296 }
2297
Ricky Waiaca8a772019-04-04 16:01:06 +01002298 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2299 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 boolean fromRecents) {
2301
Ricky Waiaca8a772019-04-04 16:01:06 +01002302 final int callingPid = Binder.getCallingPid();
2303 final int callingUid = Binder.getCallingUid();
2304 if (!isSameApp(callingUid, callingPackage)) {
2305 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2306 + Binder.getCallingPid() + " as package " + callingPackage;
2307 Slog.w(TAG, msg);
2308 throw new SecurityException(msg);
2309 }
2310 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 SafeActivityOptions.abort(options);
2312 return;
2313 }
2314 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002315 WindowProcessController callerApp = null;
2316 if (appThread != null) {
2317 callerApp = getProcessController(appThread);
2318 }
2319 final ActivityStarter starter = getActivityStartController().obtainStarter(
2320 null /* intent */, "moveTaskToFront");
2321 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2322 -1, callerApp, null, false, null)) {
2323 boolean abort = !isBackgroundActivityStartsEnabled();
2324 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2325 if (abort) {
2326 return;
2327 }
2328 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002330 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002331 if (task == null) {
2332 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002333 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 return;
2335 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002336 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002337 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002338 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 return;
2340 }
2341 ActivityOptions realOptions = options != null
2342 ? options.getOptions(mStackSupervisor)
2343 : null;
2344 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2345 false /* forceNonResizable */);
2346
2347 final ActivityRecord topActivity = task.getTopActivity();
2348 if (topActivity != null) {
2349
2350 // We are reshowing a task, use a starting window to hide the initial draw delay
2351 // so the transition can start earlier.
2352 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2353 true /* taskSwitch */, fromRecents);
2354 }
2355 } finally {
2356 Binder.restoreCallingIdentity(origId);
2357 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358 }
2359
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 /**
2361 * Return true if callingUid is system, or packageName belongs to that callingUid.
2362 */
2363 boolean isSameApp(int callingUid, @Nullable String packageName) {
2364 try {
2365 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2366 if (packageName == null) {
2367 return false;
2368 }
2369 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2370 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2371 UserHandle.getUserId(callingUid));
2372 return UserHandle.isSameApp(callingUid, uid);
2373 }
2374 } catch (RemoteException e) {
2375 // Should not happen
2376 }
2377 return true;
2378 }
2379
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002380 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2381 int callingPid, int callingUid, String name) {
2382 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2383 return true;
2384 }
2385
2386 if (getRecentTasks().isCallerRecents(sourceUid)) {
2387 return true;
2388 }
2389
2390 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2391 if (perm == PackageManager.PERMISSION_GRANTED) {
2392 return true;
2393 }
2394 if (checkAllowAppSwitchUid(sourceUid)) {
2395 return true;
2396 }
2397
2398 // If the actual IPC caller is different from the logical source, then
2399 // also see if they are allowed to control app switches.
2400 if (callingUid != -1 && callingUid != sourceUid) {
2401 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2402 if (perm == PackageManager.PERMISSION_GRANTED) {
2403 return true;
2404 }
2405 if (checkAllowAppSwitchUid(callingUid)) {
2406 return true;
2407 }
2408 }
2409
2410 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2411 return false;
2412 }
2413
2414 private boolean checkAllowAppSwitchUid(int uid) {
2415 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2416 if (types != null) {
2417 for (int i = types.size() - 1; i >= 0; i--) {
2418 if (types.valueAt(i).intValue() == uid) {
2419 return true;
2420 }
2421 }
2422 }
2423 return false;
2424 }
2425
2426 @Override
2427 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2428 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2429 "setActivityController()");
2430 synchronized (mGlobalLock) {
2431 mController = controller;
2432 mControllerIsAMonkey = imAMonkey;
2433 Watchdog.getInstance().setActivityController(controller);
2434 }
2435 }
2436
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002437 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 synchronized (mGlobalLock) {
2439 return mController != null && mControllerIsAMonkey;
2440 }
2441 }
2442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002443 @Override
2444 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2445 synchronized (mGlobalLock) {
2446 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2447 }
2448 }
2449
2450 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002451 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2452 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2453 }
2454
2455 @Override
2456 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2457 @WindowConfiguration.ActivityType int ignoreActivityType,
2458 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2459 final int callingUid = Binder.getCallingUid();
2460 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2461
2462 synchronized (mGlobalLock) {
2463 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2464
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002465 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002466 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002467 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002468 ignoreWindowingMode, callingUid, allowed);
2469 }
2470
2471 return list;
2472 }
2473
2474 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2476 synchronized (mGlobalLock) {
2477 final long origId = Binder.clearCallingIdentity();
2478 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2479 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002480 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002481 }
2482 Binder.restoreCallingIdentity(origId);
2483 }
2484 }
2485
2486 @Override
2487 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002488 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 ActivityStack stack = ActivityRecord.getStackLocked(token);
2490 if (stack != null) {
2491 return stack.willActivityBeVisibleLocked(token);
2492 }
2493 return false;
2494 }
2495 }
2496
2497 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002498 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002499 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002500 synchronized (mGlobalLock) {
2501 final long ident = Binder.clearCallingIdentity();
2502 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002503 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 if (task == null) {
2505 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2506 return;
2507 }
2508
2509 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2510 + " to stackId=" + stackId + " toTop=" + toTop);
2511
Wale Ogunwaled32da472018-11-16 07:19:28 -08002512 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002513 if (stack == null) {
2514 throw new IllegalStateException(
2515 "moveTaskToStack: No stack for stackId=" + stackId);
2516 }
2517 if (!stack.isActivityTypeStandardOrUndefined()) {
2518 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2519 + taskId + " to stack " + stackId);
2520 }
2521 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002522 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002523 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2524 }
2525 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2526 "moveTaskToStack");
2527 } finally {
2528 Binder.restoreCallingIdentity(ident);
2529 }
2530 }
2531 }
2532
2533 @Override
2534 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2535 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002536 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002537
2538 final long ident = Binder.clearCallingIdentity();
2539 try {
2540 synchronized (mGlobalLock) {
2541 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002542 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 if (stack == null) {
2544 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2545 return;
2546 }
2547 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2548 throw new IllegalArgumentException("Stack: " + stackId
2549 + " doesn't support animated resize.");
2550 }
2551 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2552 animationDuration, false /* fromFullscreen */);
2553 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002554 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 if (stack == null) {
2556 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2557 return;
2558 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002559 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002560 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2561 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2562 }
2563 }
2564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568
wilsonshih5c4cf522019-01-25 09:03:47 +08002569 @Override
2570 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2571 int animationDuration) {
2572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2573
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
2576 synchronized (mGlobalLock) {
2577 if (xOffset == 0 && yOffset == 0) {
2578 return;
2579 }
2580 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2581 if (stack == null) {
2582 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2583 return;
2584 }
2585 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2586 throw new IllegalArgumentException("Stack: " + stackId
2587 + " doesn't support animated resize.");
2588 }
2589 final Rect destBounds = new Rect();
2590 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002591 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002592 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2593 return;
2594 }
2595 destBounds.offset(xOffset, yOffset);
2596 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2597 animationDuration, false /* fromFullscreen */);
2598 }
2599 } finally {
2600 Binder.restoreCallingIdentity(ident);
2601 }
2602 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 /**
2604 * Moves the specified task to the primary-split-screen stack.
2605 *
2606 * @param taskId Id of task to move.
2607 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2608 * exist already. See
2609 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2610 * and
2611 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2612 * @param toTop If the task and stack should be moved to the top.
2613 * @param animate Whether we should play an animation for the moving the task.
2614 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2615 * stack. Pass {@code null} to use default bounds.
2616 * @param showRecents If the recents activity should be shown on the other side of the task
2617 * going into split-screen mode.
2618 */
2619 @Override
2620 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2621 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002622 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002623 "setTaskWindowingModeSplitScreenPrimary()");
2624 synchronized (mGlobalLock) {
2625 final long ident = Binder.clearCallingIdentity();
2626 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002627 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002628 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629 if (task == null) {
2630 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2631 return false;
2632 }
2633 if (DEBUG_STACK) Slog.d(TAG_STACK,
2634 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2635 + " to createMode=" + createMode + " toTop=" + toTop);
2636 if (!task.isActivityTypeStandardOrUndefined()) {
2637 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2638 + " non-standard task " + taskId + " to split-screen windowing mode");
2639 }
2640
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002641 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002642 final int windowingMode = task.getWindowingMode();
2643 final ActivityStack stack = task.getStack();
2644 if (toTop) {
2645 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2646 }
2647 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002648 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2649 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002650 return windowingMode != task.getWindowingMode();
2651 } finally {
2652 Binder.restoreCallingIdentity(ident);
2653 }
2654 }
2655 }
2656
2657 /**
2658 * Removes stacks in the input windowing modes from the system if they are of activity type
2659 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2660 */
2661 @Override
2662 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002663 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 "removeStacksInWindowingModes()");
2665
2666 synchronized (mGlobalLock) {
2667 final long ident = Binder.clearCallingIdentity();
2668 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002669 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002670 } finally {
2671 Binder.restoreCallingIdentity(ident);
2672 }
2673 }
2674 }
2675
2676 @Override
2677 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002678 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002679 "removeStacksWithActivityTypes()");
2680
2681 synchronized (mGlobalLock) {
2682 final long ident = Binder.clearCallingIdentity();
2683 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002684 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 } finally {
2686 Binder.restoreCallingIdentity(ident);
2687 }
2688 }
2689 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002690
2691 @Override
2692 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2693 int userId) {
2694 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002695 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2696 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002697 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002698 final boolean detailed = checkGetTasksPermission(
2699 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2700 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 == PackageManager.PERMISSION_GRANTED;
2702
2703 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002704 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002705 callingUid);
2706 }
2707 }
2708
2709 @Override
2710 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002711 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002712 long ident = Binder.clearCallingIdentity();
2713 try {
2714 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002715 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716 }
2717 } finally {
2718 Binder.restoreCallingIdentity(ident);
2719 }
2720 }
2721
2722 @Override
2723 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002725 long ident = Binder.clearCallingIdentity();
2726 try {
2727 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002728 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729 }
2730 } finally {
2731 Binder.restoreCallingIdentity(ident);
2732 }
2733 }
2734
2735 @Override
2736 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002738 final long callingUid = Binder.getCallingUid();
2739 final long origId = Binder.clearCallingIdentity();
2740 try {
2741 synchronized (mGlobalLock) {
2742 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002743 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002744 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2745 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2746 }
2747 } finally {
2748 Binder.restoreCallingIdentity(origId);
2749 }
2750 }
2751
2752 @Override
2753 public void startLockTaskModeByToken(IBinder token) {
2754 synchronized (mGlobalLock) {
2755 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2756 if (r == null) {
2757 return;
2758 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002759 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 }
2761 }
2762
2763 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002764 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002765 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 // This makes inner call to look as if it was initiated by system.
2767 long ident = Binder.clearCallingIdentity();
2768 try {
2769 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002770 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002771 MATCH_TASK_IN_STACKS_ONLY);
2772 if (task == null) {
2773 return;
2774 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775
2776 // When starting lock task mode the stack must be in front and focused
2777 task.getStack().moveToFront("startSystemLockTaskMode");
2778 startLockTaskModeLocked(task, true /* isSystemCaller */);
2779 }
2780 } finally {
2781 Binder.restoreCallingIdentity(ident);
2782 }
2783 }
2784
2785 @Override
2786 public void stopLockTaskModeByToken(IBinder token) {
2787 synchronized (mGlobalLock) {
2788 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2789 if (r == null) {
2790 return;
2791 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002792 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 }
2794 }
2795
2796 /**
2797 * This API should be called by SystemUI only when user perform certain action to dismiss
2798 * lock task mode. We should only dismiss pinned lock task mode in this case.
2799 */
2800 @Override
2801 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002802 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002803 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2804 }
2805
2806 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2807 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2808 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2809 return;
2810 }
2811
Wale Ogunwaled32da472018-11-16 07:19:28 -08002812 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 if (stack == null || task != stack.topTask()) {
2814 throw new IllegalArgumentException("Invalid task, not in foreground");
2815 }
2816
2817 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2818 // system or a specific app.
2819 // * System-initiated requests will only start the pinned mode (screen pinning)
2820 // * App-initiated requests
2821 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2822 // - will start the pinned mode, otherwise
2823 final int callingUid = Binder.getCallingUid();
2824 long ident = Binder.clearCallingIdentity();
2825 try {
2826 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002827 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002829 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 } finally {
2831 Binder.restoreCallingIdentity(ident);
2832 }
2833 }
2834
2835 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2836 final int callingUid = Binder.getCallingUid();
2837 long ident = Binder.clearCallingIdentity();
2838 try {
2839 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002840 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 }
2842 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2843 // task and jumping straight into a call in the case of emergency call back.
2844 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2845 if (tm != null) {
2846 tm.showInCallScreen(false);
2847 }
2848 } finally {
2849 Binder.restoreCallingIdentity(ident);
2850 }
2851 }
2852
2853 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002854 public void updateLockTaskPackages(int userId, String[] packages) {
2855 final int callingUid = Binder.getCallingUid();
2856 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2857 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2858 "updateLockTaskPackages()");
2859 }
2860 synchronized (this) {
2861 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2862 + Arrays.toString(packages));
2863 getLockTaskController().updateLockTaskPackages(userId, packages);
2864 }
2865 }
2866
2867 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 public boolean isInLockTaskMode() {
2869 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2870 }
2871
2872 @Override
2873 public int getLockTaskModeState() {
2874 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002875 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 }
2877 }
2878
2879 @Override
2880 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2881 synchronized (mGlobalLock) {
2882 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2883 if (r != null) {
2884 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002885 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002886 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002887 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002888 }
2889 }
2890 }
2891
2892 @Override
2893 public Bundle getActivityOptions(IBinder token) {
2894 final long origId = Binder.clearCallingIdentity();
2895 try {
2896 synchronized (mGlobalLock) {
2897 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2898 if (r != null) {
2899 final ActivityOptions activityOptions = r.takeOptionsLocked();
2900 return activityOptions == null ? null : activityOptions.toBundle();
2901 }
2902 return null;
2903 }
2904 } finally {
2905 Binder.restoreCallingIdentity(origId);
2906 }
2907 }
2908
2909 @Override
2910 public List<IBinder> getAppTasks(String callingPackage) {
2911 int callingUid = Binder.getCallingUid();
2912 long ident = Binder.clearCallingIdentity();
2913 try {
2914 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002915 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 }
2917 } finally {
2918 Binder.restoreCallingIdentity(ident);
2919 }
2920 }
2921
2922 @Override
2923 public void finishVoiceTask(IVoiceInteractionSession session) {
2924 synchronized (mGlobalLock) {
2925 final long origId = Binder.clearCallingIdentity();
2926 try {
2927 // TODO: VI Consider treating local voice interactions and voice tasks
2928 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002929 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 } finally {
2931 Binder.restoreCallingIdentity(origId);
2932 }
2933 }
2934
2935 }
2936
2937 @Override
2938 public boolean isTopOfTask(IBinder token) {
2939 synchronized (mGlobalLock) {
2940 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002941 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 }
2943 }
2944
2945 @Override
2946 public void notifyLaunchTaskBehindComplete(IBinder token) {
2947 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2948 }
2949
2950 @Override
2951 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002952 mH.post(() -> {
2953 synchronized (mGlobalLock) {
2954 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002955 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002956 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002957 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002958 } catch (RemoteException e) {
2959 }
2960 }
2961 }
2962
2963 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965
2966 /** Called from an app when assist data is ready. */
2967 @Override
2968 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2969 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002970 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 synchronized (pae) {
2972 pae.result = extras;
2973 pae.structure = structure;
2974 pae.content = content;
2975 if (referrer != null) {
2976 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2977 }
2978 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002979 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002980 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2981 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 structure.setHomeActivity(pae.isHome);
2983 }
2984 pae.haveResult = true;
2985 pae.notifyAll();
2986 if (pae.intent == null && pae.receiver == null) {
2987 // Caller is just waiting for the result.
2988 return;
2989 }
2990 }
2991 // We are now ready to launch the assist activity.
2992 IAssistDataReceiver sendReceiver = null;
2993 Bundle sendBundle = null;
2994 synchronized (mGlobalLock) {
2995 buildAssistBundleLocked(pae, extras);
2996 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002997 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002998 if (!exists) {
2999 // Timed out.
3000 return;
3001 }
3002
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003003 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 // Caller wants result sent back to them.
3005 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003006 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3007 pae.activity.getTaskRecord().taskId);
3008 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3009 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3011 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3012 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3013 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3014 }
3015 }
3016 if (sendReceiver != null) {
3017 try {
3018 sendReceiver.onHandleAssistData(sendBundle);
3019 } catch (RemoteException e) {
3020 }
3021 return;
3022 }
3023
3024 final long ident = Binder.clearCallingIdentity();
3025 try {
3026 if (TextUtils.equals(pae.intent.getAction(),
3027 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3028 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003029
3030 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 } else {
3032 pae.intent.replaceExtras(pae.extras);
3033 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3034 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3035 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003036 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037
3038 try {
3039 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3040 } catch (ActivityNotFoundException e) {
3041 Slog.w(TAG, "No activity to handle assist action.", e);
3042 }
3043 }
3044 } finally {
3045 Binder.restoreCallingIdentity(ident);
3046 }
3047 }
3048
Marvin Ramin830d4e32019-03-12 13:16:58 +01003049 /**
3050 * Workaround for historical API which starts the Assist service with a non-foreground
3051 * {@code startService()} call.
3052 */
3053 private void startVoiceInteractionServiceAsUser(
3054 Intent intent, int userHandle, String reason) {
3055 // Resolve the intent to find out which package we need to whitelist.
3056 ResolveInfo resolveInfo =
3057 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3058 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3059 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3060 return;
3061 }
3062 intent.setPackage(resolveInfo.serviceInfo.packageName);
3063
3064 // Whitelist background services temporarily.
3065 LocalServices.getService(DeviceIdleController.LocalService.class)
3066 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3067 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3068
3069 // Finally, try to start the service.
3070 try {
3071 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3072 } catch (RuntimeException e) {
3073 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3074 }
3075 }
3076
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 @Override
3078 public int addAppTask(IBinder activityToken, Intent intent,
3079 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3080 final int callingUid = Binder.getCallingUid();
3081 final long callingIdent = Binder.clearCallingIdentity();
3082
3083 try {
3084 synchronized (mGlobalLock) {
3085 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3086 if (r == null) {
3087 throw new IllegalArgumentException("Activity does not exist; token="
3088 + activityToken);
3089 }
3090 ComponentName comp = intent.getComponent();
3091 if (comp == null) {
3092 throw new IllegalArgumentException("Intent " + intent
3093 + " must specify explicit component");
3094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 if (thumbnail.getWidth() != mThumbnailWidth
3096 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 throw new IllegalArgumentException("Bad thumbnail size: got "
3098 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003099 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100 }
3101 if (intent.getSelector() != null) {
3102 intent.setSelector(null);
3103 }
3104 if (intent.getSourceBounds() != null) {
3105 intent.setSourceBounds(null);
3106 }
3107 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3108 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3109 // The caller has added this as an auto-remove task... that makes no
3110 // sense, so turn off auto-remove.
3111 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3112 }
3113 }
3114 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3115 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3116 if (ainfo.applicationInfo.uid != callingUid) {
3117 throw new SecurityException(
3118 "Can't add task for another application: target uid="
3119 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3120 }
3121
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003122 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003124 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003126 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 // The app has too many tasks already and we can't add any more
3128 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3129 return INVALID_TASK_ID;
3130 }
3131 task.lastTaskDescription.copyFrom(description);
3132
3133 // TODO: Send the thumbnail to WM to store it.
3134
3135 return task.taskId;
3136 }
3137 } finally {
3138 Binder.restoreCallingIdentity(callingIdent);
3139 }
3140 }
3141
3142 @Override
3143 public Point getAppTaskThumbnailSize() {
3144 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003145 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 }
3147 }
3148
3149 @Override
3150 public void setTaskResizeable(int taskId, int resizeableMode) {
3151 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003152 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3154 if (task == null) {
3155 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3156 return;
3157 }
3158 task.setResizeMode(resizeableMode);
3159 }
3160 }
3161
3162 @Override
3163 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003164 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 long ident = Binder.clearCallingIdentity();
3166 try {
3167 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003168 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003169 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 if (task == null) {
3171 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3172 return;
3173 }
3174 // Place the task in the right stack if it isn't there already based on
3175 // the requested bounds.
3176 // The stack transition logic is:
3177 // - a null bounds on a freeform task moves that task to fullscreen
3178 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3179 // that task to freeform
3180 // - otherwise the task is not moved
3181 ActivityStack stack = task.getStack();
3182 if (!task.getWindowConfiguration().canResizeTask()) {
3183 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3184 }
3185 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3186 stack = stack.getDisplay().getOrCreateStack(
3187 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3188 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3189 stack = stack.getDisplay().getOrCreateStack(
3190 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3191 }
3192
3193 // Reparent the task to the right stack if necessary
3194 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3195 if (stack != task.getStack()) {
3196 // Defer resume until the task is resized below
3197 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3198 DEFER_RESUME, "resizeTask");
3199 preserveWindow = false;
3200 }
3201
3202 // After reparenting (which only resizes the task to the stack bounds), resize the
3203 // task to the actual bounds provided
3204 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3205 }
3206 } finally {
3207 Binder.restoreCallingIdentity(ident);
3208 }
3209 }
3210
3211 @Override
3212 public boolean releaseActivityInstance(IBinder token) {
3213 synchronized (mGlobalLock) {
3214 final long origId = Binder.clearCallingIdentity();
3215 try {
3216 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3217 if (r == null) {
3218 return false;
3219 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003220 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 } finally {
3222 Binder.restoreCallingIdentity(origId);
3223 }
3224 }
3225 }
3226
3227 @Override
3228 public void releaseSomeActivities(IApplicationThread appInt) {
3229 synchronized (mGlobalLock) {
3230 final long origId = Binder.clearCallingIdentity();
3231 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003232 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003233 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 } finally {
3235 Binder.restoreCallingIdentity(origId);
3236 }
3237 }
3238 }
3239
3240 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003241 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003242 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 != PackageManager.PERMISSION_GRANTED) {
3244 throw new SecurityException("Requires permission "
3245 + android.Manifest.permission.DEVICE_POWER);
3246 }
3247
3248 synchronized (mGlobalLock) {
3249 long ident = Binder.clearCallingIdentity();
3250 if (mKeyguardShown != keyguardShowing) {
3251 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003252 final Message msg = PooledLambda.obtainMessage(
3253 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3254 keyguardShowing);
3255 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 }
3257 try {
wilsonshih177261f2019-02-22 12:02:18 +08003258 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 } finally {
3260 Binder.restoreCallingIdentity(ident);
3261 }
3262 }
3263
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003264 mH.post(() -> {
3265 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3266 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3267 }
3268 });
3269 }
3270
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003271 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003272 mH.post(() -> {
3273 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3274 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3275 }
3276 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003277 }
3278
3279 @Override
3280 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003281 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3282 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283
3284 final File passedIconFile = new File(filePath);
3285 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3286 passedIconFile.getName());
3287 if (!legitIconFile.getPath().equals(filePath)
3288 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3289 throw new IllegalArgumentException("Bad file path: " + filePath
3290 + " passed for userId " + userId);
3291 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003292 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 }
3294
3295 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003296 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3298 final ActivityOptions activityOptions = safeOptions != null
3299 ? safeOptions.getOptions(mStackSupervisor)
3300 : null;
3301 if (activityOptions == null
3302 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3303 || activityOptions.getCustomInPlaceResId() == 0) {
3304 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3305 "with valid animation");
3306 }
lumark588a3e82018-07-20 18:53:54 +08003307 // Get top display of front most application.
3308 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3309 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003310 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3311 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3312 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003313 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003314 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003315 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003316 }
3317
3318 @Override
3319 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003320 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 synchronized (mGlobalLock) {
3322 final long ident = Binder.clearCallingIdentity();
3323 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003324 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 if (stack == null) {
3326 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3327 return;
3328 }
3329 if (!stack.isActivityTypeStandardOrUndefined()) {
3330 throw new IllegalArgumentException(
3331 "Removing non-standard stack is not allowed.");
3332 }
3333 mStackSupervisor.removeStack(stack);
3334 } finally {
3335 Binder.restoreCallingIdentity(ident);
3336 }
3337 }
3338 }
3339
3340 @Override
3341 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003342 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343
3344 synchronized (mGlobalLock) {
3345 final long ident = Binder.clearCallingIdentity();
3346 try {
3347 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3348 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003349 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 } finally {
3351 Binder.restoreCallingIdentity(ident);
3352 }
3353 }
3354 }
3355
3356 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003357 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 synchronized (mGlobalLock) {
3359 long ident = Binder.clearCallingIdentity();
3360 try {
3361 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3362 if (r == null) {
3363 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003364 "toggleFreeformWindowingMode: No activity record matching token="
3365 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
3367
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003368 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003369 if (stack == null) {
3370 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3371 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 }
3373
Yunfan Chend967af82019-01-17 18:30:18 +09003374 if (!stack.inFreeformWindowingMode()
3375 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3376 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3377 + "toggle between fullscreen and freeform.");
3378 }
3379
3380 if (stack.inFreeformWindowingMode()) {
3381 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003382 } else if (stack.getParent().inFreeformWindowingMode()) {
3383 // If the window is on a freeform display, set it to undefined. It will be
3384 // resolved to freeform and it can adjust windowing mode when the display mode
3385 // changes in runtime.
3386 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003387 } else {
3388 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3389 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 } finally {
3391 Binder.restoreCallingIdentity(ident);
3392 }
3393 }
3394 }
3395
3396 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3397 @Override
3398 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003401 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 }
3403
3404 /** Unregister a task stack listener so that it stops receiving callbacks. */
3405 @Override
3406 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003407 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003409 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 }
3411
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 @Override
3413 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3414 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3415 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3416 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3417 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3418 }
3419
3420 @Override
3421 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3422 IBinder activityToken, int flags) {
3423 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3424 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3425 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3426 }
3427
3428 @Override
3429 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3430 Bundle args) {
3431 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3432 true /* focused */, true /* newSessionId */, userHandle, args,
3433 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3434 }
3435
3436 @Override
3437 public Bundle getAssistContextExtras(int requestType) {
3438 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3439 null, null, true /* focused */, true /* newSessionId */,
3440 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3441 if (pae == null) {
3442 return null;
3443 }
3444 synchronized (pae) {
3445 while (!pae.haveResult) {
3446 try {
3447 pae.wait();
3448 } catch (InterruptedException e) {
3449 }
3450 }
3451 }
3452 synchronized (mGlobalLock) {
3453 buildAssistBundleLocked(pae, pae.result);
3454 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003455 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457 return pae.extras;
3458 }
3459
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003460 /**
3461 * Binder IPC calls go through the public entry point.
3462 * This can be called with or without the global lock held.
3463 */
3464 private static int checkCallingPermission(String permission) {
3465 return checkPermission(
3466 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3467 }
3468
3469 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003470 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003471 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3472 mAmInternal.enforceCallingPermission(permission, func);
3473 }
3474 }
3475
3476 @VisibleForTesting
3477 int checkGetTasksPermission(String permission, int pid, int uid) {
3478 return checkPermission(permission, pid, uid);
3479 }
3480
3481 static int checkPermission(String permission, int pid, int uid) {
3482 if (permission == null) {
3483 return PackageManager.PERMISSION_DENIED;
3484 }
3485 return checkComponentPermission(permission, pid, uid, -1, true);
3486 }
3487
Wale Ogunwale214f3482018-10-04 11:00:47 -07003488 public static int checkComponentPermission(String permission, int pid, int uid,
3489 int owningUid, boolean exported) {
3490 return ActivityManagerService.checkComponentPermission(
3491 permission, pid, uid, owningUid, exported);
3492 }
3493
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003494 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3495 if (getRecentTasks().isCallerRecents(callingUid)) {
3496 // Always allow the recents component to get tasks
3497 return true;
3498 }
3499
3500 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3501 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3502 if (!allowed) {
3503 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3504 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3505 // Temporary compatibility: some existing apps on the system image may
3506 // still be requesting the old permission and not switched to the new
3507 // one; if so, we'll still allow them full access. This means we need
3508 // to see if they are holding the old permission and are a system app.
3509 try {
3510 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3511 allowed = true;
3512 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3513 + " is using old GET_TASKS but privileged; allowing");
3514 }
3515 } catch (RemoteException e) {
3516 }
3517 }
3518 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3519 + " does not hold REAL_GET_TASKS; limiting output");
3520 }
3521 return allowed;
3522 }
3523
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3525 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3526 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3527 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003528 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003529 "enqueueAssistContext()");
3530
3531 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003532 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003533 if (activity == null) {
3534 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3535 return null;
3536 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003537 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3539 return null;
3540 }
3541 if (focused) {
3542 if (activityToken != null) {
3543 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3544 if (activity != caller) {
3545 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3546 + " is not current top " + activity);
3547 return null;
3548 }
3549 }
3550 } else {
3551 activity = ActivityRecord.forTokenLocked(activityToken);
3552 if (activity == null) {
3553 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3554 + " couldn't be found");
3555 return null;
3556 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003557 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3559 return null;
3560 }
3561 }
3562
3563 PendingAssistExtras pae;
3564 Bundle extras = new Bundle();
3565 if (args != null) {
3566 extras.putAll(args);
3567 }
3568 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003569 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570
3571 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3572 userHandle);
3573 pae.isHome = activity.isActivityTypeHome();
3574
3575 // Increment the sessionId if necessary
3576 if (newSessionId) {
3577 mViSessionId++;
3578 }
3579 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003580 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3581 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003582 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003583 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 } catch (RemoteException e) {
3585 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3586 return null;
3587 }
3588 return pae;
3589 }
3590 }
3591
3592 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3593 if (result != null) {
3594 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3595 }
3596 if (pae.hint != null) {
3597 pae.extras.putBoolean(pae.hint, true);
3598 }
3599 }
3600
3601 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3602 IAssistDataReceiver receiver;
3603 synchronized (mGlobalLock) {
3604 mPendingAssistExtras.remove(pae);
3605 receiver = pae.receiver;
3606 }
3607 if (receiver != null) {
3608 // Caller wants result sent back to them.
3609 Bundle sendBundle = new Bundle();
3610 // At least return the receiver extras
3611 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3612 try {
3613 pae.receiver.onHandleAssistData(sendBundle);
3614 } catch (RemoteException e) {
3615 }
3616 }
3617 }
3618
3619 public class PendingAssistExtras extends Binder implements Runnable {
3620 public final ActivityRecord activity;
3621 public boolean isHome;
3622 public final Bundle extras;
3623 public final Intent intent;
3624 public final String hint;
3625 public final IAssistDataReceiver receiver;
3626 public final int userHandle;
3627 public boolean haveResult = false;
3628 public Bundle result = null;
3629 public AssistStructure structure = null;
3630 public AssistContent content = null;
3631 public Bundle receiverExtras;
3632
3633 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3634 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3635 int _userHandle) {
3636 activity = _activity;
3637 extras = _extras;
3638 intent = _intent;
3639 hint = _hint;
3640 receiver = _receiver;
3641 receiverExtras = _receiverExtras;
3642 userHandle = _userHandle;
3643 }
3644
3645 @Override
3646 public void run() {
3647 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3648 synchronized (this) {
3649 haveResult = true;
3650 notifyAll();
3651 }
3652 pendingAssistExtrasTimedOut(this);
3653 }
3654 }
3655
3656 @Override
3657 public boolean isAssistDataAllowedOnCurrentActivity() {
3658 int userId;
3659 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003660 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003661 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3662 return false;
3663 }
3664
3665 final ActivityRecord activity = focusedStack.getTopActivity();
3666 if (activity == null) {
3667 return false;
3668 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003669 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003670 }
3671 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3672 }
3673
3674 @Override
3675 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3676 long ident = Binder.clearCallingIdentity();
3677 try {
3678 synchronized (mGlobalLock) {
3679 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003680 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 if (top != caller) {
3682 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3683 + " is not current top " + top);
3684 return false;
3685 }
3686 if (!top.nowVisible) {
3687 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3688 + " is not visible");
3689 return false;
3690 }
3691 }
3692 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3693 token);
3694 } finally {
3695 Binder.restoreCallingIdentity(ident);
3696 }
3697 }
3698
3699 @Override
3700 public boolean isRootVoiceInteraction(IBinder token) {
3701 synchronized (mGlobalLock) {
3702 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3703 if (r == null) {
3704 return false;
3705 }
3706 return r.rootVoiceInteraction;
3707 }
3708 }
3709
Wale Ogunwalef6733932018-06-27 05:14:34 -07003710 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3711 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3712 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3713 if (activityToCallback == null) return;
3714 activityToCallback.setVoiceSessionLocked(voiceSession);
3715
3716 // Inform the activity
3717 try {
3718 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3719 voiceInteractor);
3720 long token = Binder.clearCallingIdentity();
3721 try {
3722 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3723 } finally {
3724 Binder.restoreCallingIdentity(token);
3725 }
3726 // TODO: VI Should we cache the activity so that it's easier to find later
3727 // rather than scan through all the stacks and activities?
3728 } catch (RemoteException re) {
3729 activityToCallback.clearVoiceSessionLocked();
3730 // TODO: VI Should this terminate the voice session?
3731 }
3732 }
3733
3734 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3735 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3736 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3737 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3738 boolean wasRunningVoice = mRunningVoice != null;
3739 mRunningVoice = session;
3740 if (!wasRunningVoice) {
3741 mVoiceWakeLock.acquire();
3742 updateSleepIfNeededLocked();
3743 }
3744 }
3745 }
3746
3747 void finishRunningVoiceLocked() {
3748 if (mRunningVoice != null) {
3749 mRunningVoice = null;
3750 mVoiceWakeLock.release();
3751 updateSleepIfNeededLocked();
3752 }
3753 }
3754
3755 @Override
3756 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3757 synchronized (mGlobalLock) {
3758 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3759 if (keepAwake) {
3760 mVoiceWakeLock.acquire();
3761 } else {
3762 mVoiceWakeLock.release();
3763 }
3764 }
3765 }
3766 }
3767
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 @Override
3769 public ComponentName getActivityClassForToken(IBinder token) {
3770 synchronized (mGlobalLock) {
3771 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3772 if (r == null) {
3773 return null;
3774 }
3775 return r.intent.getComponent();
3776 }
3777 }
3778
3779 @Override
3780 public String getPackageForToken(IBinder token) {
3781 synchronized (mGlobalLock) {
3782 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3783 if (r == null) {
3784 return null;
3785 }
3786 return r.packageName;
3787 }
3788 }
3789
3790 @Override
3791 public void showLockTaskEscapeMessage(IBinder token) {
3792 synchronized (mGlobalLock) {
3793 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3794 if (r == null) {
3795 return;
3796 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003797 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003798 }
3799 }
3800
3801 @Override
3802 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003803 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003804 final long token = Binder.clearCallingIdentity();
3805 try {
3806 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003807 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 }
3809 } finally {
3810 Binder.restoreCallingIdentity(token);
3811 }
3812 }
3813
3814 /**
3815 * Try to place task to provided position. The final position might be different depending on
3816 * current user and stacks state. The task will be moved to target stack if it's currently in
3817 * different stack.
3818 */
3819 @Override
3820 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003821 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 synchronized (mGlobalLock) {
3823 long ident = Binder.clearCallingIdentity();
3824 try {
3825 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3826 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003827 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 if (task == null) {
3829 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3830 + taskId);
3831 }
3832
Wale Ogunwaled32da472018-11-16 07:19:28 -08003833 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003834
3835 if (stack == null) {
3836 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3837 + stackId);
3838 }
3839 if (!stack.isActivityTypeStandardOrUndefined()) {
3840 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3841 + " the position of task " + taskId + " in/to non-standard stack");
3842 }
3843
3844 // TODO: Have the callers of this API call a separate reparent method if that is
3845 // what they intended to do vs. having this method also do reparenting.
3846 if (task.getStack() == stack) {
3847 // Change position in current stack.
3848 stack.positionChildAt(task, position);
3849 } else {
3850 // Reparent to new stack.
3851 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3852 !DEFER_RESUME, "positionTaskInStack");
3853 }
3854 } finally {
3855 Binder.restoreCallingIdentity(ident);
3856 }
3857 }
3858 }
3859
3860 @Override
3861 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3862 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3863 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3864 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3865 synchronized (mGlobalLock) {
3866 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3867 if (record == null) {
3868 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3869 + "found for: " + token);
3870 }
3871 record.setSizeConfigurations(horizontalSizeConfiguration,
3872 verticalSizeConfigurations, smallestSizeConfigurations);
3873 }
3874 }
3875
3876 /**
3877 * Dismisses split-screen multi-window mode.
3878 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3879 */
3880 @Override
3881 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003882 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3884 final long ident = Binder.clearCallingIdentity();
3885 try {
3886 synchronized (mGlobalLock) {
3887 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003888 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 if (stack == null) {
3890 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3891 return;
3892 }
3893
3894 if (toTop) {
3895 // Caller wants the current split-screen primary stack to be the top stack after
3896 // it goes fullscreen, so move it to the front.
3897 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003898 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003899 // In this case the current split-screen primary stack shouldn't be the top
3900 // stack after it goes fullscreen, but it current has focus, so we move the
3901 // focus to the top-most split-screen secondary stack next to it.
3902 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3903 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3904 if (otherStack != null) {
3905 otherStack.moveToFront("dismissSplitScreenMode_other");
3906 }
3907 }
3908
Evan Rosky10475742018-09-05 19:02:48 -07003909 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 }
3911 } finally {
3912 Binder.restoreCallingIdentity(ident);
3913 }
3914 }
3915
3916 /**
3917 * Dismisses Pip
3918 * @param animate True if the dismissal should be animated.
3919 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3920 * default animation duration should be used.
3921 */
3922 @Override
3923 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003924 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 final long ident = Binder.clearCallingIdentity();
3926 try {
3927 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003928 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003929 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 if (stack == null) {
3931 Slog.w(TAG, "dismissPip: pinned stack not found.");
3932 return;
3933 }
3934 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3935 throw new IllegalArgumentException("Stack: " + stack
3936 + " doesn't support animated resize.");
3937 }
3938 if (animate) {
3939 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3940 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3941 } else {
3942 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3943 }
3944 }
3945 } finally {
3946 Binder.restoreCallingIdentity(ident);
3947 }
3948 }
3949
3950 @Override
3951 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003952 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 synchronized (mGlobalLock) {
3954 mSuppressResizeConfigChanges = suppress;
3955 }
3956 }
3957
3958 /**
3959 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3960 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3961 * activity and clearing the task at the same time.
3962 */
3963 @Override
3964 // TODO: API should just be about changing windowing modes...
3965 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003966 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003967 "moveTasksToFullscreenStack()");
3968 synchronized (mGlobalLock) {
3969 final long origId = Binder.clearCallingIdentity();
3970 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003971 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003972 if (stack != null){
3973 if (!stack.isActivityTypeStandardOrUndefined()) {
3974 throw new IllegalArgumentException(
3975 "You can't move tasks from non-standard stacks.");
3976 }
3977 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(origId);
3981 }
3982 }
3983 }
3984
3985 /**
3986 * Moves the top activity in the input stackId to the pinned stack.
3987 *
3988 * @param stackId Id of stack to move the top activity to pinned stack.
3989 * @param bounds Bounds to use for pinned stack.
3990 *
3991 * @return True if the top activity of the input stack was successfully moved to the pinned
3992 * stack.
3993 */
3994 @Override
3995 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003996 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 "moveTopActivityToPinnedStack()");
3998 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003999 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4001 + "Device doesn't support picture-in-picture mode");
4002 }
4003
4004 long ident = Binder.clearCallingIdentity();
4005 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004006 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 } finally {
4008 Binder.restoreCallingIdentity(ident);
4009 }
4010 }
4011 }
4012
4013 @Override
4014 public boolean isInMultiWindowMode(IBinder token) {
4015 final long origId = Binder.clearCallingIdentity();
4016 try {
4017 synchronized (mGlobalLock) {
4018 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4019 if (r == null) {
4020 return false;
4021 }
4022 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4023 return r.inMultiWindowMode();
4024 }
4025 } finally {
4026 Binder.restoreCallingIdentity(origId);
4027 }
4028 }
4029
4030 @Override
4031 public boolean isInPictureInPictureMode(IBinder token) {
4032 final long origId = Binder.clearCallingIdentity();
4033 try {
4034 synchronized (mGlobalLock) {
4035 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4036 }
4037 } finally {
4038 Binder.restoreCallingIdentity(origId);
4039 }
4040 }
4041
4042 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004043 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4044 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 return false;
4046 }
4047
4048 // If we are animating to fullscreen then we have already dispatched the PIP mode
4049 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004050 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4051 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 }
4053
4054 @Override
4055 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4056 final long origId = Binder.clearCallingIdentity();
4057 try {
4058 synchronized (mGlobalLock) {
4059 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4060 "enterPictureInPictureMode", token, params);
4061
4062 // If the activity is already in picture in picture mode, then just return early
4063 if (isInPictureInPictureMode(r)) {
4064 return true;
4065 }
4066
4067 // Activity supports picture-in-picture, now check that we can enter PiP at this
4068 // point, if it is
4069 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4070 false /* beforeStopping */)) {
4071 return false;
4072 }
4073
4074 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004075 synchronized (mGlobalLock) {
4076 // Only update the saved args from the args that are set
4077 r.pictureInPictureArgs.copyOnlySet(params);
4078 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4079 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4080 // Adjust the source bounds by the insets for the transition down
4081 final Rect sourceBounds = new Rect(
4082 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004083 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004084 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004085 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004086 stack.setPictureInPictureAspectRatio(aspectRatio);
4087 stack.setPictureInPictureActions(actions);
4088 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4089 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4090 logPictureInPictureArgs(params);
4091 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004092 };
4093
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004094 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 // If the keyguard is showing or occluded, then try and dismiss it before
4096 // entering picture-in-picture (this will prompt the user to authenticate if the
4097 // device is currently locked).
4098 dismissKeyguard(token, new KeyguardDismissCallback() {
4099 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004100 public void onDismissSucceeded() {
4101 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102 }
4103 }, null /* message */);
4104 } else {
4105 // Enter picture in picture immediately otherwise
4106 enterPipRunnable.run();
4107 }
4108 return true;
4109 }
4110 } finally {
4111 Binder.restoreCallingIdentity(origId);
4112 }
4113 }
4114
4115 @Override
4116 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4117 final long origId = Binder.clearCallingIdentity();
4118 try {
4119 synchronized (mGlobalLock) {
4120 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4121 "setPictureInPictureParams", token, params);
4122
4123 // Only update the saved args from the args that are set
4124 r.pictureInPictureArgs.copyOnlySet(params);
4125 if (r.inPinnedWindowingMode()) {
4126 // If the activity is already in picture-in-picture, update the pinned stack now
4127 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4128 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004129 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004130 if (!stack.isAnimatingBoundsToFullscreen()) {
4131 stack.setPictureInPictureAspectRatio(
4132 r.pictureInPictureArgs.getAspectRatio());
4133 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4134 }
4135 }
4136 logPictureInPictureArgs(params);
4137 }
4138 } finally {
4139 Binder.restoreCallingIdentity(origId);
4140 }
4141 }
4142
4143 @Override
4144 public int getMaxNumPictureInPictureActions(IBinder token) {
4145 // Currently, this is a static constant, but later, we may change this to be dependent on
4146 // the context of the activity
4147 return 3;
4148 }
4149
4150 private void logPictureInPictureArgs(PictureInPictureParams params) {
4151 if (params.hasSetActions()) {
4152 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4153 params.getActions().size());
4154 }
4155 if (params.hasSetAspectRatio()) {
4156 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4157 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4158 MetricsLogger.action(lm);
4159 }
4160 }
4161
4162 /**
4163 * Checks the state of the system and the activity associated with the given {@param token} to
4164 * verify that picture-in-picture is supported for that activity.
4165 *
4166 * @return the activity record for the given {@param token} if all the checks pass.
4167 */
4168 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4169 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004170 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004171 throw new IllegalStateException(caller
4172 + ": Device doesn't support picture-in-picture mode.");
4173 }
4174
4175 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4176 if (r == null) {
4177 throw new IllegalStateException(caller
4178 + ": Can't find activity for token=" + token);
4179 }
4180
4181 if (!r.supportsPictureInPicture()) {
4182 throw new IllegalStateException(caller
4183 + ": Current activity does not support picture-in-picture.");
4184 }
4185
4186 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004187 && !mWindowManager.isValidPictureInPictureAspectRatio(
4188 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 final float minAspectRatio = mContext.getResources().getFloat(
4190 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4191 final float maxAspectRatio = mContext.getResources().getFloat(
4192 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4193 throw new IllegalArgumentException(String.format(caller
4194 + ": Aspect ratio is too extreme (must be between %f and %f).",
4195 minAspectRatio, maxAspectRatio));
4196 }
4197
4198 // Truncate the number of actions if necessary
4199 params.truncateActions(getMaxNumPictureInPictureActions(token));
4200
4201 return r;
4202 }
4203
4204 @Override
4205 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004206 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 synchronized (mGlobalLock) {
4208 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4209 if (r == null) {
4210 throw new IllegalArgumentException("Activity does not exist; token="
4211 + activityToken);
4212 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004213 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004214 }
4215 }
4216
4217 @Override
4218 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4219 Rect tempDockedTaskInsetBounds,
4220 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004221 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 long ident = Binder.clearCallingIdentity();
4223 try {
4224 synchronized (mGlobalLock) {
4225 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4226 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4227 PRESERVE_WINDOWS);
4228 }
4229 } finally {
4230 Binder.restoreCallingIdentity(ident);
4231 }
4232 }
4233
4234 @Override
4235 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004236 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 final long ident = Binder.clearCallingIdentity();
4238 try {
4239 synchronized (mGlobalLock) {
4240 mStackSupervisor.setSplitScreenResizing(resizing);
4241 }
4242 } finally {
4243 Binder.restoreCallingIdentity(ident);
4244 }
4245 }
4246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 /**
4248 * Check that we have the features required for VR-related API calls, and throw an exception if
4249 * not.
4250 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004251 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 if (!mContext.getPackageManager().hasSystemFeature(
4253 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4254 throw new UnsupportedOperationException("VR mode not supported on this device!");
4255 }
4256 }
4257
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 @Override
4259 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261
4262 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4263
4264 ActivityRecord r;
4265 synchronized (mGlobalLock) {
4266 r = ActivityRecord.isInStackLocked(token);
4267 }
4268
4269 if (r == null) {
4270 throw new IllegalArgumentException();
4271 }
4272
4273 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004274 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 VrManagerInternal.NO_ERROR) {
4276 return err;
4277 }
4278
4279 // Clear the binder calling uid since this path may call moveToTask().
4280 final long callingId = Binder.clearCallingIdentity();
4281 try {
4282 synchronized (mGlobalLock) {
4283 r.requestedVrComponent = (enabled) ? packageName : null;
4284
4285 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004286 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004287 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 }
4289 return 0;
4290 }
4291 } finally {
4292 Binder.restoreCallingIdentity(callingId);
4293 }
4294 }
4295
4296 @Override
4297 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4298 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4299 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004300 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4302 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4303 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004304 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004305 || activity.voiceSession != null) {
4306 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4307 return;
4308 }
4309 if (activity.pendingVoiceInteractionStart) {
4310 Slog.w(TAG, "Pending start of voice interaction already.");
4311 return;
4312 }
4313 activity.pendingVoiceInteractionStart = true;
4314 }
4315 LocalServices.getService(VoiceInteractionManagerInternal.class)
4316 .startLocalVoiceInteraction(callingActivity, options);
4317 }
4318
4319 @Override
4320 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4321 LocalServices.getService(VoiceInteractionManagerInternal.class)
4322 .stopLocalVoiceInteraction(callingActivity);
4323 }
4324
4325 @Override
4326 public boolean supportsLocalVoiceInteraction() {
4327 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4328 .supportsLocalVoiceInteraction();
4329 }
4330
4331 /** Notifies all listeners when the pinned stack animation starts. */
4332 @Override
4333 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004334 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335 }
4336
4337 /** Notifies all listeners when the pinned stack animation ends. */
4338 @Override
4339 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004340 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 }
4342
4343 @Override
4344 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 final long ident = Binder.clearCallingIdentity();
4347 try {
4348 synchronized (mGlobalLock) {
4349 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4350 }
4351 } finally {
4352 Binder.restoreCallingIdentity(ident);
4353 }
4354 }
4355
4356 @Override
4357 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359
4360 synchronized (mGlobalLock) {
4361 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004362 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 // Call might come when display is not yet added or has already been removed.
4364 if (DEBUG_CONFIGURATION) {
4365 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4366 + displayId);
4367 }
4368 return false;
4369 }
4370
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004371 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004374 }
4375
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004376 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004377 final Message msg = PooledLambda.obtainMessage(
4378 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4379 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 }
4381
4382 final long origId = Binder.clearCallingIdentity();
4383 try {
4384 if (values != null) {
4385 Settings.System.clearConfiguration(values);
4386 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4389 return mTmpUpdateConfigurationResult.changes != 0;
4390 } finally {
4391 Binder.restoreCallingIdentity(origId);
4392 }
4393 }
4394 }
4395
4396 @Override
4397 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399
4400 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 }
4405
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004407 final Message msg = PooledLambda.obtainMessage(
4408 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4409 DEFAULT_DISPLAY);
4410 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 }
4412
4413 final long origId = Binder.clearCallingIdentity();
4414 try {
4415 if (values != null) {
4416 Settings.System.clearConfiguration(values);
4417 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004418 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 UserHandle.USER_NULL, false /* deferResume */,
4420 mTmpUpdateConfigurationResult);
4421 return mTmpUpdateConfigurationResult.changes != 0;
4422 } finally {
4423 Binder.restoreCallingIdentity(origId);
4424 }
4425 }
4426 }
4427
4428 @Override
4429 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4430 CharSequence message) {
4431 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4434 }
4435 final long callingId = Binder.clearCallingIdentity();
4436 try {
4437 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004438 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 }
4440 } finally {
4441 Binder.restoreCallingIdentity(callingId);
4442 }
4443 }
4444
4445 @Override
4446 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 "cancelTaskWindowTransition()");
4449 final long ident = Binder.clearCallingIdentity();
4450 try {
4451 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004452 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 MATCH_TASK_IN_STACKS_ONLY);
4454 if (task == null) {
4455 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4456 return;
4457 }
4458 task.cancelWindowTransition();
4459 }
4460 } finally {
4461 Binder.restoreCallingIdentity(ident);
4462 }
4463 }
4464
4465 @Override
4466 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 final long ident = Binder.clearCallingIdentity();
4469 try {
4470 final TaskRecord task;
4471 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004472 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4474 if (task == null) {
4475 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4476 return null;
4477 }
4478 }
4479 // Don't call this while holding the lock as this operation might hit the disk.
4480 return task.getSnapshot(reducedResolution);
4481 } finally {
4482 Binder.restoreCallingIdentity(ident);
4483 }
4484 }
4485
4486 @Override
4487 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4488 synchronized (mGlobalLock) {
4489 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4490 if (r == null) {
4491 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4492 + token);
4493 return;
4494 }
4495 final long origId = Binder.clearCallingIdentity();
4496 try {
4497 r.setDisablePreviewScreenshots(disable);
4498 } finally {
4499 Binder.restoreCallingIdentity(origId);
4500 }
4501 }
4502 }
4503
4504 /** Return the user id of the last resumed activity. */
4505 @Override
4506 public @UserIdInt
4507 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4510 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004511 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004512 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004514 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
4516 }
4517
4518 @Override
4519 public void updateLockTaskFeatures(int userId, int flags) {
4520 final int callingUid = Binder.getCallingUid();
4521 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 "updateLockTaskFeatures()");
4524 }
4525 synchronized (mGlobalLock) {
4526 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4527 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004528 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 }
4530 }
4531
4532 @Override
4533 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4534 synchronized (mGlobalLock) {
4535 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4536 if (r == null) {
4537 return;
4538 }
4539 final long origId = Binder.clearCallingIdentity();
4540 try {
4541 r.setShowWhenLocked(showWhenLocked);
4542 } finally {
4543 Binder.restoreCallingIdentity(origId);
4544 }
4545 }
4546 }
4547
4548 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004549 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4550 synchronized (mGlobalLock) {
4551 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4552 if (r == null) {
4553 return;
4554 }
4555 final long origId = Binder.clearCallingIdentity();
4556 try {
4557 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4558 } finally {
4559 Binder.restoreCallingIdentity(origId);
4560 }
4561 }
4562 }
4563
4564 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4566 synchronized (mGlobalLock) {
4567 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4568 if (r == null) {
4569 return;
4570 }
4571 final long origId = Binder.clearCallingIdentity();
4572 try {
4573 r.setTurnScreenOn(turnScreenOn);
4574 } finally {
4575 Binder.restoreCallingIdentity(origId);
4576 }
4577 }
4578 }
4579
4580 @Override
4581 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 "registerRemoteAnimations");
4584 definition.setCallingPid(Binder.getCallingPid());
4585 synchronized (mGlobalLock) {
4586 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4587 if (r == null) {
4588 return;
4589 }
4590 final long origId = Binder.clearCallingIdentity();
4591 try {
4592 r.registerRemoteAnimations(definition);
4593 } finally {
4594 Binder.restoreCallingIdentity(origId);
4595 }
4596 }
4597 }
4598
4599 @Override
4600 public void registerRemoteAnimationForNextActivityStart(String packageName,
4601 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004602 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 "registerRemoteAnimationForNextActivityStart");
4604 adapter.setCallingPid(Binder.getCallingPid());
4605 synchronized (mGlobalLock) {
4606 final long origId = Binder.clearCallingIdentity();
4607 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004608 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 packageName, adapter);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
Evan Rosky966759f2019-01-15 10:33:58 -08004616 @Override
4617 public void registerRemoteAnimationsForDisplay(int displayId,
4618 RemoteAnimationDefinition definition) {
4619 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4620 "registerRemoteAnimations");
4621 definition.setCallingPid(Binder.getCallingPid());
4622 synchronized (mGlobalLock) {
4623 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4624 if (display == null) {
4625 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4626 return;
4627 }
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
4630 display.mDisplayContent.registerRemoteAnimations(definition);
4631 } finally {
4632 Binder.restoreCallingIdentity(origId);
4633 }
4634 }
4635 }
4636
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4638 @Override
4639 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4640 synchronized (mGlobalLock) {
4641 final long origId = Binder.clearCallingIdentity();
4642 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004643 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004644 } finally {
4645 Binder.restoreCallingIdentity(origId);
4646 }
4647 }
4648 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004649
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 @Override
4651 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004652 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004653 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004654 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004655 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004656 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004657 }
4658 }
4659
4660 @Override
4661 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004662 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004663 != PERMISSION_GRANTED) {
4664 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4665 + Binder.getCallingPid()
4666 + ", uid=" + Binder.getCallingUid()
4667 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4668 Slog.w(TAG, msg);
4669 throw new SecurityException(msg);
4670 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004671 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004672 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004673 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004674 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004675 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004676 }
4677 }
4678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 @Override
4680 public void stopAppSwitches() {
4681 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4682 synchronized (mGlobalLock) {
4683 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4684 mDidAppSwitch = false;
4685 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4686 }
4687 }
4688
4689 @Override
4690 public void resumeAppSwitches() {
4691 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4692 synchronized (mGlobalLock) {
4693 // Note that we don't execute any pending app switches... we will
4694 // let those wait until either the timeout, or the next start
4695 // activity request.
4696 mAppSwitchesAllowedTime = 0;
4697 }
4698 }
4699
4700 void onStartActivitySetDidAppSwitch() {
4701 if (mDidAppSwitch) {
4702 // This is the second allowed switch since we stopped switches, so now just generally
4703 // allow switches. Use case:
4704 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4705 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4706 // anyone to switch again).
4707 mAppSwitchesAllowedTime = 0;
4708 } else {
4709 mDidAppSwitch = true;
4710 }
4711 }
4712
4713 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 boolean shouldDisableNonVrUiLocked() {
4715 return mVrController.shouldDisableNonVrUiLocked();
4716 }
4717
Wale Ogunwale53783742018-09-16 10:21:51 -07004718 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 // VR apps are expected to run in a main display. If an app is turning on VR for
4720 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4721 // fullscreen stack before enabling VR Mode.
4722 // TODO: The goal of this code is to keep the VR app on the main display. When the
4723 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4724 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4725 // option would be a better choice here.
4726 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4727 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4728 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004729 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004730 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004731 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 mH.post(() -> {
4734 if (!mVrController.onVrModeChanged(r)) {
4735 return;
4736 }
4737 synchronized (mGlobalLock) {
4738 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4739 mWindowManager.disableNonVrUi(disableNonVrUi);
4740 if (disableNonVrUi) {
4741 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4742 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004743 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 }
4745 }
4746 });
4747 }
4748
Wale Ogunwale53783742018-09-16 10:21:51 -07004749 @Override
4750 public int getPackageScreenCompatMode(String packageName) {
4751 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4752 synchronized (mGlobalLock) {
4753 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4754 }
4755 }
4756
4757 @Override
4758 public void setPackageScreenCompatMode(String packageName, int mode) {
4759 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4760 "setPackageScreenCompatMode");
4761 synchronized (mGlobalLock) {
4762 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4763 }
4764 }
4765
4766 @Override
4767 public boolean getPackageAskScreenCompat(String packageName) {
4768 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4769 synchronized (mGlobalLock) {
4770 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4771 }
4772 }
4773
4774 @Override
4775 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4776 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4777 "setPackageAskScreenCompat");
4778 synchronized (mGlobalLock) {
4779 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4780 }
4781 }
4782
Wale Ogunwale64258362018-10-16 15:13:37 -07004783 public static String relaunchReasonToString(int relaunchReason) {
4784 switch (relaunchReason) {
4785 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4786 return "window_resize";
4787 case RELAUNCH_REASON_FREE_RESIZE:
4788 return "free_resize";
4789 default:
4790 return null;
4791 }
4792 }
4793
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004794 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004795 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004796 }
4797
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 /** Pokes the task persister. */
4799 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4800 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4801 }
4802
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 boolean isKeyguardLocked() {
4804 return mKeyguardController.isKeyguardLocked();
4805 }
4806
Garfield Tan01548632018-11-27 10:15:48 -08004807 /**
4808 * Clears launch params for the given package.
4809 * @param packageNames the names of the packages of which the launch params are to be cleared
4810 */
4811 @Override
4812 public void clearLaunchParamsForPackages(List<String> packageNames) {
4813 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4814 "clearLaunchParamsForPackages");
4815 synchronized (mGlobalLock) {
4816 for (int i = 0; i < packageNames.size(); ++i) {
4817 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4818 }
4819 }
4820 }
4821
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004822 /**
4823 * Makes the display with the given id a single task instance display. I.e the display can only
4824 * contain one task.
4825 */
4826 @Override
4827 public void setDisplayToSingleTaskInstance(int displayId) {
4828 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4829 "setDisplayToSingleTaskInstance");
4830 final long origId = Binder.clearCallingIdentity();
4831 try {
4832 final ActivityDisplay display =
4833 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4834 if (display != null) {
4835 display.setDisplayToSingleTaskInstance();
4836 }
4837 } finally {
4838 Binder.restoreCallingIdentity(origId);
4839 }
4840 }
4841
Wale Ogunwale31913b52018-10-13 08:29:31 -07004842 void dumpLastANRLocked(PrintWriter pw) {
4843 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4844 if (mLastANRState == null) {
4845 pw.println(" <no ANR has occurred since boot>");
4846 } else {
4847 pw.println(mLastANRState);
4848 }
4849 }
4850
4851 void dumpLastANRTracesLocked(PrintWriter pw) {
4852 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4853
4854 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4855 if (ArrayUtils.isEmpty(files)) {
4856 pw.println(" <no ANR has occurred since boot>");
4857 return;
4858 }
4859 // Find the latest file.
4860 File latest = null;
4861 for (File f : files) {
4862 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4863 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004864 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004865 }
4866 pw.print("File: ");
4867 pw.print(latest.getName());
4868 pw.println();
4869 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4870 String line;
4871 while ((line = in.readLine()) != null) {
4872 pw.println(line);
4873 }
4874 } catch (IOException e) {
4875 pw.print("Unable to read: ");
4876 pw.print(e);
4877 pw.println();
4878 }
4879 }
4880
4881 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4882 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4883 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4884 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4885 }
4886
4887 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4888 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4889 pw.println(header);
4890
Wale Ogunwaled32da472018-11-16 07:19:28 -08004891 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004892 dumpPackage);
4893 boolean needSep = printedAnything;
4894
4895 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004896 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004897 " ResumedActivity: ");
4898 if (printed) {
4899 printedAnything = true;
4900 needSep = false;
4901 }
4902
4903 if (dumpPackage == null) {
4904 if (needSep) {
4905 pw.println();
4906 }
4907 printedAnything = true;
4908 mStackSupervisor.dump(pw, " ");
4909 }
4910
4911 if (!printedAnything) {
4912 pw.println(" (nothing)");
4913 }
4914 }
4915
4916 void dumpActivityContainersLocked(PrintWriter pw) {
4917 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004918 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004919 pw.println(" ");
4920 }
4921
4922 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4923 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4924 getActivityStartController().dump(pw, "", dumpPackage);
4925 }
4926
4927 /**
4928 * There are three things that cmd can be:
4929 * - a flattened component name that matches an existing activity
4930 * - the cmd arg isn't the flattened component name of an existing activity:
4931 * dump all activity whose component contains the cmd as a substring
4932 * - A hex number of the ActivityRecord object instance.
4933 *
4934 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4935 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4936 */
4937 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4938 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4939 ArrayList<ActivityRecord> activities;
4940
4941 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004942 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 dumpFocusedStackOnly);
4944 }
4945
4946 if (activities.size() <= 0) {
4947 return false;
4948 }
4949
4950 String[] newArgs = new String[args.length - opti];
4951 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4952
4953 TaskRecord lastTask = null;
4954 boolean needSep = false;
4955 for (int i = activities.size() - 1; i >= 0; i--) {
4956 ActivityRecord r = activities.get(i);
4957 if (needSep) {
4958 pw.println();
4959 }
4960 needSep = true;
4961 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004962 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004963 if (lastTask != task) {
4964 lastTask = task;
4965 pw.print("TASK "); pw.print(lastTask.affinity);
4966 pw.print(" id="); pw.print(lastTask.taskId);
4967 pw.print(" userId="); pw.println(lastTask.userId);
4968 if (dumpAll) {
4969 lastTask.dump(pw, " ");
4970 }
4971 }
4972 }
4973 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4974 }
4975 return true;
4976 }
4977
4978 /**
4979 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4980 * there is a thread associated with the activity.
4981 */
4982 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4983 final ActivityRecord r, String[] args, boolean dumpAll) {
4984 String innerPrefix = prefix + " ";
4985 synchronized (mGlobalLock) {
4986 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4987 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4988 pw.print(" pid=");
4989 if (r.hasProcess()) pw.println(r.app.getPid());
4990 else pw.println("(not running)");
4991 if (dumpAll) {
4992 r.dump(pw, innerPrefix);
4993 }
4994 }
4995 if (r.attachedToProcess()) {
4996 // flush anything that is already in the PrintWriter since the thread is going
4997 // to write to the file descriptor directly
4998 pw.flush();
4999 try {
5000 TransferPipe tp = new TransferPipe();
5001 try {
5002 r.app.getThread().dumpActivity(tp.getWriteFd(),
5003 r.appToken, innerPrefix, args);
5004 tp.go(fd);
5005 } finally {
5006 tp.kill();
5007 }
5008 } catch (IOException e) {
5009 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5010 } catch (RemoteException e) {
5011 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005013 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005014 }
5015
sanryhuang498e77e2018-12-06 14:57:01 +08005016 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5017 boolean testPssMode) {
5018 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5019 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5020 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005021 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5023 st.toString());
5024 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5026 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5027 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005028 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5029 testPssMode);
5030 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005031 }
5032
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005033 int getCurrentUserId() {
5034 return mAmInternal.getCurrentUserId();
5035 }
5036
5037 private void enforceNotIsolatedCaller(String caller) {
5038 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5039 throw new SecurityException("Isolated process not allowed to call " + caller);
5040 }
5041 }
5042
Wale Ogunwalef6733932018-06-27 05:14:34 -07005043 public Configuration getConfiguration() {
5044 Configuration ci;
5045 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005046 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005047 ci.userSetLocale = false;
5048 }
5049 return ci;
5050 }
5051
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005052 /**
5053 * Current global configuration information. Contains general settings for the entire system,
5054 * also corresponds to the merged configuration of the default display.
5055 */
5056 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005057 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005058 }
5059
5060 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5061 boolean initLocale) {
5062 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5063 }
5064
5065 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5066 boolean initLocale, boolean deferResume) {
5067 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5068 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5069 UserHandle.USER_NULL, deferResume);
5070 }
5071
Wale Ogunwale59507092018-10-29 09:00:30 -07005072 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 final long origId = Binder.clearCallingIdentity();
5074 try {
5075 synchronized (mGlobalLock) {
5076 updateConfigurationLocked(values, null, false, true, userId,
5077 false /* deferResume */);
5078 }
5079 } finally {
5080 Binder.restoreCallingIdentity(origId);
5081 }
5082 }
5083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005084 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5085 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5086 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5087 deferResume, null /* result */);
5088 }
5089
5090 /**
5091 * Do either or both things: (1) change the current configuration, and (2)
5092 * make sure the given activity is running with the (now) current
5093 * configuration. Returns true if the activity has been left running, or
5094 * false if <var>starting</var> is being destroyed to match the new
5095 * configuration.
5096 *
5097 * @param userId is only used when persistent parameter is set to true to persist configuration
5098 * for that particular user
5099 */
5100 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5101 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5102 ActivityTaskManagerService.UpdateConfigurationResult result) {
5103 int changes = 0;
5104 boolean kept = true;
5105
5106 if (mWindowManager != null) {
5107 mWindowManager.deferSurfaceLayout();
5108 }
5109 try {
5110 if (values != null) {
5111 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5112 deferResume);
5113 }
5114
5115 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5116 } finally {
5117 if (mWindowManager != null) {
5118 mWindowManager.continueSurfaceLayout();
5119 }
5120 }
5121
5122 if (result != null) {
5123 result.changes = changes;
5124 result.activityRelaunched = !kept;
5125 }
5126 return kept;
5127 }
5128
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 /** Update default (global) configuration and notify listeners about changes. */
5130 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5131 boolean persistent, int userId, boolean deferResume) {
5132 mTempConfig.setTo(getGlobalConfiguration());
5133 final int changes = mTempConfig.updateFrom(values);
5134 if (changes == 0) {
5135 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5136 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5137 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5138 // (even if there are no actual changes) to unfreeze the window.
5139 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5140 return 0;
5141 }
5142
5143 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5144 "Updating global configuration to: " + values);
5145
5146 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5147 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5148 values.colorMode,
5149 values.densityDpi,
5150 values.fontScale,
5151 values.hardKeyboardHidden,
5152 values.keyboard,
5153 values.keyboardHidden,
5154 values.mcc,
5155 values.mnc,
5156 values.navigation,
5157 values.navigationHidden,
5158 values.orientation,
5159 values.screenHeightDp,
5160 values.screenLayout,
5161 values.screenWidthDp,
5162 values.smallestScreenWidthDp,
5163 values.touchscreen,
5164 values.uiMode);
5165
5166
5167 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5168 final LocaleList locales = values.getLocales();
5169 int bestLocaleIndex = 0;
5170 if (locales.size() > 1) {
5171 if (mSupportedSystemLocales == null) {
5172 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5173 }
5174 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5175 }
5176 SystemProperties.set("persist.sys.locale",
5177 locales.get(bestLocaleIndex).toLanguageTag());
5178 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005179
5180 final Message m = PooledLambda.obtainMessage(
5181 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5182 locales.get(bestLocaleIndex));
5183 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184 }
5185
Yunfan Chen75157d72018-07-27 14:47:21 +09005186 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005189 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5192 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005193 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194
5195 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005196 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197
5198 AttributeCache ac = AttributeCache.instance();
5199 if (ac != null) {
5200 ac.updateConfiguration(mTempConfig);
5201 }
5202
5203 // Make sure all resources in our process are updated right now, so that anyone who is going
5204 // to retrieve resource values after we return will be sure to get the new ones. This is
5205 // especially important during boot, where the first config change needs to guarantee all
5206 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005207 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005208
5209 // We need another copy of global config because we're scheduling some calls instead of
5210 // running them in place. We need to be sure that object we send will be handled unchanged.
5211 final Configuration configCopy = new Configuration(mTempConfig);
5212 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005213 final Message msg = PooledLambda.obtainMessage(
5214 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5215 this, userId, configCopy);
5216 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005217 }
5218
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005219 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5220 for (int i = pidMap.size() - 1; i >= 0; i--) {
5221 final int pid = pidMap.keyAt(i);
5222 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005223 if (DEBUG_CONFIGURATION) {
5224 Slog.v(TAG_CONFIGURATION, "Update process config of "
5225 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005227 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228 }
5229
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005230 final Message msg = PooledLambda.obtainMessage(
5231 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5232 mAmInternal, changes, initLocale);
5233 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234
5235 // Override configuration of the default display duplicates global config, so we need to
5236 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005237 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 DEFAULT_DISPLAY);
5239
5240 return changes;
5241 }
5242
5243 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5244 boolean deferResume, int displayId) {
5245 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5246 displayId, null /* result */);
5247 }
5248
5249 /**
5250 * Updates override configuration specific for the selected display. If no config is provided,
5251 * new one will be computed in WM based on current display info.
5252 */
5253 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5254 ActivityRecord starting, boolean deferResume, int displayId,
5255 ActivityTaskManagerService.UpdateConfigurationResult result) {
5256 int changes = 0;
5257 boolean kept = true;
5258
5259 if (mWindowManager != null) {
5260 mWindowManager.deferSurfaceLayout();
5261 }
5262 try {
5263 if (values != null) {
5264 if (displayId == DEFAULT_DISPLAY) {
5265 // Override configuration of the default display duplicates global config, so
5266 // we're calling global config update instead for default display. It will also
5267 // apply the correct override config.
5268 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5269 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5270 } else {
5271 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5272 }
5273 }
5274
5275 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5276 } finally {
5277 if (mWindowManager != null) {
5278 mWindowManager.continueSurfaceLayout();
5279 }
5280 }
5281
5282 if (result != null) {
5283 result.changes = changes;
5284 result.activityRelaunched = !kept;
5285 }
5286 return kept;
5287 }
5288
5289 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5290 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005291 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292 final int changes = mTempConfig.updateFrom(values);
5293 if (changes != 0) {
5294 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5295 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005296 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297
5298 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5299 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005300 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005301
Wale Ogunwale5c918702018-10-18 11:06:33 -07005302 // Post message to start process to avoid possible deadlock of calling into AMS with
5303 // the ATMS lock held.
5304 final Message msg = PooledLambda.obtainMessage(
5305 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005306 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005307 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005308 }
5309 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005310 return changes;
5311 }
5312
Wale Ogunwalef6733932018-06-27 05:14:34 -07005313 private void updateEventDispatchingLocked(boolean booted) {
5314 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5315 }
5316
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005317 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5318 final ContentResolver resolver = mContext.getContentResolver();
5319 Settings.System.putConfigurationForUser(resolver, config, userId);
5320 }
5321
5322 private void sendLocaleToMountDaemonMsg(Locale l) {
5323 try {
5324 IBinder service = ServiceManager.getService("mount");
5325 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5326 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5327 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5328 } catch (RemoteException e) {
5329 Log.e(TAG, "Error storing locale for decryption UI", e);
5330 }
5331 }
5332
Alison Cichowlas3e340502018-08-07 17:15:01 -04005333 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5334 mStartActivitySources.remove(permissionToken);
5335 mExpiredStartAsCallerTokens.add(permissionToken);
5336 }
5337
5338 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5339 mExpiredStartAsCallerTokens.remove(permissionToken);
5340 }
5341
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005342 boolean isActivityStartsLoggingEnabled() {
5343 return mAmInternal.isActivityStartsLoggingEnabled();
5344 }
5345
Michal Karpinski8596ded2018-11-14 14:43:48 +00005346 boolean isBackgroundActivityStartsEnabled() {
5347 return mAmInternal.isBackgroundActivityStartsEnabled();
5348 }
5349
Ricky Waiaca8a772019-04-04 16:01:06 +01005350 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5351 if (packageName == null) {
5352 return false;
5353 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005354 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5355 }
5356
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 void enableScreenAfterBoot(boolean booted) {
5358 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5359 SystemClock.uptimeMillis());
5360 mWindowManager.enableScreenAfterBoot();
5361
5362 synchronized (mGlobalLock) {
5363 updateEventDispatchingLocked(booted);
5364 }
5365 }
5366
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005367 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5368 if (r == null || !r.hasProcess()) {
5369 return KEY_DISPATCHING_TIMEOUT_MS;
5370 }
5371 return getInputDispatchingTimeoutLocked(r.app);
5372 }
5373
5374 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005375 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005376 }
5377
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 /**
5379 * Decide based on the configuration whether we should show the ANR,
5380 * crash, etc dialogs. The idea is that if there is no affordance to
5381 * press the on-screen buttons, or the user experience would be more
5382 * greatly impacted than the crash itself, we shouldn't show the dialog.
5383 *
5384 * A thought: SystemUI might also want to get told about this, the Power
5385 * dialog / global actions also might want different behaviors.
5386 */
5387 private void updateShouldShowDialogsLocked(Configuration config) {
5388 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5389 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5390 && config.navigation == Configuration.NAVIGATION_NONAV);
5391 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5392 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5393 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5394 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5395 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5396 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5397 HIDE_ERROR_DIALOGS, 0) != 0;
5398 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5399 }
5400
5401 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5402 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5403 FONT_SCALE, 1.0f, userId);
5404
5405 synchronized (this) {
5406 if (getGlobalConfiguration().fontScale == scaleFactor) {
5407 return;
5408 }
5409
5410 final Configuration configuration
5411 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5412 configuration.fontScale = scaleFactor;
5413 updatePersistentConfiguration(configuration, userId);
5414 }
5415 }
5416
5417 // Actually is sleeping or shutting down or whatever else in the future
5418 // is an inactive state.
5419 boolean isSleepingOrShuttingDownLocked() {
5420 return isSleepingLocked() || mShuttingDown;
5421 }
5422
5423 boolean isSleepingLocked() {
5424 return mSleeping;
5425 }
5426
Riddle Hsu16567132018-08-16 21:37:47 +08005427 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005429 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 if (task.isActivityTypeStandard()) {
5431 if (mCurAppTimeTracker != r.appTimeTracker) {
5432 // We are switching app tracking. Complete the current one.
5433 if (mCurAppTimeTracker != null) {
5434 mCurAppTimeTracker.stop();
5435 mH.obtainMessage(
5436 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005437 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005438 mCurAppTimeTracker = null;
5439 }
5440 if (r.appTimeTracker != null) {
5441 mCurAppTimeTracker = r.appTimeTracker;
5442 startTimeTrackingFocusedActivityLocked();
5443 }
5444 } else {
5445 startTimeTrackingFocusedActivityLocked();
5446 }
5447 } else {
5448 r.appTimeTracker = null;
5449 }
5450 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5451 // TODO: Probably not, because we don't want to resume voice on switching
5452 // back to this activity
5453 if (task.voiceInteractor != null) {
5454 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5455 } else {
5456 finishRunningVoiceLocked();
5457
5458 if (mLastResumedActivity != null) {
5459 final IVoiceInteractionSession session;
5460
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005461 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 if (lastResumedActivityTask != null
5463 && lastResumedActivityTask.voiceSession != null) {
5464 session = lastResumedActivityTask.voiceSession;
5465 } else {
5466 session = mLastResumedActivity.voiceSession;
5467 }
5468
5469 if (session != null) {
5470 // We had been in a voice interaction session, but now focused has
5471 // move to something different. Just finish the session, we can't
5472 // return to it and retain the proper state and synchronization with
5473 // the voice interaction service.
5474 finishVoiceTask(session);
5475 }
5476 }
5477 }
5478
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005479 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5480 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 }
5482 updateResumedAppTrace(r);
5483 mLastResumedActivity = r;
5484
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005485 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005486
5487 applyUpdateLockStateLocked(r);
5488 applyUpdateVrModeLocked(r);
5489
5490 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005491 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 r == null ? "NULL" : r.shortComponentName,
5493 reason);
5494 }
5495
5496 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5497 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005498 final ActivityTaskManagerInternal.SleepToken token =
5499 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 updateSleepIfNeededLocked();
5501 return token;
5502 }
5503 }
5504
5505 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005506 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 final boolean wasSleeping = mSleeping;
5508 boolean updateOomAdj = false;
5509
5510 if (!shouldSleep) {
5511 // If wasSleeping is true, we need to wake up activity manager state from when
5512 // we started sleeping. In either case, we need to apply the sleep tokens, which
5513 // will wake up stacks or put them to sleep as appropriate.
5514 if (wasSleeping) {
5515 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005516 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5517 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005518 startTimeTrackingFocusedActivityLocked();
5519 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005520 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5522 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005523 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524 if (wasSleeping) {
5525 updateOomAdj = true;
5526 }
5527 } else if (!mSleeping && shouldSleep) {
5528 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005529 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5530 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005531 if (mCurAppTimeTracker != null) {
5532 mCurAppTimeTracker.stop();
5533 }
5534 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005535 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005536 mStackSupervisor.goingToSleepLocked();
5537 updateResumedAppTrace(null /* resumed */);
5538 updateOomAdj = true;
5539 }
5540 if (updateOomAdj) {
5541 mH.post(mAmInternal::updateOomAdj);
5542 }
5543 }
5544
5545 void updateOomAdj() {
5546 mH.post(mAmInternal::updateOomAdj);
5547 }
5548
Wale Ogunwale53783742018-09-16 10:21:51 -07005549 void updateCpuStats() {
5550 mH.post(mAmInternal::updateCpuStats);
5551 }
5552
Hui Yu03d12402018-12-06 18:00:37 -08005553 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5554 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005555 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5556 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005557 mH.sendMessage(m);
5558 }
5559
Hui Yu03d12402018-12-06 18:00:37 -08005560 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005561 ComponentName taskRoot = null;
5562 final TaskRecord task = activity.getTaskRecord();
5563 if (task != null) {
5564 final ActivityRecord rootActivity = task.getRootActivity();
5565 if (rootActivity != null) {
5566 taskRoot = rootActivity.mActivityComponent;
5567 }
5568 }
5569
Hui Yu03d12402018-12-06 18:00:37 -08005570 final Message m = PooledLambda.obtainMessage(
5571 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005572 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005573 mH.sendMessage(m);
5574 }
5575
Wale Ogunwale53783742018-09-16 10:21:51 -07005576 void setBooting(boolean booting) {
5577 mAmInternal.setBooting(booting);
5578 }
5579
5580 boolean isBooting() {
5581 return mAmInternal.isBooting();
5582 }
5583
5584 void setBooted(boolean booted) {
5585 mAmInternal.setBooted(booted);
5586 }
5587
5588 boolean isBooted() {
5589 return mAmInternal.isBooted();
5590 }
5591
5592 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5593 mH.post(() -> {
5594 if (finishBooting) {
5595 mAmInternal.finishBooting();
5596 }
5597 if (enableScreen) {
5598 mInternal.enableScreenAfterBoot(isBooted());
5599 }
5600 });
5601 }
5602
5603 void setHeavyWeightProcess(ActivityRecord root) {
5604 mHeavyWeightProcess = root.app;
5605 final Message m = PooledLambda.obtainMessage(
5606 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005607 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005608 mH.sendMessage(m);
5609 }
5610
5611 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5612 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5613 return;
5614 }
5615
5616 mHeavyWeightProcess = null;
5617 final Message m = PooledLambda.obtainMessage(
5618 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5619 proc.mUserId);
5620 mH.sendMessage(m);
5621 }
5622
5623 private void cancelHeavyWeightProcessNotification(int userId) {
5624 final INotificationManager inm = NotificationManager.getService();
5625 if (inm == null) {
5626 return;
5627 }
5628 try {
5629 inm.cancelNotificationWithTag("android", null,
5630 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5631 } catch (RuntimeException e) {
5632 Slog.w(TAG, "Error canceling notification for service", e);
5633 } catch (RemoteException e) {
5634 }
5635
5636 }
5637
5638 private void postHeavyWeightProcessNotification(
5639 WindowProcessController proc, Intent intent, int userId) {
5640 if (proc == null) {
5641 return;
5642 }
5643
5644 final INotificationManager inm = NotificationManager.getService();
5645 if (inm == null) {
5646 return;
5647 }
5648
5649 try {
5650 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5651 String text = mContext.getString(R.string.heavy_weight_notification,
5652 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5653 Notification notification =
5654 new Notification.Builder(context,
5655 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5656 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5657 .setWhen(0)
5658 .setOngoing(true)
5659 .setTicker(text)
5660 .setColor(mContext.getColor(
5661 com.android.internal.R.color.system_notification_accent_color))
5662 .setContentTitle(text)
5663 .setContentText(
5664 mContext.getText(R.string.heavy_weight_notification_detail))
5665 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5666 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5667 new UserHandle(userId)))
5668 .build();
5669 try {
5670 inm.enqueueNotificationWithTag("android", "android", null,
5671 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5672 } catch (RuntimeException e) {
5673 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5674 } catch (RemoteException e) {
5675 }
5676 } catch (PackageManager.NameNotFoundException e) {
5677 Slog.w(TAG, "Unable to create context for heavy notification", e);
5678 }
5679
5680 }
5681
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005682 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5683 IBinder token, String resultWho, int requestCode, Intent[] intents,
5684 String[] resolvedTypes, int flags, Bundle bOptions) {
5685
5686 ActivityRecord activity = null;
5687 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5688 activity = ActivityRecord.isInStackLocked(token);
5689 if (activity == null) {
5690 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5691 return null;
5692 }
5693 if (activity.finishing) {
5694 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5695 return null;
5696 }
5697 }
5698
5699 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5700 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5701 bOptions);
5702 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5703 if (noCreate) {
5704 return rec;
5705 }
5706 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5707 if (activity.pendingResults == null) {
5708 activity.pendingResults = new HashSet<>();
5709 }
5710 activity.pendingResults.add(rec.ref);
5711 }
5712 return rec;
5713 }
5714
Andrii Kulian52d255c2018-07-13 11:32:19 -07005715 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005716 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005717 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005718 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5719 mCurAppTimeTracker.start(resumedActivity.packageName);
5720 }
5721 }
5722
5723 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5724 if (mTracedResumedActivity != null) {
5725 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5726 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5727 }
5728 if (resumed != null) {
5729 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5730 constructResumedTraceName(resumed.packageName), 0);
5731 }
5732 mTracedResumedActivity = resumed;
5733 }
5734
5735 private String constructResumedTraceName(String packageName) {
5736 return "focused app: " + packageName;
5737 }
5738
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005739 /** Applies latest configuration and/or visibility updates if needed. */
5740 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5741 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005742 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005743 // mainStack is null during startup.
5744 if (mainStack != null) {
5745 if (changes != 0 && starting == null) {
5746 // If the configuration changed, and the caller is not already
5747 // in the process of starting an activity, then find the top
5748 // activity to check if its configuration needs to change.
5749 starting = mainStack.topRunningActivityLocked();
5750 }
5751
5752 if (starting != null) {
5753 kept = starting.ensureActivityConfiguration(changes,
5754 false /* preserveWindow */);
5755 // And we need to make sure at this point that all other activities
5756 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005757 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005758 !PRESERVE_WINDOWS);
5759 }
5760 }
5761
5762 return kept;
5763 }
5764
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005765 void scheduleAppGcsLocked() {
5766 mH.post(() -> mAmInternal.scheduleAppGcs());
5767 }
5768
Wale Ogunwale53783742018-09-16 10:21:51 -07005769 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5770 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5771 }
5772
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005773 /**
5774 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5775 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5776 * on demand.
5777 */
5778 IPackageManager getPackageManager() {
5779 return AppGlobals.getPackageManager();
5780 }
5781
5782 PackageManagerInternal getPackageManagerInternalLocked() {
5783 if (mPmInternal == null) {
5784 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5785 }
5786 return mPmInternal;
5787 }
5788
Wale Ogunwale008163e2018-07-23 23:11:08 -07005789 AppWarnings getAppWarningsLocked() {
5790 return mAppWarnings;
5791 }
5792
Wale Ogunwale214f3482018-10-04 11:00:47 -07005793 Intent getHomeIntent() {
5794 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5795 intent.setComponent(mTopComponent);
5796 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5797 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5798 intent.addCategory(Intent.CATEGORY_HOME);
5799 }
5800 return intent;
5801 }
5802
Chilun2ef71f72018-11-16 17:57:15 +08005803 /**
5804 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5805 * activities.
5806 *
5807 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5808 * component defined in config_secondaryHomeComponent.
5809 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5810 */
5811 Intent getSecondaryHomeIntent(String preferredPackage) {
5812 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5813 if (preferredPackage == null) {
5814 // Using the component stored in config if no package name.
5815 final String secondaryHomeComponent = mContext.getResources().getString(
5816 com.android.internal.R.string.config_secondaryHomeComponent);
5817 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5818 } else {
5819 intent.setPackage(preferredPackage);
5820 }
5821 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5822 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5823 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5824 }
5825 return intent;
5826 }
5827
Wale Ogunwale214f3482018-10-04 11:00:47 -07005828 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5829 if (info == null) return null;
5830 ApplicationInfo newInfo = new ApplicationInfo(info);
5831 newInfo.initForUser(userId);
5832 return newInfo;
5833 }
5834
Wale Ogunwale9c103022018-10-18 07:44:54 -07005835 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005836 if (uid == SYSTEM_UID) {
5837 // The system gets to run in any process. If there are multiple processes with the same
5838 // uid, just pick the first (this should never happen).
5839 final SparseArray<WindowProcessController> procs =
5840 mProcessNames.getMap().get(processName);
5841 if (procs == null) return null;
5842 final int procCount = procs.size();
5843 for (int i = 0; i < procCount; i++) {
5844 final int procUid = procs.keyAt(i);
5845 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5846 // Don't use an app process or different user process for system component.
5847 continue;
5848 }
5849 return procs.valueAt(i);
5850 }
5851 }
5852
5853 return mProcessNames.get(processName, uid);
5854 }
5855
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005856 WindowProcessController getProcessController(IApplicationThread thread) {
5857 if (thread == null) {
5858 return null;
5859 }
5860
5861 final IBinder threadBinder = thread.asBinder();
5862 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5863 for (int i = pmap.size()-1; i >= 0; i--) {
5864 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5865 for (int j = procs.size() - 1; j >= 0; j--) {
5866 final WindowProcessController proc = procs.valueAt(j);
5867 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5868 return proc;
5869 }
5870 }
5871 }
5872
5873 return null;
5874 }
5875
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005876 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005877 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005878 if (proc == null) return null;
5879 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5880 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005881 }
5882 return null;
5883 }
5884
Riddle Hsua0536432019-02-16 00:38:59 +08005885 int getUidState(int uid) {
5886 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005887 }
5888
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005889 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005890 // A uid is considered to be foreground if it has a visible non-toast window.
5891 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005892 }
5893
Ricky Wai96f5c352019-04-10 18:40:17 +01005894 boolean isDeviceOwner(int uid) {
5895 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005896 }
5897
Ricky Wai96f5c352019-04-10 18:40:17 +01005898 void setDeviceOwnerUid(int uid) {
5899 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005900 }
5901
Wale Ogunwale9de19442018-10-18 19:05:03 -07005902 /**
5903 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5904 * the whitelist
5905 */
5906 String getPendingTempWhitelistTagForUidLocked(int uid) {
5907 return mPendingTempWhitelist.get(uid);
5908 }
5909
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005910 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5911 if (true || Build.IS_USER) {
5912 return;
5913 }
5914
5915 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5916 StrictMode.allowThreadDiskWrites();
5917 try {
5918 File tracesDir = new File("/data/anr");
5919 File tracesFile = null;
5920 try {
5921 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5922
5923 StringBuilder sb = new StringBuilder();
5924 Time tobj = new Time();
5925 tobj.set(System.currentTimeMillis());
5926 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5927 sb.append(": ");
5928 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5929 sb.append(" since ");
5930 sb.append(msg);
5931 FileOutputStream fos = new FileOutputStream(tracesFile);
5932 fos.write(sb.toString().getBytes());
5933 if (app == null) {
5934 fos.write("\n*** No application process!".getBytes());
5935 }
5936 fos.close();
5937 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5938 } catch (IOException e) {
5939 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5940 return;
5941 }
5942
5943 if (app != null && app.getPid() > 0) {
5944 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5945 firstPids.add(app.getPid());
5946 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5947 }
5948
5949 File lastTracesFile = null;
5950 File curTracesFile = null;
5951 for (int i=9; i>=0; i--) {
5952 String name = String.format(Locale.US, "slow%02d.txt", i);
5953 curTracesFile = new File(tracesDir, name);
5954 if (curTracesFile.exists()) {
5955 if (lastTracesFile != null) {
5956 curTracesFile.renameTo(lastTracesFile);
5957 } else {
5958 curTracesFile.delete();
5959 }
5960 }
5961 lastTracesFile = curTracesFile;
5962 }
5963 tracesFile.renameTo(curTracesFile);
5964 } finally {
5965 StrictMode.setThreadPolicy(oldPolicy);
5966 }
5967 }
5968
Michal Karpinskida34cd42019-04-02 19:46:52 +01005969 boolean isAssociatedCompanionApp(int userId, int uid) {
5970 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5971 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005972 return false;
5973 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005974 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005975 }
5976
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005977 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005978 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005979
5980
Wale Ogunwale98875612018-10-12 07:53:02 -07005981 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5982 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005983
Riddle Hsud93a6c42018-11-29 21:50:06 +08005984 H(Looper looper) {
5985 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005986 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005987
5988 @Override
5989 public void handleMessage(Message msg) {
5990 switch (msg.what) {
5991 case REPORT_TIME_TRACKER_MSG: {
5992 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5993 tracker.deliverResult(mContext);
5994 } break;
5995 }
5996 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005997 }
5998
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005999 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006000 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006001
6002 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006003 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006004 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006005
6006 @Override
6007 public void handleMessage(Message msg) {
6008 switch (msg.what) {
6009 case DISMISS_DIALOG_UI_MSG: {
6010 final Dialog d = (Dialog) msg.obj;
6011 d.dismiss();
6012 break;
6013 }
6014 }
6015 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006016 }
6017
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006018 final class LocalService extends ActivityTaskManagerInternal {
6019 @Override
6020 public SleepToken acquireSleepToken(String tag, int displayId) {
6021 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006023 }
6024
6025 @Override
6026 public ComponentName getHomeActivityForUser(int userId) {
6027 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006028 final ActivityRecord homeActivity =
6029 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006030 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
6032 }
6033
6034 @Override
6035 public void onLocalVoiceInteractionStarted(IBinder activity,
6036 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6037 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006038 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 }
6040 }
6041
6042 @Override
6043 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6044 synchronized (mGlobalLock) {
6045 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6046 reasons, timestamp);
6047 }
6048 }
6049
6050 @Override
6051 public void notifyAppTransitionFinished() {
6052 synchronized (mGlobalLock) {
6053 mStackSupervisor.notifyAppTransitionDone();
6054 }
6055 }
6056
6057 @Override
6058 public void notifyAppTransitionCancelled() {
6059 synchronized (mGlobalLock) {
6060 mStackSupervisor.notifyAppTransitionDone();
6061 }
6062 }
6063
6064 @Override
6065 public List<IBinder> getTopVisibleActivities() {
6066 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006067 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006068 }
6069 }
6070
6071 @Override
6072 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6073 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006074 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006075 }
6076 }
6077
6078 @Override
6079 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6080 Bundle bOptions) {
6081 Preconditions.checkNotNull(intents, "intents");
6082 final String[] resolvedTypes = new String[intents.length];
6083
6084 // UID of the package on user userId.
6085 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6086 // packageUid may not be initialized.
6087 int packageUid = 0;
6088 final long ident = Binder.clearCallingIdentity();
6089
6090 try {
6091 for (int i = 0; i < intents.length; i++) {
6092 resolvedTypes[i] =
6093 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6094 }
6095
6096 packageUid = AppGlobals.getPackageManager().getPackageUid(
6097 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6098 } catch (RemoteException e) {
6099 // Shouldn't happen.
6100 } finally {
6101 Binder.restoreCallingIdentity(ident);
6102 }
6103
Riddle Hsu591bf612019-02-14 17:55:31 +08006104 return getActivityStartController().startActivitiesInPackage(
6105 packageUid, packageName,
6106 intents, resolvedTypes, null /* resultTo */,
6107 SafeActivityOptions.fromBundle(bOptions), userId,
6108 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6109 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 }
6111
6112 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006113 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6114 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6115 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6116 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006117 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006118 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006119 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6120 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6121 userId, validateIncomingUser, originatingPendingIntent,
6122 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006123 }
6124 }
6125
6126 @Override
6127 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6128 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6129 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6130 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006131 PendingIntentRecord originatingPendingIntent,
6132 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006133 synchronized (mGlobalLock) {
6134 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6135 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6136 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006137 validateIncomingUser, originatingPendingIntent,
6138 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006139 }
6140 }
6141
6142 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6144 Intent intent, Bundle options, int userId) {
6145 return ActivityTaskManagerService.this.startActivityAsUser(
6146 caller, callerPacakge, intent,
6147 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6148 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6149 false /*validateIncomingUser*/);
6150 }
6151
6152 @Override
lumark588a3e82018-07-20 18:53:54 +08006153 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 synchronized (mGlobalLock) {
6155
6156 // We might change the visibilities here, so prepare an empty app transition which
6157 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006158 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006159 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006160 if (activityDisplay == null) {
6161 return;
6162 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006163 final DisplayContent dc = activityDisplay.mDisplayContent;
6164 final boolean wasTransitionSet =
6165 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006167 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006169 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170
6171 // If there was a transition set already we don't want to interfere with it as we
6172 // might be starting it too early.
6173 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006174 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
6176 }
6177 if (callback != null) {
6178 callback.run();
6179 }
6180 }
6181
6182 @Override
6183 public void notifyKeyguardTrustedChanged() {
6184 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006185 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006186 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006187 }
6188 }
6189 }
6190
6191 /**
6192 * Called after virtual display Id is updated by
6193 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6194 * {@param vrVr2dDisplayId}.
6195 */
6196 @Override
6197 public void setVr2dDisplayId(int vr2dDisplayId) {
6198 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6199 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006200 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
6202 }
6203
6204 @Override
6205 public void setFocusedActivity(IBinder token) {
6206 synchronized (mGlobalLock) {
6207 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6208 if (r == null) {
6209 throw new IllegalArgumentException(
6210 "setFocusedActivity: No activity record matching token=" + token);
6211 }
Louis Chang19443452018-10-09 12:10:21 +08006212 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006213 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215 }
6216 }
6217
6218 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006220 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
6222
6223 @Override
6224 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006225 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
6227
6228 @Override
6229 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006230 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231 }
6232
6233 @Override
6234 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6235 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6236 }
6237
6238 @Override
6239 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006240 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006241 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006242
6243 @Override
6244 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6245 synchronized (mGlobalLock) {
6246 mActiveVoiceInteractionServiceComponent = component;
6247 }
6248 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006249
6250 @Override
6251 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6252 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6253 return;
6254 }
6255 synchronized (mGlobalLock) {
6256 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6257 if (types == null) {
6258 if (uid < 0) {
6259 return;
6260 }
6261 types = new ArrayMap<>();
6262 mAllowAppSwitchUids.put(userId, types);
6263 }
6264 if (uid < 0) {
6265 types.remove(type);
6266 } else {
6267 types.put(type, uid);
6268 }
6269 }
6270 }
6271
6272 @Override
6273 public void onUserStopped(int userId) {
6274 synchronized (mGlobalLock) {
6275 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6276 mAllowAppSwitchUids.remove(userId);
6277 }
6278 }
6279
6280 @Override
6281 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6282 synchronized (mGlobalLock) {
6283 return ActivityTaskManagerService.this.isGetTasksAllowed(
6284 caller, callingPid, callingUid);
6285 }
6286 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006287
Riddle Hsua0536432019-02-16 00:38:59 +08006288 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006289 @Override
6290 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006291 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006292 mProcessNames.put(proc.mName, proc.mUid, proc);
6293 }
6294 }
6295
Riddle Hsua0536432019-02-16 00:38:59 +08006296 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006297 @Override
6298 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006299 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006300 mProcessNames.remove(name, uid);
6301 }
6302 }
6303
Riddle Hsua0536432019-02-16 00:38:59 +08006304 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006305 @Override
6306 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006308 if (proc == mHomeProcess) {
6309 mHomeProcess = null;
6310 }
6311 if (proc == mPreviousProcess) {
6312 mPreviousProcess = null;
6313 }
6314 }
6315 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006316
Riddle Hsua0536432019-02-16 00:38:59 +08006317 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006318 @Override
6319 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006320 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006321 return mTopProcessState;
6322 }
6323 }
6324
Riddle Hsua0536432019-02-16 00:38:59 +08006325 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006326 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006327 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006328 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006329 return proc == mHeavyWeightProcess;
6330 }
6331 }
6332
Riddle Hsua0536432019-02-16 00:38:59 +08006333 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006334 @Override
6335 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006336 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006337 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6338 }
6339 }
6340
6341 @Override
6342 public void finishHeavyWeightApp() {
6343 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006344 if (mHeavyWeightProcess != null) {
6345 mHeavyWeightProcess.finishActivities();
6346 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006347 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6348 mHeavyWeightProcess);
6349 }
6350 }
6351
Riddle Hsua0536432019-02-16 00:38:59 +08006352 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006353 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006354 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006356 return isSleepingLocked();
6357 }
6358 }
6359
6360 @Override
6361 public boolean isShuttingDown() {
6362 synchronized (mGlobalLock) {
6363 return mShuttingDown;
6364 }
6365 }
6366
6367 @Override
6368 public boolean shuttingDown(boolean booted, int timeout) {
6369 synchronized (mGlobalLock) {
6370 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006371 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006372 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006373 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006374 return mStackSupervisor.shutdownLocked(timeout);
6375 }
6376 }
6377
6378 @Override
6379 public void enableScreenAfterBoot(boolean booted) {
6380 synchronized (mGlobalLock) {
6381 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6382 SystemClock.uptimeMillis());
6383 mWindowManager.enableScreenAfterBoot();
6384 updateEventDispatchingLocked(booted);
6385 }
6386 }
6387
6388 @Override
6389 public boolean showStrictModeViolationDialog() {
6390 synchronized (mGlobalLock) {
6391 return mShowDialogs && !mSleeping && !mShuttingDown;
6392 }
6393 }
6394
6395 @Override
6396 public void showSystemReadyErrorDialogsIfNeeded() {
6397 synchronized (mGlobalLock) {
6398 try {
6399 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6400 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6401 + " data partition or your device will be unstable.");
6402 mUiHandler.post(() -> {
6403 if (mShowDialogs) {
6404 AlertDialog d = new BaseErrorDialog(mUiContext);
6405 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6406 d.setCancelable(false);
6407 d.setTitle(mUiContext.getText(R.string.android_system_label));
6408 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6409 d.setButton(DialogInterface.BUTTON_POSITIVE,
6410 mUiContext.getText(R.string.ok),
6411 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6412 d.show();
6413 }
6414 });
6415 }
6416 } catch (RemoteException e) {
6417 }
6418
6419 if (!Build.isBuildConsistent()) {
6420 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6421 mUiHandler.post(() -> {
6422 if (mShowDialogs) {
6423 AlertDialog d = new BaseErrorDialog(mUiContext);
6424 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6425 d.setCancelable(false);
6426 d.setTitle(mUiContext.getText(R.string.android_system_label));
6427 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6428 d.setButton(DialogInterface.BUTTON_POSITIVE,
6429 mUiContext.getText(R.string.ok),
6430 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6431 d.show();
6432 }
6433 });
6434 }
6435 }
6436 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006437
6438 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006439 public void onProcessMapped(int pid, WindowProcessController proc) {
6440 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006441 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006442 }
6443 }
6444
6445 @Override
6446 public void onProcessUnMapped(int pid) {
6447 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006448 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006449 }
6450 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006451
6452 @Override
6453 public void onPackageDataCleared(String name) {
6454 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006456 mAppWarnings.onPackageDataCleared(name);
6457 }
6458 }
6459
6460 @Override
6461 public void onPackageUninstalled(String name) {
6462 synchronized (mGlobalLock) {
6463 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006464 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006465 }
6466 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006467
6468 @Override
6469 public void onPackageAdded(String name, boolean replacing) {
6470 synchronized (mGlobalLock) {
6471 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6472 }
6473 }
6474
6475 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006476 public void onPackageReplaced(ApplicationInfo aInfo) {
6477 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006478 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006479 }
6480 }
6481
6482 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006483 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6484 synchronized (mGlobalLock) {
6485 return compatibilityInfoForPackageLocked(ai);
6486 }
6487 }
6488
Yunfan Chen75157d72018-07-27 14:47:21 +09006489 /**
6490 * Set the corresponding display information for the process global configuration. To be
6491 * called when we need to show IME on a different display.
6492 *
6493 * @param pid The process id associated with the IME window.
6494 * @param displayId The ID of the display showing the IME.
6495 */
6496 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006497 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006498 // Don't update process-level configuration for Multi-Client IME process since other
6499 // IMEs on other displays will also receive this configuration change due to IME
6500 // services use the same application config/context.
6501 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006502
Yunfan Chen75157d72018-07-27 14:47:21 +09006503 if (pid == MY_PID || pid < 0) {
6504 if (DEBUG_CONFIGURATION) {
6505 Slog.w(TAG,
6506 "Trying to update display configuration for system/invalid process.");
6507 }
6508 return;
6509 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006510 synchronized (mGlobalLock) {
6511 final ActivityDisplay activityDisplay =
6512 mRootActivityContainer.getActivityDisplay(displayId);
6513 if (activityDisplay == null) {
6514 // Call might come when display is not yet added or has been removed.
6515 if (DEBUG_CONFIGURATION) {
6516 Slog.w(TAG, "Trying to update display configuration for non-existing "
6517 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006518 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006519 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006520 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006521 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006522 if (process == null) {
6523 if (DEBUG_CONFIGURATION) {
6524 Slog.w(TAG, "Trying to update display configuration for invalid "
6525 + "process, pid=" + pid);
6526 }
6527 return;
6528 }
6529 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6530 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006531 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006532
6533 @Override
6534 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6535 int requestCode, int resultCode, Intent data) {
6536 synchronized (mGlobalLock) {
6537 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006538 if (r != null && r.getActivityStack() != null) {
6539 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6540 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006541 }
6542 }
6543 }
6544
6545 @Override
6546 public void clearPendingResultForActivity(IBinder activityToken,
6547 WeakReference<PendingIntentRecord> pir) {
6548 synchronized (mGlobalLock) {
6549 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6550 if (r != null && r.pendingResults != null) {
6551 r.pendingResults.remove(pir);
6552 }
6553 }
6554 }
6555
6556 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006557 public ActivityTokens getTopActivityForTask(int taskId) {
6558 synchronized (mGlobalLock) {
6559 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6560 if (taskRecord == null) {
6561 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6562 + " Requested task not found");
6563 return null;
6564 }
6565 final ActivityRecord activity = taskRecord.getTopActivity();
6566 if (activity == null) {
6567 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6568 + " Requested activity not found");
6569 return null;
6570 }
6571 if (!activity.attachedToProcess()) {
6572 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6573 + activity);
6574 return null;
6575 }
6576 return new ActivityTokens(activity.appToken, activity.assistToken,
6577 activity.app.getThread());
6578 }
6579 }
6580
6581 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006582 public IIntentSender getIntentSender(int type, String packageName,
6583 int callingUid, int userId, IBinder token, String resultWho,
6584 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6585 Bundle bOptions) {
6586 synchronized (mGlobalLock) {
6587 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6588 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6589 }
6590 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006591
6592 @Override
6593 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6594 synchronized (mGlobalLock) {
6595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6596 if (r == null) {
6597 return null;
6598 }
6599 if (r.mServiceConnectionsHolder == null) {
6600 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6601 ActivityTaskManagerService.this, r);
6602 }
6603
6604 return r.mServiceConnectionsHolder;
6605 }
6606 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006607
6608 @Override
6609 public Intent getHomeIntent() {
6610 synchronized (mGlobalLock) {
6611 return ActivityTaskManagerService.this.getHomeIntent();
6612 }
6613 }
6614
6615 @Override
6616 public boolean startHomeActivity(int userId, String reason) {
6617 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006618 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006619 }
6620 }
6621
6622 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006623 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006624 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006625 synchronized (mGlobalLock) {
6626 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006627 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006628 }
Chilun8b1f1be2019-03-13 17:14:36 +08006629 }
6630
6631 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006632 public boolean startHomeOnAllDisplays(int userId, String reason) {
6633 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006634 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006635 }
6636 }
6637
Riddle Hsua0536432019-02-16 00:38:59 +08006638 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006639 @Override
6640 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006641 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006642 if (mFactoryTest == FACTORY_TEST_OFF) {
6643 return false;
6644 }
6645 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6646 && wpc.mName.equals(mTopComponent.getPackageName())) {
6647 return true;
6648 }
6649 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6650 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6651 }
6652 }
6653
6654 @Override
6655 public void updateTopComponentForFactoryTest() {
6656 synchronized (mGlobalLock) {
6657 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6658 return;
6659 }
6660 final ResolveInfo ri = mContext.getPackageManager()
6661 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6662 final CharSequence errorMsg;
6663 if (ri != null) {
6664 final ActivityInfo ai = ri.activityInfo;
6665 final ApplicationInfo app = ai.applicationInfo;
6666 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6667 mTopAction = Intent.ACTION_FACTORY_TEST;
6668 mTopData = null;
6669 mTopComponent = new ComponentName(app.packageName, ai.name);
6670 errorMsg = null;
6671 } else {
6672 errorMsg = mContext.getResources().getText(
6673 com.android.internal.R.string.factorytest_not_system);
6674 }
6675 } else {
6676 errorMsg = mContext.getResources().getText(
6677 com.android.internal.R.string.factorytest_no_action);
6678 }
6679 if (errorMsg == null) {
6680 return;
6681 }
6682
6683 mTopAction = null;
6684 mTopData = null;
6685 mTopComponent = null;
6686 mUiHandler.post(() -> {
6687 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6688 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006689 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006690 });
6691 }
6692 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006693
Riddle Hsua0536432019-02-16 00:38:59 +08006694 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 @Override
6696 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6697 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006698 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006700 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701
6702 wpc.clearRecentTasks();
6703 wpc.clearActivities();
6704
6705 if (wpc.isInstrumenting()) {
6706 finishInstrumentationCallback.run();
6707 }
6708
Jorim Jaggid0752812018-10-16 16:07:20 +02006709 if (!restarting && hasVisibleActivities) {
6710 mWindowManager.deferSurfaceLayout();
6711 try {
6712 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6713 // If there was nothing to resume, and we are not already restarting
6714 // this process, but there is a visible activity that is hosted by the
6715 // process...then make sure all visible activities are running, taking
6716 // care of restarting this process.
6717 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6718 !PRESERVE_WINDOWS);
6719 }
6720 } finally {
6721 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 }
6724 }
6725 }
6726
6727 @Override
6728 public void closeSystemDialogs(String reason) {
6729 enforceNotIsolatedCaller("closeSystemDialogs");
6730
6731 final int pid = Binder.getCallingPid();
6732 final int uid = Binder.getCallingUid();
6733 final long origId = Binder.clearCallingIdentity();
6734 try {
6735 synchronized (mGlobalLock) {
6736 // Only allow this from foreground processes, so that background
6737 // applications can't abuse it to prevent system UI from being shown.
6738 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006739 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 if (!proc.isPerceptible()) {
6741 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6742 + " from background process " + proc);
6743 return;
6744 }
6745 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 mWindowManager.closeSystemDialogs(reason);
6747
Wale Ogunwaled32da472018-11-16 07:19:28 -08006748 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006750 // Call into AM outside the synchronized block.
6751 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 } finally {
6753 Binder.restoreCallingIdentity(origId);
6754 }
6755 }
6756
6757 @Override
6758 public void cleanupDisabledPackageComponents(
6759 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6760 synchronized (mGlobalLock) {
6761 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006762 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 mStackSupervisor.scheduleIdleLocked();
6766 }
6767
6768 // Clean-up disabled tasks
6769 getRecentTasks().cleanupDisabledPackageTasksLocked(
6770 packageName, disabledClasses, userId);
6771 }
6772 }
6773
6774 @Override
6775 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6776 int userId) {
6777 synchronized (mGlobalLock) {
6778
6779 boolean didSomething =
6780 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 null, doit, evenPersistent, userId);
6783 return didSomething;
6784 }
6785 }
6786
6787 @Override
6788 public void resumeTopActivities(boolean scheduleIdle) {
6789 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006790 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006791 if (scheduleIdle) {
6792 mStackSupervisor.scheduleIdleLocked();
6793 }
6794 }
6795 }
6796
Riddle Hsua0536432019-02-16 00:38:59 +08006797 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 @Override
6799 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006800 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6802 }
6803 }
6804
Riddle Hsua0536432019-02-16 00:38:59 +08006805 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 @Override
6807 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006808 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 }
6811 }
6812
6813 @Override
6814 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6815 try {
6816 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6817 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6818 }
6819 } catch (RemoteException ex) {
6820 throw new SecurityException("Fail to check is caller a privileged app", ex);
6821 }
6822
6823 synchronized (mGlobalLock) {
6824 final long ident = Binder.clearCallingIdentity();
6825 try {
6826 if (mAmInternal.shouldConfirmCredentials(userId)) {
6827 if (mKeyguardController.isKeyguardLocked()) {
6828 // Showing launcher to avoid user entering credential twice.
6829 startHomeActivity(currentUserId, "notifyLockedProfile");
6830 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006831 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 }
6833 } finally {
6834 Binder.restoreCallingIdentity(ident);
6835 }
6836 }
6837 }
6838
6839 @Override
6840 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6841 mAmInternal.enforceCallingPermission(
6842 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6843
6844 synchronized (mGlobalLock) {
6845 final long ident = Binder.clearCallingIdentity();
6846 try {
6847 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6848 FLAG_ACTIVITY_TASK_ON_HOME);
6849 ActivityOptions activityOptions = options != null
6850 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006851 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006852 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006853 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006854 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006855 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006856 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6857 UserHandle.CURRENT);
6858 } finally {
6859 Binder.restoreCallingIdentity(ident);
6860 }
6861 }
6862 }
6863
6864 @Override
6865 public void writeActivitiesToProto(ProtoOutputStream proto) {
6866 synchronized (mGlobalLock) {
6867 // The output proto of "activity --proto activities"
6868 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006869 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006870 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6871 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006872 }
6873 }
6874
6875 @Override
6876 public void saveANRState(String reason) {
6877 synchronized (mGlobalLock) {
6878 final StringWriter sw = new StringWriter();
6879 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6880 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6881 if (reason != null) {
6882 pw.println(" Reason: " + reason);
6883 }
6884 pw.println();
6885 getActivityStartController().dump(pw, " ", null);
6886 pw.println();
6887 pw.println("-------------------------------------------------------------------------------");
6888 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6889 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6890 "" /* header */);
6891 pw.println();
6892 pw.close();
6893
6894 mLastANRState = sw.toString();
6895 }
6896 }
6897
6898 @Override
6899 public void clearSavedANRState() {
6900 synchronized (mGlobalLock) {
6901 mLastANRState = null;
6902 }
6903 }
6904
6905 @Override
6906 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6907 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6908 synchronized (mGlobalLock) {
6909 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6910 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6911 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6912 dumpLastANRLocked(pw);
6913 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6914 dumpLastANRTracesLocked(pw);
6915 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6916 dumpActivityStarterLocked(pw, dumpPackage);
6917 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6918 dumpActivityContainersLocked(pw);
6919 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6920 if (getRecentTasks() != null) {
6921 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6922 }
6923 }
6924 }
6925 }
6926
6927 @Override
6928 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6929 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6930 int wakefulness) {
6931 synchronized (mGlobalLock) {
6932 if (mHomeProcess != null && (dumpPackage == null
6933 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6934 if (needSep) {
6935 pw.println();
6936 needSep = false;
6937 }
6938 pw.println(" mHomeProcess: " + mHomeProcess);
6939 }
6940 if (mPreviousProcess != null && (dumpPackage == null
6941 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6942 if (needSep) {
6943 pw.println();
6944 needSep = false;
6945 }
6946 pw.println(" mPreviousProcess: " + mPreviousProcess);
6947 }
6948 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6949 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6950 StringBuilder sb = new StringBuilder(128);
6951 sb.append(" mPreviousProcessVisibleTime: ");
6952 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6953 pw.println(sb);
6954 }
6955 if (mHeavyWeightProcess != null && (dumpPackage == null
6956 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6957 if (needSep) {
6958 pw.println();
6959 needSep = false;
6960 }
6961 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6962 }
6963 if (dumpPackage == null) {
6964 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006965 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006966 }
6967 if (dumpAll) {
6968 if (dumpPackage == null) {
6969 pw.println(" mConfigWillChange: "
6970 + getTopDisplayFocusedStack().mConfigWillChange);
6971 }
6972 if (mCompatModePackages.getPackages().size() > 0) {
6973 boolean printed = false;
6974 for (Map.Entry<String, Integer> entry
6975 : mCompatModePackages.getPackages().entrySet()) {
6976 String pkg = entry.getKey();
6977 int mode = entry.getValue();
6978 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6979 continue;
6980 }
6981 if (!printed) {
6982 pw.println(" mScreenCompatPackages:");
6983 printed = true;
6984 }
6985 pw.println(" " + pkg + ": " + mode);
6986 }
6987 }
6988 }
6989
6990 if (dumpPackage == null) {
6991 pw.println(" mWakefulness="
6992 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006993 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 if (mRunningVoice != null) {
6995 pw.println(" mRunningVoice=" + mRunningVoice);
6996 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6997 }
6998 pw.println(" mSleeping=" + mSleeping);
6999 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7000 pw.println(" mVrController=" + mVrController);
7001 }
7002 if (mCurAppTimeTracker != null) {
7003 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7004 }
7005 if (mAllowAppSwitchUids.size() > 0) {
7006 boolean printed = false;
7007 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7008 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7009 for (int j = 0; j < types.size(); j++) {
7010 if (dumpPackage == null ||
7011 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7012 if (needSep) {
7013 pw.println();
7014 needSep = false;
7015 }
7016 if (!printed) {
7017 pw.println(" mAllowAppSwitchUids:");
7018 printed = true;
7019 }
7020 pw.print(" User ");
7021 pw.print(mAllowAppSwitchUids.keyAt(i));
7022 pw.print(": Type ");
7023 pw.print(types.keyAt(j));
7024 pw.print(" = ");
7025 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7026 pw.println();
7027 }
7028 }
7029 }
7030 }
7031 if (dumpPackage == null) {
7032 if (mController != null) {
7033 pw.println(" mController=" + mController
7034 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7035 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007036 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7037 pw.println(" mLaunchingActivityWakeLock="
7038 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007039 }
7040
7041 return needSep;
7042 }
7043 }
7044
7045 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007046 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7047 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 synchronized (mGlobalLock) {
7049 if (dumpPackage == null) {
7050 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7051 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007052 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7053 if (mRunningVoice != null) {
7054 final long vrToken = proto.start(
7055 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7056 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7057 mRunningVoice.toString());
7058 mVoiceWakeLock.writeToProto(
7059 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7060 proto.end(vrToken);
7061 }
7062 mVrController.writeToProto(proto,
7063 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007064 if (mController != null) {
7065 final long token = proto.start(CONTROLLER);
7066 proto.write(CONTROLLER, mController.toString());
7067 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7068 proto.end(token);
7069 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007070 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7071 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7072 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 }
7074
7075 if (mHomeProcess != null && (dumpPackage == null
7076 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007077 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007078 }
7079
7080 if (mPreviousProcess != null && (dumpPackage == null
7081 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007082 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007083 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7084 }
7085
7086 if (mHeavyWeightProcess != null && (dumpPackage == null
7087 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007088 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 }
7090
7091 for (Map.Entry<String, Integer> entry
7092 : mCompatModePackages.getPackages().entrySet()) {
7093 String pkg = entry.getKey();
7094 int mode = entry.getValue();
7095 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7096 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7097 proto.write(PACKAGE, pkg);
7098 proto.write(MODE, mode);
7099 proto.end(compatToken);
7100 }
7101 }
7102
7103 if (mCurAppTimeTracker != null) {
7104 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7105 }
7106
7107 }
7108 }
7109
7110 @Override
7111 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7112 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7113 boolean dumpFocusedStackOnly) {
7114 synchronized (mGlobalLock) {
7115 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7116 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7117 }
7118 }
7119
7120 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007121 public void dumpForOom(PrintWriter pw) {
7122 synchronized (mGlobalLock) {
7123 pw.println(" mHomeProcess: " + mHomeProcess);
7124 pw.println(" mPreviousProcess: " + mPreviousProcess);
7125 if (mHeavyWeightProcess != null) {
7126 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7127 }
7128 }
7129 }
7130
7131 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007132 public boolean canGcNow() {
7133 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007134 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 }
7136 }
7137
Riddle Hsua0536432019-02-16 00:38:59 +08007138 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007139 @Override
7140 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007141 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007142 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 return top != null ? top.app : null;
7144 }
7145 }
7146
Riddle Hsua0536432019-02-16 00:38:59 +08007147 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007148 @Override
7149 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007150 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007151 if (mRootActivityContainer != null) {
7152 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007153 }
7154 }
7155 }
7156
7157 @Override
7158 public void scheduleDestroyAllActivities(String reason) {
7159 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007160 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 }
7162 }
7163
7164 @Override
7165 public void removeUser(int userId) {
7166 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007167 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007168 }
7169 }
7170
7171 @Override
7172 public boolean switchUser(int userId, UserState userState) {
7173 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007174 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 }
7176 }
7177
7178 @Override
7179 public void onHandleAppCrash(WindowProcessController wpc) {
7180 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007181 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007182 }
7183 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007184
7185 @Override
7186 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007188 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007189 }
7190 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007191
Riddle Hsua0536432019-02-16 00:38:59 +08007192 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007193 @Override
7194 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007195 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007196 }
7197
Riddle Hsua0536432019-02-16 00:38:59 +08007198 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007199 @Override
7200 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007201 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007202 }
7203
Riddle Hsua0536432019-02-16 00:38:59 +08007204 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007205 @Override
7206 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007207 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007208 }
7209
Riddle Hsua0536432019-02-16 00:38:59 +08007210 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007211 @Override
7212 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007213 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007214 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007215
7216 @Override
7217 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007218 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007219 mPendingTempWhitelist.put(uid, tag);
7220 }
7221 }
7222
7223 @Override
7224 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007225 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007226 mPendingTempWhitelist.remove(uid);
7227 }
7228 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007229
7230 @Override
7231 public boolean handleAppCrashInActivityController(String processName, int pid,
7232 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7233 Runnable killCrashingAppCallback) {
7234 synchronized (mGlobalLock) {
7235 if (mController == null) {
7236 return false;
7237 }
7238
7239 try {
7240 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7241 stackTrace)) {
7242 killCrashingAppCallback.run();
7243 return true;
7244 }
7245 } catch (RemoteException e) {
7246 mController = null;
7247 Watchdog.getInstance().setActivityController(null);
7248 }
7249 return false;
7250 }
7251 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007252
7253 @Override
7254 public void removeRecentTasksByPackageName(String packageName, int userId) {
7255 synchronized (mGlobalLock) {
7256 mRecentTasks.removeTasksByPackageName(packageName, userId);
7257 }
7258 }
7259
7260 @Override
7261 public void cleanupRecentTasksForUser(int userId) {
7262 synchronized (mGlobalLock) {
7263 mRecentTasks.cleanupLocked(userId);
7264 }
7265 }
7266
7267 @Override
7268 public void loadRecentTasksForUser(int userId) {
7269 synchronized (mGlobalLock) {
7270 mRecentTasks.loadUserRecentsLocked(userId);
7271 }
7272 }
7273
7274 @Override
7275 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7276 synchronized (mGlobalLock) {
7277 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7278 }
7279 }
7280
7281 @Override
7282 public void flushRecentTasks() {
7283 mRecentTasks.flush();
7284 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007285
7286 @Override
7287 public WindowProcessController getHomeProcess() {
7288 synchronized (mGlobalLock) {
7289 return mHomeProcess;
7290 }
7291 }
7292
7293 @Override
7294 public WindowProcessController getPreviousProcess() {
7295 synchronized (mGlobalLock) {
7296 return mPreviousProcess;
7297 }
7298 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007299
7300 @Override
7301 public void clearLockedTasks(String reason) {
7302 synchronized (mGlobalLock) {
7303 getLockTaskController().clearLockedTasks(reason);
7304 }
7305 }
7306
7307 @Override
7308 public void updateUserConfiguration() {
7309 synchronized (mGlobalLock) {
7310 final Configuration configuration = new Configuration(getGlobalConfiguration());
7311 final int currentUserId = mAmInternal.getCurrentUserId();
7312 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7313 configuration, currentUserId, Settings.System.canWrite(mContext));
7314 updateConfigurationLocked(configuration, null /* starting */,
7315 false /* initLocale */, false /* persistent */, currentUserId,
7316 false /* deferResume */);
7317 }
7318 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007319
7320 @Override
7321 public boolean canShowErrorDialogs() {
7322 synchronized (mGlobalLock) {
7323 return mShowDialogs && !mSleeping && !mShuttingDown
7324 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7325 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7326 mAmInternal.getCurrentUserId())
7327 && !(UserManager.isDeviceInDemoMode(mContext)
7328 && mAmInternal.getCurrentUser().isDemo());
7329 }
7330 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007331
7332 @Override
7333 public void setProfileApp(String profileApp) {
7334 synchronized (mGlobalLock) {
7335 mProfileApp = profileApp;
7336 }
7337 }
7338
7339 @Override
7340 public void setProfileProc(WindowProcessController wpc) {
7341 synchronized (mGlobalLock) {
7342 mProfileProc = wpc;
7343 }
7344 }
7345
7346 @Override
7347 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7348 synchronized (mGlobalLock) {
7349 mProfilerInfo = profilerInfo;
7350 }
7351 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007352
7353 @Override
7354 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7355 synchronized (mGlobalLock) {
7356 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7357 }
7358 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007359
7360 @Override
7361 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7362 synchronized (mGlobalLock) {
7363 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7364 }
7365 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007366
7367 @Override
7368 public boolean isUidForeground(int uid) {
7369 synchronized (mGlobalLock) {
7370 return ActivityTaskManagerService.this.isUidForeground(uid);
7371 }
7372 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007373
7374 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007375 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007376 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007377 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007378 }
7379 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007380
7381 @Override
7382 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007383 // Translate package names into UIDs
7384 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007385 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007386 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7387 if (uid >= 0) {
7388 result.add(uid);
7389 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007390 }
7391 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007392 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007393 }
7394 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007395 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007396}