blob: 8d613afeace36b6cd3f55867b8f285d3056bc2a3 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800227import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100248import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800266import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313
Wale Ogunwale98875612018-10-12 07:53:02 -0700314 /** Used to indicate that an app transition should be animated. */
315 static final boolean ANIMATE = true;
316
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700317 /** Hardware-reported OpenGLES version. */
318 final int GL_ES_VERSION;
319
Wale Ogunwale31913b52018-10-13 08:29:31 -0700320 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
321 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
322 public static final String DUMP_LASTANR_CMD = "lastanr" ;
323 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
324 public static final String DUMP_STARTER_CMD = "starter" ;
325 public static final String DUMP_CONTAINERS_CMD = "containers" ;
326 public static final String DUMP_RECENTS_CMD = "recents" ;
327 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
328
Wale Ogunwale64258362018-10-16 15:13:37 -0700329 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
330 public static final int RELAUNCH_REASON_NONE = 0;
331 /** This activity is being relaunched due to windowing mode change. */
332 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
333 /** This activity is being relaunched due to a free-resize operation. */
334 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
335
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700336 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700337
Wale Ogunwalef6733932018-06-27 05:14:34 -0700338 /**
339 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
340 * change at runtime. Use mContext for non-UI purposes.
341 */
342 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700343 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700344 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700345 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700347 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700348 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800349 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800350 @VisibleForTesting
351 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 PowerManagerInternal mPowerManagerInternal;
353 private UsageStatsManagerInternal mUsageStatsInternal;
354
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700355 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 IntentFirewall mIntentFirewall;
357
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700358 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800359 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800360 /**
361 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
362 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
363 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
364 *
365 * @see WindowManagerThreadPriorityBooster
366 */
367 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700368 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800369 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700370 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700371 private UserManagerService mUserManager;
372 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700373 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800374 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700375 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700376 /** All processes currently running that might have a window organized by name. */
377 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100378 /** All processes we currently have running mapped by pid and uid */
379 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** This is the process holding what we currently consider to be the "home" activity. */
381 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700382 /** The currently running heavy-weight process, if any. */
383 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700384 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /**
386 * This is the process holding the activity the user last visited that is in a different process
387 * from the one they are currently in.
388 */
389 WindowProcessController mPreviousProcess;
390 /** The time at which the previous process was last visible. */
391 long mPreviousProcessVisibleTime;
392
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700393 /** List of intents that were used to start the most recent tasks. */
394 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700395 /** State of external calls telling us if the device is awake or asleep. */
396 private boolean mKeyguardShown = false;
397
398 // Wrapper around VoiceInteractionServiceManager
399 private AssistUtils mAssistUtils;
400
401 // VoiceInteraction session ID that changes for each new request except when
402 // being called for multi-window assist in a single session.
403 private int mViSessionId = 1000;
404
405 // How long to wait in getAssistContextExtras for the activity and foreground services
406 // to respond with the result.
407 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
408
409 // How long top wait when going through the modern assist (which doesn't need to block
410 // on getting this result before starting to launch its UI).
411 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
412
413 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
414 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
415
Alison Cichowlas3e340502018-08-07 17:15:01 -0400416 // Permission tokens are used to temporarily granted a trusted app the ability to call
417 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
418 // showing any appropriate error messages to the user.
419 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
420 10 * MINUTE_IN_MILLIS;
421
422 // How long before the service actually expires a token. This is slightly longer than
423 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
424 // expiration exception.
425 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
426 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
427
428 // How long the service will remember expired tokens, for the purpose of providing error
429 // messaging when a client uses an expired token.
430 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
431 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
432
Marvin Ramin830d4e32019-03-12 13:16:58 +0100433 // How long to whitelist the Services for when requested.
434 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
435
Alison Cichowlas3e340502018-08-07 17:15:01 -0400436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
462 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
507 IActivityController mController = null;
508 boolean mControllerIsAMonkey = false;
509
Wale Ogunwale214f3482018-10-04 11:00:47 -0700510 final int mFactoryTest;
511
512 /** Used to control how we initialize the service. */
513 ComponentName mTopComponent;
514 String mTopAction = Intent.ACTION_MAIN;
515 String mTopData;
516
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800517 /** Profiling app information. */
518 String mProfileApp = null;
519 WindowProcessController mProfileProc = null;
520 ProfilerInfo mProfilerInfo = null;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700523 * Dump of the activity state at the time of the last ANR. Cleared after
524 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
525 */
526 String mLastANRState;
527
528 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 * Used to retain an update lock when the foreground activity is in
530 * immersive mode.
531 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700532 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533
534 /**
535 * Packages that are being allowed to perform unrestricted app switches. Mapping is
536 * User -> Type -> uid.
537 */
538 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
539
540 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700541 private int mThumbnailWidth;
542 private int mThumbnailHeight;
543 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Flag that indicates if multi-window is enabled.
547 *
548 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
549 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
550 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
551 * At least one of the forms of multi-window must be enabled in order for this flag to be
552 * initialized to 'true'.
553 *
554 * @see #mSupportsSplitScreenMultiWindow
555 * @see #mSupportsFreeformWindowManagement
556 * @see #mSupportsPictureInPicture
557 * @see #mSupportsMultiDisplay
558 */
559 boolean mSupportsMultiWindow;
560 boolean mSupportsSplitScreenMultiWindow;
561 boolean mSupportsFreeformWindowManagement;
562 boolean mSupportsPictureInPicture;
563 boolean mSupportsMultiDisplay;
564 boolean mForceResizableActivities;
565
566 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
567
568 // VR Vr2d Display Id.
569 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700570
Wale Ogunwalef6733932018-06-27 05:14:34 -0700571 /**
572 * Set while we are wanting to sleep, to prevent any
573 * activities from being started/resumed.
574 *
575 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
576 *
577 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
578 * while in the sleep state until there is a pending transition out of sleep, in which case
579 * mSleeping is set to false, and remains false while awake.
580 *
581 * Whether mSleeping can quickly toggled between true/false without the device actually
582 * display changing states is undefined.
583 */
584 private boolean mSleeping = false;
585
586 /**
587 * The process state used for processes that are running the top activities.
588 * This changes between TOP and TOP_SLEEPING to following mSleeping.
589 */
590 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
591
592 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
593 // automatically. Important for devices without direct input devices.
594 private boolean mShowDialogs = true;
595
596 /** Set if we are shutting down the system, similar to sleeping. */
597 boolean mShuttingDown = false;
598
599 /**
600 * We want to hold a wake lock while running a voice interaction session, since
601 * this may happen with the screen off and we need to keep the CPU running to
602 * be able to continue to interact with the user.
603 */
604 PowerManager.WakeLock mVoiceWakeLock;
605
606 /**
607 * Set while we are running a voice interaction. This overrides sleeping while it is active.
608 */
609 IVoiceInteractionSession mRunningVoice;
610
611 /**
612 * The last resumed activity. This is identical to the current resumed activity most
613 * of the time but could be different when we're pausing one activity before we resume
614 * another activity.
615 */
616 ActivityRecord mLastResumedActivity;
617
618 /**
619 * The activity that is currently being traced as the active resumed activity.
620 *
621 * @see #updateResumedAppTrace
622 */
623 private @Nullable ActivityRecord mTracedResumedActivity;
624
625 /** If non-null, we are tracking the time the user spends in the currently focused app. */
626 AppTimeTracker mCurAppTimeTracker;
627
Wale Ogunwale008163e2018-07-23 23:11:08 -0700628 private AppWarnings mAppWarnings;
629
Wale Ogunwale53783742018-09-16 10:21:51 -0700630 /**
631 * Packages that the user has asked to have run in screen size
632 * compatibility mode instead of filling the screen.
633 */
634 CompatModePackages mCompatModePackages;
635
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 private FontScaleSettingObserver mFontScaleSettingObserver;
637
Ricky Wai96f5c352019-04-10 18:40:17 +0100638 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000639
Wale Ogunwalef6733932018-06-27 05:14:34 -0700640 private final class FontScaleSettingObserver extends ContentObserver {
641 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
642 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
643
644 public FontScaleSettingObserver() {
645 super(mH);
646 final ContentResolver resolver = mContext.getContentResolver();
647 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
648 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
649 UserHandle.USER_ALL);
650 }
651
652 @Override
653 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
654 if (mFontScaleUri.equals(uri)) {
655 updateFontScaleIfNeeded(userId);
656 } else if (mHideErrorDialogsUri.equals(uri)) {
657 synchronized (mGlobalLock) {
658 updateShouldShowDialogsLocked(getGlobalConfiguration());
659 }
660 }
661 }
662 }
663
Riddle Hsua0536432019-02-16 00:38:59 +0800664 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
665 @Target(ElementType.METHOD)
666 @Retention(RetentionPolicy.SOURCE)
667 @interface HotPath {
668 int NONE = 0;
669 int OOM_ADJUSTMENT = 1;
670 int LRU_UPDATE = 2;
671 int PROCESS_CHANGE = 3;
672 int caller() default NONE;
673 }
674
Charles Chen8d98dd22018-12-26 17:36:54 +0800675 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
676 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700677 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700678 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700679 mSystemThread = ActivityThread.currentActivityThread();
680 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700681 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800682 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700683 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 }
685
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700686 public void onSystemReady() {
687 synchronized (mGlobalLock) {
688 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
689 PackageManager.FEATURE_CANT_SAVE_STATE);
690 mAssistUtils = new AssistUtils(mContext);
691 mVrController.onSystemReady();
692 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700693 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onInitPowerManagement() {
698 synchronized (mGlobalLock) {
699 mStackSupervisor.initPowerManagement();
700 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
701 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
702 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
703 mVoiceWakeLock.setReferenceCounted(false);
704 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700705 }
706
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700707 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700708 mFontScaleSettingObserver = new FontScaleSettingObserver();
709 }
710
Wale Ogunwale59507092018-10-29 09:00:30 -0700711 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700712 final boolean freeformWindowManagement =
713 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
714 || Settings.Global.getInt(
715 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
716
717 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
718 final boolean supportsPictureInPicture = supportsMultiWindow &&
719 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
720 final boolean supportsSplitScreenMultiWindow =
721 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
722 final boolean supportsMultiDisplay = mContext.getPackageManager()
723 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700724 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
725 final boolean forceResizable = Settings.Global.getInt(
726 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700727 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700728
729 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900730 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731
732 final Configuration configuration = new Configuration();
733 Settings.System.getConfiguration(resolver, configuration);
734 if (forceRtl) {
735 // This will take care of setting the correct layout direction flags
736 configuration.setLayoutDirection(configuration.locale);
737 }
738
739 synchronized (mGlobalLock) {
740 mForceResizableActivities = forceResizable;
741 final boolean multiWindowFormEnabled = freeformWindowManagement
742 || supportsSplitScreenMultiWindow
743 || supportsPictureInPicture
744 || supportsMultiDisplay;
745 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
746 mSupportsMultiWindow = true;
747 mSupportsFreeformWindowManagement = freeformWindowManagement;
748 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
749 mSupportsPictureInPicture = supportsPictureInPicture;
750 mSupportsMultiDisplay = supportsMultiDisplay;
751 } else {
752 mSupportsMultiWindow = false;
753 mSupportsFreeformWindowManagement = false;
754 mSupportsSplitScreenMultiWindow = false;
755 mSupportsPictureInPicture = false;
756 mSupportsMultiDisplay = false;
757 }
758 mWindowManager.setForceResizableTasks(mForceResizableActivities);
759 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700760 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
761 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700762 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763 // This happens before any activities are started, so we can change global configuration
764 // in-place.
765 updateConfigurationLocked(configuration, null, true);
766 final Configuration globalConfig = getGlobalConfiguration();
767 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
768
769 // Load resources only after the current configuration has been set.
770 final Resources res = mContext.getResources();
771 mThumbnailWidth = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_width);
773 mThumbnailHeight = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_height);
775
776 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
777 mFullscreenThumbnailScale = (float) res
778 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
779 (float) globalConfig.screenWidthDp;
780 } else {
781 mFullscreenThumbnailScale = res.getFraction(
782 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
783 }
784 }
785 }
786
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800787 public WindowManagerGlobalLock getGlobalLock() {
788 return mGlobalLock;
789 }
790
Yunfan Chen585f2932019-01-29 16:04:45 +0900791 /** For test purpose only. */
792 @VisibleForTesting
793 public ActivityTaskManagerInternal getAtmInternal() {
794 return mInternal;
795 }
796
Riddle Hsud93a6c42018-11-29 21:50:06 +0800797 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
798 Looper looper) {
799 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700800 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700801 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700802 final File systemDir = SystemServiceManager.ensureSystemDir();
803 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
804 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700805 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
807 mTempConfig.setToDefaults();
808 mTempConfig.setLocales(LocaleList.getDefault());
809 mConfigurationSeq = mTempConfig.seq = 1;
810 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800811 mRootActivityContainer = new RootActivityContainer(this);
812 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700813
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700815 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700818 mRecentTasks = createRecentTasks();
819 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700877 protected RecentTasks createRecentTasks() {
878 return new RecentTasks(this, mStackSupervisor);
879 }
880
881 RecentTasks getRecentTasks() {
882 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700883 }
884
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700885 ClientLifecycleManager getLifecycleManager() {
886 return mLifecycleManager;
887 }
888
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700889 ActivityStartController getActivityStartController() {
890 return mActivityStartController;
891 }
892
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700893 TaskChangeNotificationController getTaskChangeNotificationController() {
894 return mTaskChangeNotificationController;
895 }
896
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700897 LockTaskController getLockTaskController() {
898 return mLockTaskController;
899 }
900
Yunfan Chen75157d72018-07-27 14:47:21 +0900901 /**
902 * Return the global configuration used by the process corresponding to the input pid. This is
903 * usually the global configuration with some overrides specific to that process.
904 */
905 Configuration getGlobalConfigurationForCallingPid() {
906 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800907 return getGlobalConfigurationForPid(pid);
908 }
909
910 /**
911 * Return the global configuration used by the process corresponding to the given pid.
912 */
913 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900914 if (pid == MY_PID || pid < 0) {
915 return getGlobalConfiguration();
916 }
917 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100918 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900919 return app != null ? app.getConfiguration() : getGlobalConfiguration();
920 }
921 }
922
923 /**
924 * Return the device configuration info used by the process corresponding to the input pid.
925 * The value is consistent with the global configuration for the process.
926 */
927 @Override
928 public ConfigurationInfo getDeviceConfigurationInfo() {
929 ConfigurationInfo config = new ConfigurationInfo();
930 synchronized (mGlobalLock) {
931 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
932 config.reqTouchScreen = globalConfig.touchscreen;
933 config.reqKeyboardType = globalConfig.keyboard;
934 config.reqNavigation = globalConfig.navigation;
935 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
936 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
937 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
938 }
939 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
940 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
941 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
942 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700943 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900944 }
945 return config;
946 }
947
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700948 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700949 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700950 }
951
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700952 public static final class Lifecycle extends SystemService {
953 private final ActivityTaskManagerService mService;
954
955 public Lifecycle(Context context) {
956 super(context);
957 mService = new ActivityTaskManagerService(context);
958 }
959
960 @Override
961 public void onStart() {
962 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700963 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700964 }
965
Garfield Tan891146c2018-10-09 12:14:00 -0700966 @Override
967 public void onUnlockUser(int userId) {
968 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800969 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700970 }
971 }
972
973 @Override
974 public void onCleanupUser(int userId) {
975 synchronized (mService.getGlobalLock()) {
976 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
977 }
978 }
979
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 public ActivityTaskManagerService getService() {
981 return mService;
982 }
983 }
984
985 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 public final int startActivity(IApplicationThread caller, String callingPackage,
987 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
988 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
989 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
990 resultWho, requestCode, startFlags, profilerInfo, bOptions,
991 UserHandle.getCallingUserId());
992 }
993
994 @Override
995 public final int startActivities(IApplicationThread caller, String callingPackage,
996 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
997 int userId) {
998 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700999 enforceNotIsolatedCaller(reason);
1000 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001001 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001002 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1003 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1004 reason, null /* originatingPendingIntent */,
1005 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001006 }
1007
1008 @Override
1009 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1010 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1011 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1012 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1013 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1014 true /*validateIncomingUser*/);
1015 }
1016
1017 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1018 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1019 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1020 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001021 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001023 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1025
1026 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001027 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 .setCaller(caller)
1029 .setCallingPackage(callingPackage)
1030 .setResolvedType(resolvedType)
1031 .setResultTo(resultTo)
1032 .setResultWho(resultWho)
1033 .setRequestCode(requestCode)
1034 .setStartFlags(startFlags)
1035 .setProfilerInfo(profilerInfo)
1036 .setActivityOptions(bOptions)
1037 .setMayWait(userId)
1038 .execute();
1039
1040 }
1041
1042 @Override
1043 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1044 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001045 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1046 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 // Refuse possible leaked file descriptors
1048 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1049 throw new IllegalArgumentException("File descriptors passed in Intent");
1050 }
1051
1052 if (!(target instanceof PendingIntentRecord)) {
1053 throw new IllegalArgumentException("Bad PendingIntent object");
1054 }
1055
1056 PendingIntentRecord pir = (PendingIntentRecord)target;
1057
1058 synchronized (mGlobalLock) {
1059 // If this is coming from the currently resumed activity, it is
1060 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001061 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 if (stack.mResumedActivity != null &&
1063 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 }
1066 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001067 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 }
1070
1071 @Override
1072 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1073 Bundle bOptions) {
1074 // Refuse possible leaked file descriptors
1075 if (intent != null && intent.hasFileDescriptors()) {
1076 throw new IllegalArgumentException("File descriptors passed in Intent");
1077 }
1078 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1079
1080 synchronized (mGlobalLock) {
1081 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1082 if (r == null) {
1083 SafeActivityOptions.abort(options);
1084 return false;
1085 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001086 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 // The caller is not running... d'oh!
1088 SafeActivityOptions.abort(options);
1089 return false;
1090 }
1091 intent = new Intent(intent);
1092 // The caller is not allowed to change the data.
1093 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1094 // And we are resetting to find the next component...
1095 intent.setComponent(null);
1096
1097 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1098
1099 ActivityInfo aInfo = null;
1100 try {
1101 List<ResolveInfo> resolves =
1102 AppGlobals.getPackageManager().queryIntentActivities(
1103 intent, r.resolvedType,
1104 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1105 UserHandle.getCallingUserId()).getList();
1106
1107 // Look for the original activity in the list...
1108 final int N = resolves != null ? resolves.size() : 0;
1109 for (int i=0; i<N; i++) {
1110 ResolveInfo rInfo = resolves.get(i);
1111 if (rInfo.activityInfo.packageName.equals(r.packageName)
1112 && rInfo.activityInfo.name.equals(r.info.name)) {
1113 // We found the current one... the next matching is
1114 // after it.
1115 i++;
1116 if (i<N) {
1117 aInfo = resolves.get(i).activityInfo;
1118 }
1119 if (debug) {
1120 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1121 + "/" + r.info.name);
1122 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1123 ? "null" : aInfo.packageName + "/" + aInfo.name));
1124 }
1125 break;
1126 }
1127 }
1128 } catch (RemoteException e) {
1129 }
1130
1131 if (aInfo == null) {
1132 // Nobody who is next!
1133 SafeActivityOptions.abort(options);
1134 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1135 return false;
1136 }
1137
1138 intent.setComponent(new ComponentName(
1139 aInfo.applicationInfo.packageName, aInfo.name));
1140 intent.setFlags(intent.getFlags()&~(
1141 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1142 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1143 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1144 FLAG_ACTIVITY_NEW_TASK));
1145
1146 // Okay now we need to start the new activity, replacing the currently running activity.
1147 // This is a little tricky because we want to start the new one as if the current one is
1148 // finished, but not finish the current one first so that there is no flicker.
1149 // And thus...
1150 final boolean wasFinishing = r.finishing;
1151 r.finishing = true;
1152
1153 // Propagate reply information over to the new activity.
1154 final ActivityRecord resultTo = r.resultTo;
1155 final String resultWho = r.resultWho;
1156 final int requestCode = r.requestCode;
1157 r.resultTo = null;
1158 if (resultTo != null) {
1159 resultTo.removeResultsLocked(r, resultWho, requestCode);
1160 }
1161
1162 final long origId = Binder.clearCallingIdentity();
1163 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001164 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001165 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001166 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001167 .setResolvedType(r.resolvedType)
1168 .setActivityInfo(aInfo)
1169 .setResultTo(resultTo != null ? resultTo.appToken : null)
1170 .setResultWho(resultWho)
1171 .setRequestCode(requestCode)
1172 .setCallingPid(-1)
1173 .setCallingUid(r.launchedFromUid)
1174 .setCallingPackage(r.launchedFromPackage)
1175 .setRealCallingPid(-1)
1176 .setRealCallingUid(r.launchedFromUid)
1177 .setActivityOptions(options)
1178 .execute();
1179 Binder.restoreCallingIdentity(origId);
1180
1181 r.finishing = wasFinishing;
1182 if (res != ActivityManager.START_SUCCESS) {
1183 return false;
1184 }
1185 return true;
1186 }
1187 }
1188
1189 @Override
1190 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1191 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1192 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1193 final WaitResult res = new WaitResult();
1194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001195 enforceNotIsolatedCaller("startActivityAndWait");
1196 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1197 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001198 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001199 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001200 .setCaller(caller)
1201 .setCallingPackage(callingPackage)
1202 .setResolvedType(resolvedType)
1203 .setResultTo(resultTo)
1204 .setResultWho(resultWho)
1205 .setRequestCode(requestCode)
1206 .setStartFlags(startFlags)
1207 .setActivityOptions(bOptions)
1208 .setMayWait(userId)
1209 .setProfilerInfo(profilerInfo)
1210 .setWaitResult(res)
1211 .execute();
1212 }
1213 return res;
1214 }
1215
1216 @Override
1217 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1218 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1219 int startFlags, Configuration config, Bundle bOptions, int userId) {
1220 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001221 enforceNotIsolatedCaller("startActivityWithConfig");
1222 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1223 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001225 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 .setCaller(caller)
1227 .setCallingPackage(callingPackage)
1228 .setResolvedType(resolvedType)
1229 .setResultTo(resultTo)
1230 .setResultWho(resultWho)
1231 .setRequestCode(requestCode)
1232 .setStartFlags(startFlags)
1233 .setGlobalConfiguration(config)
1234 .setActivityOptions(bOptions)
1235 .setMayWait(userId)
1236 .execute();
1237 }
1238 }
1239
Alison Cichowlas3e340502018-08-07 17:15:01 -04001240
1241 @Override
1242 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1243 int callingUid = Binder.getCallingUid();
1244 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1245 throw new SecurityException("Only the system process can request a permission token, "
1246 + "received request from uid: " + callingUid);
1247 }
1248 IBinder permissionToken = new Binder();
1249 synchronized (mGlobalLock) {
1250 mStartActivitySources.put(permissionToken, delegatorToken);
1251 }
1252
1253 Message expireMsg = PooledLambda.obtainMessage(
1254 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1255 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1256
1257 Message forgetMsg = PooledLambda.obtainMessage(
1258 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1259 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1260
1261 return permissionToken;
1262 }
1263
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 @Override
1265 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1266 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1268 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001269 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001270 // permission grants) as any app that may launch one of your own activities. So we only
1271 // allow this in two cases:
1272 // 1) The caller is an activity that is part of the core framework, and then only when it
1273 // is running as the system.
1274 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1275 // can only be requested by a system activity, which may then delegate this call to
1276 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 final ActivityRecord sourceRecord;
1278 final int targetUid;
1279 final String targetPackage;
1280 final boolean isResolver;
1281 synchronized (mGlobalLock) {
1282 if (resultTo == null) {
1283 throw new SecurityException("Must be called from an activity");
1284 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285 final IBinder sourceToken;
1286 if (permissionToken != null) {
1287 // To even attempt to use a permissionToken, an app must also have this signature
1288 // permission.
1289 mAmInternal.enforceCallingPermission(
1290 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1291 "startActivityAsCaller");
1292 // If called with a permissionToken, we want the sourceRecord from the delegator
1293 // activity that requested this token.
1294 sourceToken = mStartActivitySources.remove(permissionToken);
1295 if (sourceToken == null) {
1296 // Invalid permissionToken, check if it recently expired.
1297 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1298 throw new SecurityException("Called with expired permission token: "
1299 + permissionToken);
1300 } else {
1301 throw new SecurityException("Called with invalid permission token: "
1302 + permissionToken);
1303 }
1304 }
1305 } else {
1306 // This method was called directly by the source.
1307 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001308 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001309
Wale Ogunwaled32da472018-11-16 07:19:28 -08001310 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001311 if (sourceRecord == null) {
1312 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 }
1314 if (sourceRecord.app == null) {
1315 throw new SecurityException("Called without a process attached to activity");
1316 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001317
1318 // Whether called directly or from a delegate, the source activity must be from the
1319 // android package.
1320 if (!sourceRecord.info.packageName.equals("android")) {
1321 throw new SecurityException("Must be called from an activity that is "
1322 + "declared in the android package");
1323 }
1324
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001325 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 // This is still okay, as long as this activity is running under the
1327 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001328 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001330 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001331 + " must be system uid or original calling uid "
1332 + sourceRecord.launchedFromUid);
1333 }
1334 }
1335 if (ignoreTargetSecurity) {
1336 if (intent.getComponent() == null) {
1337 throw new SecurityException(
1338 "Component must be specified with ignoreTargetSecurity");
1339 }
1340 if (intent.getSelector() != null) {
1341 throw new SecurityException(
1342 "Selector not allowed with ignoreTargetSecurity");
1343 }
1344 }
1345 targetUid = sourceRecord.launchedFromUid;
1346 targetPackage = sourceRecord.launchedFromPackage;
1347 isResolver = sourceRecord.isResolverOrChildActivity();
1348 }
1349
1350 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001351 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001352 }
1353
1354 // TODO: Switch to user app stacks here.
1355 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001356 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 .setCallingUid(targetUid)
1358 .setCallingPackage(targetPackage)
1359 .setResolvedType(resolvedType)
1360 .setResultTo(resultTo)
1361 .setResultWho(resultWho)
1362 .setRequestCode(requestCode)
1363 .setStartFlags(startFlags)
1364 .setActivityOptions(bOptions)
1365 .setMayWait(userId)
1366 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1367 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1368 .execute();
1369 } catch (SecurityException e) {
1370 // XXX need to figure out how to propagate to original app.
1371 // A SecurityException here is generally actually a fault of the original
1372 // calling activity (such as a fairly granting permissions), so propagate it
1373 // back to them.
1374 /*
1375 StringBuilder msg = new StringBuilder();
1376 msg.append("While launching");
1377 msg.append(intent.toString());
1378 msg.append(": ");
1379 msg.append(e.getMessage());
1380 */
1381 throw e;
1382 }
1383 }
1384
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001385 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1386 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1387 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1388 }
1389
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 @Override
1391 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1392 Intent intent, String resolvedType, IVoiceInteractionSession session,
1393 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1394 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001395 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 if (session == null || interactor == null) {
1397 throw new NullPointerException("null session or interactor");
1398 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001401 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 .setCallingUid(callingUid)
1403 .setCallingPackage(callingPackage)
1404 .setResolvedType(resolvedType)
1405 .setVoiceSession(session)
1406 .setVoiceInteractor(interactor)
1407 .setStartFlags(startFlags)
1408 .setProfilerInfo(profilerInfo)
1409 .setActivityOptions(bOptions)
1410 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001411 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 .execute();
1413 }
1414
1415 @Override
1416 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1417 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1419 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001421 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001422 .setCallingUid(callingUid)
1423 .setCallingPackage(callingPackage)
1424 .setResolvedType(resolvedType)
1425 .setActivityOptions(bOptions)
1426 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001427 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 .execute();
1429 }
1430
1431 @Override
1432 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1433 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435 final int callingPid = Binder.getCallingPid();
1436 final long origId = Binder.clearCallingIdentity();
1437 try {
1438 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001439 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1440 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441
1442 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1444 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1446 recentsUid, assistDataReceiver);
1447 }
1448 } finally {
1449 Binder.restoreCallingIdentity(origId);
1450 }
1451 }
1452
1453 @Override
1454 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 "startActivityFromRecents()");
1457
1458 final int callingPid = Binder.getCallingPid();
1459 final int callingUid = Binder.getCallingUid();
1460 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1461 final long origId = Binder.clearCallingIdentity();
1462 try {
1463 synchronized (mGlobalLock) {
1464 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1465 safeOptions);
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(origId);
1469 }
1470 }
1471
1472 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001473 * Public API to check if the client is allowed to start an activity on specified display.
1474 *
1475 * If the target display is private or virtual, some restrictions will apply.
1476 *
1477 * @param displayId Target display id.
1478 * @param intent Intent used to launch the activity.
1479 * @param resolvedType The MIME type of the intent.
1480 * @param userId The id of the user for whom the call is made.
1481 * @return {@code true} if a call to start an activity on the target display should succeed and
1482 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1483 */
1484 @Override
1485 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1486 String resolvedType, int userId) {
1487 final int callingUid = Binder.getCallingUid();
1488 final int callingPid = Binder.getCallingPid();
1489 final long origId = Binder.clearCallingIdentity();
1490
1491 try {
1492 // Collect information about the target of the Intent.
1493 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1494 0 /* startFlags */, null /* profilerInfo */, userId,
1495 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1496 UserHandle.USER_NULL));
1497 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1498
1499 synchronized (mGlobalLock) {
1500 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1501 aInfo);
1502 }
1503 } finally {
1504 Binder.restoreCallingIdentity(origId);
1505 }
1506 }
1507
1508 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 * This is the internal entry point for handling Activity.finish().
1510 *
1511 * @param token The Binder token referencing the Activity we want to finish.
1512 * @param resultCode Result code, if any, from this Activity.
1513 * @param resultData Result data (Intent), if any, from this Activity.
1514 * @param finishTask Whether to finish the task associated with this Activity.
1515 *
1516 * @return Returns true if the activity successfully finished, or false if it is still running.
1517 */
1518 @Override
1519 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1520 int finishTask) {
1521 // Refuse possible leaked file descriptors
1522 if (resultData != null && resultData.hasFileDescriptors()) {
1523 throw new IllegalArgumentException("File descriptors passed in Intent");
1524 }
1525
1526 synchronized (mGlobalLock) {
1527 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1528 if (r == null) {
1529 return true;
1530 }
1531 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001532 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 ActivityRecord rootR = tr.getRootActivity();
1534 if (rootR == null) {
1535 Slog.w(TAG, "Finishing task with all activities already finished");
1536 }
1537 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1538 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001539 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001540 return false;
1541 }
1542
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001543 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1544 // We should consolidate.
1545 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001547 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001548 if (next != null) {
1549 // ask watcher if this is allowed
1550 boolean resumeOK = true;
1551 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001552 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001554 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 Watchdog.getInstance().setActivityController(null);
1556 }
1557
1558 if (!resumeOK) {
1559 Slog.i(TAG, "Not finishing activity because controller resumed");
1560 return false;
1561 }
1562 }
1563 }
1564 final long origId = Binder.clearCallingIdentity();
1565 try {
1566 boolean res;
1567 final boolean finishWithRootActivity =
1568 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1569 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1570 || (finishWithRootActivity && r == rootR)) {
1571 // If requested, remove the task that is associated to this activity only if it
1572 // was the root activity in the task. The result code and data is ignored
1573 // because we don't support returning them across task boundaries. Also, to
1574 // keep backwards compatibility we remove the task from recents when finishing
1575 // task with root activity.
1576 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1577 finishWithRootActivity, "finish-activity");
1578 if (!res) {
1579 Slog.i(TAG, "Removing task failed to finish activity");
1580 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001581 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001582 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 } else {
1584 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1585 resultData, "app-request", true);
1586 if (!res) {
1587 Slog.i(TAG, "Failed to finish by app-request");
1588 }
1589 }
1590 return res;
1591 } finally {
1592 Binder.restoreCallingIdentity(origId);
1593 }
1594 }
1595 }
1596
1597 @Override
1598 public boolean finishActivityAffinity(IBinder token) {
1599 synchronized (mGlobalLock) {
1600 final long origId = Binder.clearCallingIdentity();
1601 try {
1602 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1603 if (r == null) {
1604 return false;
1605 }
1606
1607 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1608 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001609 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001610 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 return false;
1612 }
1613 return task.getStack().finishActivityAffinityLocked(r);
1614 } finally {
1615 Binder.restoreCallingIdentity(origId);
1616 }
1617 }
1618 }
1619
1620 @Override
1621 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1622 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001623 try {
1624 WindowProcessController proc = null;
1625 synchronized (mGlobalLock) {
1626 ActivityStack stack = ActivityRecord.getStackLocked(token);
1627 if (stack == null) {
1628 return;
1629 }
1630 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1631 false /* fromTimeout */, false /* processPausingActivities */, config);
1632 if (r != null) {
1633 proc = r.app;
1634 }
1635 if (stopProfiling && proc != null) {
1636 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 }
1638 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001639 } finally {
1640 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 }
1643
1644 @Override
1645 public final void activityResumed(IBinder token) {
1646 final long origId = Binder.clearCallingIdentity();
1647 synchronized (mGlobalLock) {
1648 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001649 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 }
1651 Binder.restoreCallingIdentity(origId);
1652 }
1653
1654 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001655 public final void activityTopResumedStateLost() {
1656 final long origId = Binder.clearCallingIdentity();
1657 synchronized (mGlobalLock) {
1658 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1659 }
1660 Binder.restoreCallingIdentity(origId);
1661 }
1662
1663 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001664 public final void activityPaused(IBinder token) {
1665 final long origId = Binder.clearCallingIdentity();
1666 synchronized (mGlobalLock) {
1667 ActivityStack stack = ActivityRecord.getStackLocked(token);
1668 if (stack != null) {
1669 stack.activityPausedLocked(token, false);
1670 }
1671 }
1672 Binder.restoreCallingIdentity(origId);
1673 }
1674
1675 @Override
1676 public final void activityStopped(IBinder token, Bundle icicle,
1677 PersistableBundle persistentState, CharSequence description) {
1678 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1679
1680 // Refuse possible leaked file descriptors
1681 if (icicle != null && icicle.hasFileDescriptors()) {
1682 throw new IllegalArgumentException("File descriptors passed in Bundle");
1683 }
1684
1685 final long origId = Binder.clearCallingIdentity();
1686
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001687 String restartingName = null;
1688 int restartingUid = 0;
1689 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001691 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001692 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001693 if (r.attachedToProcess()
1694 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1695 // The activity was requested to restart from
1696 // {@link #restartActivityProcessIfVisible}.
1697 restartingName = r.app.mName;
1698 restartingUid = r.app.mUid;
1699 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 r.activityStoppedLocked(icicle, persistentState, description);
1701 }
1702 }
1703
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001704 if (restartingName != null) {
1705 // In order to let the foreground activity can be restarted with its saved state from
1706 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1707 // until the activity reports stopped with the state. And the activity record will be
1708 // kept because the record state is restarting, then the activity will be restarted
1709 // immediately if it is still the top one.
1710 mStackSupervisor.removeRestartTimeouts(r);
1711 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1712 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001713 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714
1715 Binder.restoreCallingIdentity(origId);
1716 }
1717
1718 @Override
1719 public final void activityDestroyed(IBinder token) {
1720 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1721 synchronized (mGlobalLock) {
1722 ActivityStack stack = ActivityRecord.getStackLocked(token);
1723 if (stack != null) {
1724 stack.activityDestroyedLocked(token, "activityDestroyed");
1725 }
1726 }
1727 }
1728
1729 @Override
1730 public final void activityRelaunched(IBinder token) {
1731 final long origId = Binder.clearCallingIdentity();
1732 synchronized (mGlobalLock) {
1733 mStackSupervisor.activityRelaunchedLocked(token);
1734 }
1735 Binder.restoreCallingIdentity(origId);
1736 }
1737
1738 public final void activitySlept(IBinder token) {
1739 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1740
1741 final long origId = Binder.clearCallingIdentity();
1742
1743 synchronized (mGlobalLock) {
1744 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1745 if (r != null) {
1746 mStackSupervisor.activitySleptLocked(r);
1747 }
1748 }
1749
1750 Binder.restoreCallingIdentity(origId);
1751 }
1752
1753 @Override
1754 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1755 synchronized (mGlobalLock) {
1756 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1757 if (r == null) {
1758 return;
1759 }
1760 final long origId = Binder.clearCallingIdentity();
1761 try {
1762 r.setRequestedOrientation(requestedOrientation);
1763 } finally {
1764 Binder.restoreCallingIdentity(origId);
1765 }
1766 }
1767 }
1768
1769 @Override
1770 public int getRequestedOrientation(IBinder token) {
1771 synchronized (mGlobalLock) {
1772 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1773 if (r == null) {
1774 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1775 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001776 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001777 }
1778 }
1779
1780 @Override
1781 public void setImmersive(IBinder token, boolean immersive) {
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r == null) {
1785 throw new IllegalArgumentException();
1786 }
1787 r.immersive = immersive;
1788
1789 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001790 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001792 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793 }
1794 }
1795 }
1796
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001797 void applyUpdateLockStateLocked(ActivityRecord r) {
1798 // Modifications to the UpdateLock state are done on our handler, outside
1799 // the activity manager's locks. The new state is determined based on the
1800 // state *now* of the relevant activity record. The object is passed to
1801 // the handler solely for logging detail, not to be consulted/modified.
1802 final boolean nextState = r != null && r.immersive;
1803 mH.post(() -> {
1804 if (mUpdateLock.isHeld() != nextState) {
1805 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1806 "Applying new update lock state '" + nextState + "' for " + r);
1807 if (nextState) {
1808 mUpdateLock.acquire();
1809 } else {
1810 mUpdateLock.release();
1811 }
1812 }
1813 });
1814 }
1815
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 @Override
1817 public boolean isImmersive(IBinder token) {
1818 synchronized (mGlobalLock) {
1819 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r == null) {
1821 throw new IllegalArgumentException();
1822 }
1823 return r.immersive;
1824 }
1825 }
1826
1827 @Override
1828 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001829 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001831 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 return (r != null) ? r.immersive : false;
1833 }
1834 }
1835
1836 @Override
1837 public void overridePendingTransition(IBinder token, String packageName,
1838 int enterAnim, int exitAnim) {
1839 synchronized (mGlobalLock) {
1840 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1841 if (self == null) {
1842 return;
1843 }
1844
1845 final long origId = Binder.clearCallingIdentity();
1846
1847 if (self.isState(
1848 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001849 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001850 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 }
1852
1853 Binder.restoreCallingIdentity(origId);
1854 }
1855 }
1856
1857 @Override
1858 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001861 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 if (r == null) {
1863 return ActivityManager.COMPAT_MODE_UNKNOWN;
1864 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001865 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 }
1867 }
1868
1869 @Override
1870 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001873 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001874 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001875 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 if (r == null) {
1877 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1878 return;
1879 }
1880 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001881 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001882 }
1883 }
1884
1885 @Override
1886 public int getLaunchedFromUid(IBinder activityToken) {
1887 ActivityRecord srec;
1888 synchronized (mGlobalLock) {
1889 srec = ActivityRecord.forTokenLocked(activityToken);
1890 }
1891 if (srec == null) {
1892 return -1;
1893 }
1894 return srec.launchedFromUid;
1895 }
1896
1897 @Override
1898 public String getLaunchedFromPackage(IBinder activityToken) {
1899 ActivityRecord srec;
1900 synchronized (mGlobalLock) {
1901 srec = ActivityRecord.forTokenLocked(activityToken);
1902 }
1903 if (srec == null) {
1904 return null;
1905 }
1906 return srec.launchedFromPackage;
1907 }
1908
1909 @Override
1910 public boolean convertFromTranslucent(IBinder token) {
1911 final long origId = Binder.clearCallingIdentity();
1912 try {
1913 synchronized (mGlobalLock) {
1914 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1915 if (r == null) {
1916 return false;
1917 }
1918 final boolean translucentChanged = r.changeWindowTranslucency(true);
1919 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001920 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 return translucentChanged;
1924 }
1925 } finally {
1926 Binder.restoreCallingIdentity(origId);
1927 }
1928 }
1929
1930 @Override
1931 public boolean convertToTranslucent(IBinder token, Bundle options) {
1932 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1933 final long origId = Binder.clearCallingIdentity();
1934 try {
1935 synchronized (mGlobalLock) {
1936 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1937 if (r == null) {
1938 return false;
1939 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001940 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 int index = task.mActivities.lastIndexOf(r);
1942 if (index > 0) {
1943 ActivityRecord under = task.mActivities.get(index - 1);
1944 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1945 }
1946 final boolean translucentChanged = r.changeWindowTranslucency(false);
1947 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001948 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001950 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 return translucentChanged;
1953 }
1954 } finally {
1955 Binder.restoreCallingIdentity(origId);
1956 }
1957 }
1958
1959 @Override
1960 public void notifyActivityDrawn(IBinder token) {
1961 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1962 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001965 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 }
1967 }
1968 }
1969
1970 @Override
1971 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1972 synchronized (mGlobalLock) {
1973 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1974 if (r == null) {
1975 return;
1976 }
1977 r.reportFullyDrawnLocked(restoredFromBundle);
1978 }
1979 }
1980
1981 @Override
1982 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1983 synchronized (mGlobalLock) {
1984 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1985 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1986 return stack.mDisplayId;
1987 }
1988 return DEFAULT_DISPLAY;
1989 }
1990 }
1991
1992 @Override
1993 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001994 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 long ident = Binder.clearCallingIdentity();
1996 try {
1997 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001998 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002000 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 }
2002 return null;
2003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(ident);
2006 }
2007 }
2008
2009 @Override
2010 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002011 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2013 final long callingId = Binder.clearCallingIdentity();
2014 try {
2015 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002016 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 if (stack == null) {
2018 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2019 return;
2020 }
2021 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002022 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002023 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 }
2025 }
2026 } finally {
2027 Binder.restoreCallingIdentity(callingId);
2028 }
2029 }
2030
2031 @Override
2032 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2035 final long callingId = Binder.clearCallingIdentity();
2036 try {
2037 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002038 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002039 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 if (task == null) {
2041 return;
2042 }
2043 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002044 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002045 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 }
2047 }
2048 } finally {
2049 Binder.restoreCallingIdentity(callingId);
2050 }
2051 }
2052
2053 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002054 public void restartActivityProcessIfVisible(IBinder activityToken) {
2055 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2056 final long callingId = Binder.clearCallingIdentity();
2057 try {
2058 synchronized (mGlobalLock) {
2059 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2060 if (r == null) {
2061 return;
2062 }
2063 r.restartProcessIfVisible();
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(callingId);
2067 }
2068 }
2069
2070 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 synchronized (mGlobalLock) {
2074 final long ident = Binder.clearCallingIdentity();
2075 try {
2076 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2077 "remove-task");
2078 } finally {
2079 Binder.restoreCallingIdentity(ident);
2080 }
2081 }
2082 }
2083
2084 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002085 public void removeAllVisibleRecentTasks() {
2086 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2087 synchronized (mGlobalLock) {
2088 final long ident = Binder.clearCallingIdentity();
2089 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002090 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002091 } finally {
2092 Binder.restoreCallingIdentity(ident);
2093 }
2094 }
2095 }
2096
2097 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002098 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2099 synchronized (mGlobalLock) {
2100 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2101 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002102 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 }
2104 }
2105 return false;
2106 }
2107
2108 @Override
2109 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2110 Intent resultData) {
2111
2112 synchronized (mGlobalLock) {
2113 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2114 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002115 return r.getActivityStack().navigateUpToLocked(
2116 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002117 }
2118 return false;
2119 }
2120 }
2121
2122 /**
2123 * Attempts to move a task backwards in z-order (the order of activities within the task is
2124 * unchanged).
2125 *
2126 * There are several possible results of this call:
2127 * - if the task is locked, then we will show the lock toast
2128 * - if there is a task behind the provided task, then that task is made visible and resumed as
2129 * this task is moved to the back
2130 * - otherwise, if there are no other tasks in the stack:
2131 * - if this task is in the pinned stack, then we remove the stack completely, which will
2132 * have the effect of moving the task to the top or bottom of the fullscreen stack
2133 * (depending on whether it is visible)
2134 * - otherwise, we simply return home and hide this task
2135 *
2136 * @param token A reference to the activity we wish to move
2137 * @param nonRoot If false then this only works if the activity is the root
2138 * of a task; if true it will work for any activity in a task.
2139 * @return Returns true if the move completed, false if not.
2140 */
2141 @Override
2142 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002143 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 synchronized (mGlobalLock) {
2145 final long origId = Binder.clearCallingIdentity();
2146 try {
2147 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002148 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 if (task != null) {
2150 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2151 }
2152 } finally {
2153 Binder.restoreCallingIdentity(origId);
2154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002161 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002162 long ident = Binder.clearCallingIdentity();
2163 Rect rect = new Rect();
2164 try {
2165 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002166 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2168 if (task == null) {
2169 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2170 return rect;
2171 }
2172 if (task.getStack() != null) {
2173 // Return the bounds from window manager since it will be adjusted for various
2174 // things like the presense of a docked stack for tasks that aren't resizeable.
2175 task.getWindowContainerBounds(rect);
2176 } else {
2177 // Task isn't in window manager yet since it isn't associated with a stack.
2178 // Return the persist value from activity manager
2179 if (!task.matchParentBounds()) {
2180 rect.set(task.getBounds());
2181 } else if (task.mLastNonFullscreenBounds != null) {
2182 rect.set(task.mLastNonFullscreenBounds);
2183 }
2184 }
2185 }
2186 } finally {
2187 Binder.restoreCallingIdentity(ident);
2188 }
2189 return rect;
2190 }
2191
2192 @Override
2193 public ActivityManager.TaskDescription getTaskDescription(int id) {
2194 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002195 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002197 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2199 if (tr != null) {
2200 return tr.lastTaskDescription;
2201 }
2202 }
2203 return null;
2204 }
2205
2206 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002207 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2208 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2209 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2210 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2211 return;
2212 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002213 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002214 synchronized (mGlobalLock) {
2215 final long ident = Binder.clearCallingIdentity();
2216 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002217 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002218 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002219 if (task == null) {
2220 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2221 return;
2222 }
2223
2224 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2225 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2226
2227 if (!task.isActivityTypeStandardOrUndefined()) {
2228 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2229 + " non-standard task " + taskId + " to windowing mode="
2230 + windowingMode);
2231 }
2232
2233 final ActivityStack stack = task.getStack();
2234 if (toTop) {
2235 stack.moveToFront("setTaskWindowingMode", task);
2236 }
2237 stack.setWindowingMode(windowingMode);
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 }
2242 }
2243
2244 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002246 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 ActivityRecord r = getCallingRecordLocked(token);
2248 return r != null ? r.info.packageName : null;
2249 }
2250 }
2251
2252 @Override
2253 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002254 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002255 ActivityRecord r = getCallingRecordLocked(token);
2256 return r != null ? r.intent.getComponent() : null;
2257 }
2258 }
2259
2260 private ActivityRecord getCallingRecordLocked(IBinder token) {
2261 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2262 if (r == null) {
2263 return null;
2264 }
2265 return r.resultTo;
2266 }
2267
2268 @Override
2269 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002270 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271
2272 synchronized (mGlobalLock) {
2273 final long origId = Binder.clearCallingIdentity();
2274 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002275 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002276 } finally {
2277 Binder.restoreCallingIdentity(origId);
2278 }
2279 }
2280 }
2281
2282 /**
2283 * TODO: Add mController hook
2284 */
2285 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002286 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2287 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002288 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289
2290 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2291 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002292 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2293 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 }
2295 }
2296
Ricky Waiaca8a772019-04-04 16:01:06 +01002297 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2298 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 boolean fromRecents) {
2300
Ricky Waiaca8a772019-04-04 16:01:06 +01002301 final int callingPid = Binder.getCallingPid();
2302 final int callingUid = Binder.getCallingUid();
2303 if (!isSameApp(callingUid, callingPackage)) {
2304 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2305 + Binder.getCallingPid() + " as package " + callingPackage;
2306 Slog.w(TAG, msg);
2307 throw new SecurityException(msg);
2308 }
2309 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 SafeActivityOptions.abort(options);
2311 return;
2312 }
2313 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002314 WindowProcessController callerApp = null;
2315 if (appThread != null) {
2316 callerApp = getProcessController(appThread);
2317 }
2318 final ActivityStarter starter = getActivityStartController().obtainStarter(
2319 null /* intent */, "moveTaskToFront");
2320 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2321 -1, callerApp, null, false, null)) {
2322 boolean abort = !isBackgroundActivityStartsEnabled();
2323 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2324 if (abort) {
2325 return;
2326 }
2327 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002329 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002330 if (task == null) {
2331 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002332 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002333 return;
2334 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002335 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002337 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 return;
2339 }
2340 ActivityOptions realOptions = options != null
2341 ? options.getOptions(mStackSupervisor)
2342 : null;
2343 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2344 false /* forceNonResizable */);
2345
2346 final ActivityRecord topActivity = task.getTopActivity();
2347 if (topActivity != null) {
2348
2349 // We are reshowing a task, use a starting window to hide the initial draw delay
2350 // so the transition can start earlier.
2351 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2352 true /* taskSwitch */, fromRecents);
2353 }
2354 } finally {
2355 Binder.restoreCallingIdentity(origId);
2356 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357 }
2358
Ricky Waiaca8a772019-04-04 16:01:06 +01002359 /**
2360 * Return true if callingUid is system, or packageName belongs to that callingUid.
2361 */
2362 boolean isSameApp(int callingUid, @Nullable String packageName) {
2363 try {
2364 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2365 if (packageName == null) {
2366 return false;
2367 }
2368 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2369 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2370 UserHandle.getUserId(callingUid));
2371 return UserHandle.isSameApp(callingUid, uid);
2372 }
2373 } catch (RemoteException e) {
2374 // Should not happen
2375 }
2376 return true;
2377 }
2378
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002379 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2380 int callingPid, int callingUid, String name) {
2381 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2382 return true;
2383 }
2384
2385 if (getRecentTasks().isCallerRecents(sourceUid)) {
2386 return true;
2387 }
2388
2389 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2390 if (perm == PackageManager.PERMISSION_GRANTED) {
2391 return true;
2392 }
2393 if (checkAllowAppSwitchUid(sourceUid)) {
2394 return true;
2395 }
2396
2397 // If the actual IPC caller is different from the logical source, then
2398 // also see if they are allowed to control app switches.
2399 if (callingUid != -1 && callingUid != sourceUid) {
2400 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2401 if (perm == PackageManager.PERMISSION_GRANTED) {
2402 return true;
2403 }
2404 if (checkAllowAppSwitchUid(callingUid)) {
2405 return true;
2406 }
2407 }
2408
2409 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2410 return false;
2411 }
2412
2413 private boolean checkAllowAppSwitchUid(int uid) {
2414 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2415 if (types != null) {
2416 for (int i = types.size() - 1; i >= 0; i--) {
2417 if (types.valueAt(i).intValue() == uid) {
2418 return true;
2419 }
2420 }
2421 }
2422 return false;
2423 }
2424
2425 @Override
2426 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2427 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2428 "setActivityController()");
2429 synchronized (mGlobalLock) {
2430 mController = controller;
2431 mControllerIsAMonkey = imAMonkey;
2432 Watchdog.getInstance().setActivityController(controller);
2433 }
2434 }
2435
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002436 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002437 synchronized (mGlobalLock) {
2438 return mController != null && mControllerIsAMonkey;
2439 }
2440 }
2441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002442 @Override
2443 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2444 synchronized (mGlobalLock) {
2445 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2446 }
2447 }
2448
2449 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002450 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2451 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2452 }
2453
2454 @Override
2455 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2456 @WindowConfiguration.ActivityType int ignoreActivityType,
2457 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2458 final int callingUid = Binder.getCallingUid();
2459 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2460
2461 synchronized (mGlobalLock) {
2462 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2463
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002464 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002465 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002466 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002467 ignoreWindowingMode, callingUid, allowed);
2468 }
2469
2470 return list;
2471 }
2472
2473 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002474 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2475 synchronized (mGlobalLock) {
2476 final long origId = Binder.clearCallingIdentity();
2477 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2478 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002479 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480 }
2481 Binder.restoreCallingIdentity(origId);
2482 }
2483 }
2484
2485 @Override
2486 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002487 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002488 ActivityStack stack = ActivityRecord.getStackLocked(token);
2489 if (stack != null) {
2490 return stack.willActivityBeVisibleLocked(token);
2491 }
2492 return false;
2493 }
2494 }
2495
2496 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002498 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002499 synchronized (mGlobalLock) {
2500 final long ident = Binder.clearCallingIdentity();
2501 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 if (task == null) {
2504 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2505 return;
2506 }
2507
2508 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2509 + " to stackId=" + stackId + " toTop=" + toTop);
2510
Wale Ogunwaled32da472018-11-16 07:19:28 -08002511 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 if (stack == null) {
2513 throw new IllegalStateException(
2514 "moveTaskToStack: No stack for stackId=" + stackId);
2515 }
2516 if (!stack.isActivityTypeStandardOrUndefined()) {
2517 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2518 + taskId + " to stack " + stackId);
2519 }
2520 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002521 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2523 }
2524 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2525 "moveTaskToStack");
2526 } finally {
2527 Binder.restoreCallingIdentity(ident);
2528 }
2529 }
2530 }
2531
2532 @Override
2533 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2534 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002535 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002536
2537 final long ident = Binder.clearCallingIdentity();
2538 try {
2539 synchronized (mGlobalLock) {
2540 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002541 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 if (stack == null) {
2543 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2544 return;
2545 }
2546 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2547 throw new IllegalArgumentException("Stack: " + stackId
2548 + " doesn't support animated resize.");
2549 }
2550 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2551 animationDuration, false /* fromFullscreen */);
2552 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002553 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002554 if (stack == null) {
2555 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2556 return;
2557 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002558 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2560 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2561 }
2562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567
wilsonshih5c4cf522019-01-25 09:03:47 +08002568 @Override
2569 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2570 int animationDuration) {
2571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2572
2573 final long ident = Binder.clearCallingIdentity();
2574 try {
2575 synchronized (mGlobalLock) {
2576 if (xOffset == 0 && yOffset == 0) {
2577 return;
2578 }
2579 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2580 if (stack == null) {
2581 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2582 return;
2583 }
2584 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2585 throw new IllegalArgumentException("Stack: " + stackId
2586 + " doesn't support animated resize.");
2587 }
2588 final Rect destBounds = new Rect();
2589 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002590 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002591 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2592 return;
2593 }
2594 destBounds.offset(xOffset, yOffset);
2595 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2596 animationDuration, false /* fromFullscreen */);
2597 }
2598 } finally {
2599 Binder.restoreCallingIdentity(ident);
2600 }
2601 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 /**
2603 * Moves the specified task to the primary-split-screen stack.
2604 *
2605 * @param taskId Id of task to move.
2606 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2607 * exist already. See
2608 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2609 * and
2610 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2611 * @param toTop If the task and stack should be moved to the top.
2612 * @param animate Whether we should play an animation for the moving the task.
2613 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2614 * stack. Pass {@code null} to use default bounds.
2615 * @param showRecents If the recents activity should be shown on the other side of the task
2616 * going into split-screen mode.
2617 */
2618 @Override
2619 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2620 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002621 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 "setTaskWindowingModeSplitScreenPrimary()");
2623 synchronized (mGlobalLock) {
2624 final long ident = Binder.clearCallingIdentity();
2625 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002626 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002627 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 if (task == null) {
2629 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2630 return false;
2631 }
2632 if (DEBUG_STACK) Slog.d(TAG_STACK,
2633 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2634 + " to createMode=" + createMode + " toTop=" + toTop);
2635 if (!task.isActivityTypeStandardOrUndefined()) {
2636 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2637 + " non-standard task " + taskId + " to split-screen windowing mode");
2638 }
2639
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002640 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002641 final int windowingMode = task.getWindowingMode();
2642 final ActivityStack stack = task.getStack();
2643 if (toTop) {
2644 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2645 }
2646 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002647 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2648 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002649 return windowingMode != task.getWindowingMode();
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
2654 }
2655
2656 /**
2657 * Removes stacks in the input windowing modes from the system if they are of activity type
2658 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2659 */
2660 @Override
2661 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002662 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002663 "removeStacksInWindowingModes()");
2664
2665 synchronized (mGlobalLock) {
2666 final long ident = Binder.clearCallingIdentity();
2667 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002668 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002669 } finally {
2670 Binder.restoreCallingIdentity(ident);
2671 }
2672 }
2673 }
2674
2675 @Override
2676 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002677 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 "removeStacksWithActivityTypes()");
2679
2680 synchronized (mGlobalLock) {
2681 final long ident = Binder.clearCallingIdentity();
2682 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002683 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 } finally {
2685 Binder.restoreCallingIdentity(ident);
2686 }
2687 }
2688 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002689
2690 @Override
2691 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2692 int userId) {
2693 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002694 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2695 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002696 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002697 final boolean detailed = checkGetTasksPermission(
2698 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2699 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002700 == PackageManager.PERMISSION_GRANTED;
2701
2702 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002703 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002704 callingUid);
2705 }
2706 }
2707
2708 @Override
2709 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002711 long ident = Binder.clearCallingIdentity();
2712 try {
2713 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002714 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002715 }
2716 } finally {
2717 Binder.restoreCallingIdentity(ident);
2718 }
2719 }
2720
2721 @Override
2722 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002723 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002724 long ident = Binder.clearCallingIdentity();
2725 try {
2726 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002727 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728 }
2729 } finally {
2730 Binder.restoreCallingIdentity(ident);
2731 }
2732 }
2733
2734 @Override
2735 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002736 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002737 final long callingUid = Binder.getCallingUid();
2738 final long origId = Binder.clearCallingIdentity();
2739 try {
2740 synchronized (mGlobalLock) {
2741 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002742 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2744 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2745 }
2746 } finally {
2747 Binder.restoreCallingIdentity(origId);
2748 }
2749 }
2750
2751 @Override
2752 public void startLockTaskModeByToken(IBinder token) {
2753 synchronized (mGlobalLock) {
2754 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2755 if (r == null) {
2756 return;
2757 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002758 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002759 }
2760 }
2761
2762 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002763 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 // This makes inner call to look as if it was initiated by system.
2766 long ident = Binder.clearCallingIdentity();
2767 try {
2768 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002769 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002770 MATCH_TASK_IN_STACKS_ONLY);
2771 if (task == null) {
2772 return;
2773 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774
2775 // When starting lock task mode the stack must be in front and focused
2776 task.getStack().moveToFront("startSystemLockTaskMode");
2777 startLockTaskModeLocked(task, true /* isSystemCaller */);
2778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 @Override
2785 public void stopLockTaskModeByToken(IBinder token) {
2786 synchronized (mGlobalLock) {
2787 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2788 if (r == null) {
2789 return;
2790 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002791 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 }
2794
2795 /**
2796 * This API should be called by SystemUI only when user perform certain action to dismiss
2797 * lock task mode. We should only dismiss pinned lock task mode in this case.
2798 */
2799 @Override
2800 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002801 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2803 }
2804
2805 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2806 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2807 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2808 return;
2809 }
2810
Wale Ogunwaled32da472018-11-16 07:19:28 -08002811 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002812 if (stack == null || task != stack.topTask()) {
2813 throw new IllegalArgumentException("Invalid task, not in foreground");
2814 }
2815
2816 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2817 // system or a specific app.
2818 // * System-initiated requests will only start the pinned mode (screen pinning)
2819 // * App-initiated requests
2820 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2821 // - will start the pinned mode, otherwise
2822 final int callingUid = Binder.getCallingUid();
2823 long ident = Binder.clearCallingIdentity();
2824 try {
2825 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002826 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002828 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2835 final int callingUid = Binder.getCallingUid();
2836 long ident = Binder.clearCallingIdentity();
2837 try {
2838 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002839 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840 }
2841 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2842 // task and jumping straight into a call in the case of emergency call back.
2843 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2844 if (tm != null) {
2845 tm.showInCallScreen(false);
2846 }
2847 } finally {
2848 Binder.restoreCallingIdentity(ident);
2849 }
2850 }
2851
2852 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002853 public void updateLockTaskPackages(int userId, String[] packages) {
2854 final int callingUid = Binder.getCallingUid();
2855 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2856 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2857 "updateLockTaskPackages()");
2858 }
2859 synchronized (this) {
2860 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2861 + Arrays.toString(packages));
2862 getLockTaskController().updateLockTaskPackages(userId, packages);
2863 }
2864 }
2865
2866 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002867 public boolean isInLockTaskMode() {
2868 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2869 }
2870
2871 @Override
2872 public int getLockTaskModeState() {
2873 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002874 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 }
2876 }
2877
2878 @Override
2879 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2880 synchronized (mGlobalLock) {
2881 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2882 if (r != null) {
2883 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002884 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002886 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 }
2888 }
2889 }
2890
2891 @Override
2892 public Bundle getActivityOptions(IBinder token) {
2893 final long origId = Binder.clearCallingIdentity();
2894 try {
2895 synchronized (mGlobalLock) {
2896 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2897 if (r != null) {
2898 final ActivityOptions activityOptions = r.takeOptionsLocked();
2899 return activityOptions == null ? null : activityOptions.toBundle();
2900 }
2901 return null;
2902 }
2903 } finally {
2904 Binder.restoreCallingIdentity(origId);
2905 }
2906 }
2907
2908 @Override
2909 public List<IBinder> getAppTasks(String callingPackage) {
2910 int callingUid = Binder.getCallingUid();
2911 long ident = Binder.clearCallingIdentity();
2912 try {
2913 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002914 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 }
2916 } finally {
2917 Binder.restoreCallingIdentity(ident);
2918 }
2919 }
2920
2921 @Override
2922 public void finishVoiceTask(IVoiceInteractionSession session) {
2923 synchronized (mGlobalLock) {
2924 final long origId = Binder.clearCallingIdentity();
2925 try {
2926 // TODO: VI Consider treating local voice interactions and voice tasks
2927 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002928 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 } finally {
2930 Binder.restoreCallingIdentity(origId);
2931 }
2932 }
2933
2934 }
2935
2936 @Override
2937 public boolean isTopOfTask(IBinder token) {
2938 synchronized (mGlobalLock) {
2939 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002940 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 }
2942 }
2943
2944 @Override
2945 public void notifyLaunchTaskBehindComplete(IBinder token) {
2946 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2947 }
2948
2949 @Override
2950 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002951 mH.post(() -> {
2952 synchronized (mGlobalLock) {
2953 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002954 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002955 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002956 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002957 } catch (RemoteException e) {
2958 }
2959 }
2960 }
2961
2962 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 }
2964
2965 /** Called from an app when assist data is ready. */
2966 @Override
2967 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2968 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002969 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 synchronized (pae) {
2971 pae.result = extras;
2972 pae.structure = structure;
2973 pae.content = content;
2974 if (referrer != null) {
2975 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2976 }
2977 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002978 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002979 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2980 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002981 structure.setHomeActivity(pae.isHome);
2982 }
2983 pae.haveResult = true;
2984 pae.notifyAll();
2985 if (pae.intent == null && pae.receiver == null) {
2986 // Caller is just waiting for the result.
2987 return;
2988 }
2989 }
2990 // We are now ready to launch the assist activity.
2991 IAssistDataReceiver sendReceiver = null;
2992 Bundle sendBundle = null;
2993 synchronized (mGlobalLock) {
2994 buildAssistBundleLocked(pae, extras);
2995 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002996 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 if (!exists) {
2998 // Timed out.
2999 return;
3000 }
3001
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003002 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 // Caller wants result sent back to them.
3004 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003005 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3006 pae.activity.getTaskRecord().taskId);
3007 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3008 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3010 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3011 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3012 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3013 }
3014 }
3015 if (sendReceiver != null) {
3016 try {
3017 sendReceiver.onHandleAssistData(sendBundle);
3018 } catch (RemoteException e) {
3019 }
3020 return;
3021 }
3022
3023 final long ident = Binder.clearCallingIdentity();
3024 try {
3025 if (TextUtils.equals(pae.intent.getAction(),
3026 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3027 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003028
3029 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 } else {
3031 pae.intent.replaceExtras(pae.extras);
3032 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3033 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3034 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003035 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036
3037 try {
3038 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3039 } catch (ActivityNotFoundException e) {
3040 Slog.w(TAG, "No activity to handle assist action.", e);
3041 }
3042 }
3043 } finally {
3044 Binder.restoreCallingIdentity(ident);
3045 }
3046 }
3047
Marvin Ramin830d4e32019-03-12 13:16:58 +01003048 /**
3049 * Workaround for historical API which starts the Assist service with a non-foreground
3050 * {@code startService()} call.
3051 */
3052 private void startVoiceInteractionServiceAsUser(
3053 Intent intent, int userHandle, String reason) {
3054 // Resolve the intent to find out which package we need to whitelist.
3055 ResolveInfo resolveInfo =
3056 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3057 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3058 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3059 return;
3060 }
3061 intent.setPackage(resolveInfo.serviceInfo.packageName);
3062
3063 // Whitelist background services temporarily.
3064 LocalServices.getService(DeviceIdleController.LocalService.class)
3065 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3066 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3067
3068 // Finally, try to start the service.
3069 try {
3070 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3071 } catch (RuntimeException e) {
3072 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3073 }
3074 }
3075
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 @Override
3077 public int addAppTask(IBinder activityToken, Intent intent,
3078 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3079 final int callingUid = Binder.getCallingUid();
3080 final long callingIdent = Binder.clearCallingIdentity();
3081
3082 try {
3083 synchronized (mGlobalLock) {
3084 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3085 if (r == null) {
3086 throw new IllegalArgumentException("Activity does not exist; token="
3087 + activityToken);
3088 }
3089 ComponentName comp = intent.getComponent();
3090 if (comp == null) {
3091 throw new IllegalArgumentException("Intent " + intent
3092 + " must specify explicit component");
3093 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003094 if (thumbnail.getWidth() != mThumbnailWidth
3095 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 throw new IllegalArgumentException("Bad thumbnail size: got "
3097 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 }
3100 if (intent.getSelector() != null) {
3101 intent.setSelector(null);
3102 }
3103 if (intent.getSourceBounds() != null) {
3104 intent.setSourceBounds(null);
3105 }
3106 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3107 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3108 // The caller has added this as an auto-remove task... that makes no
3109 // sense, so turn off auto-remove.
3110 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3111 }
3112 }
3113 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3114 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3115 if (ainfo.applicationInfo.uid != callingUid) {
3116 throw new SecurityException(
3117 "Can't add task for another application: target uid="
3118 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3119 }
3120
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003121 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003123 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003125 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 // The app has too many tasks already and we can't add any more
3127 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3128 return INVALID_TASK_ID;
3129 }
3130 task.lastTaskDescription.copyFrom(description);
3131
3132 // TODO: Send the thumbnail to WM to store it.
3133
3134 return task.taskId;
3135 }
3136 } finally {
3137 Binder.restoreCallingIdentity(callingIdent);
3138 }
3139 }
3140
3141 @Override
3142 public Point getAppTaskThumbnailSize() {
3143 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 }
3146 }
3147
3148 @Override
3149 public void setTaskResizeable(int taskId, int resizeableMode) {
3150 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003151 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3153 if (task == null) {
3154 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3155 return;
3156 }
3157 task.setResizeMode(resizeableMode);
3158 }
3159 }
3160
3161 @Override
3162 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003163 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 long ident = Binder.clearCallingIdentity();
3165 try {
3166 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003167 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003168 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 if (task == null) {
3170 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3171 return;
3172 }
3173 // Place the task in the right stack if it isn't there already based on
3174 // the requested bounds.
3175 // The stack transition logic is:
3176 // - a null bounds on a freeform task moves that task to fullscreen
3177 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3178 // that task to freeform
3179 // - otherwise the task is not moved
3180 ActivityStack stack = task.getStack();
3181 if (!task.getWindowConfiguration().canResizeTask()) {
3182 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3183 }
3184 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3185 stack = stack.getDisplay().getOrCreateStack(
3186 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3187 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3188 stack = stack.getDisplay().getOrCreateStack(
3189 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3190 }
3191
3192 // Reparent the task to the right stack if necessary
3193 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3194 if (stack != task.getStack()) {
3195 // Defer resume until the task is resized below
3196 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3197 DEFER_RESUME, "resizeTask");
3198 preserveWindow = false;
3199 }
3200
3201 // After reparenting (which only resizes the task to the stack bounds), resize the
3202 // task to the actual bounds provided
3203 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3204 }
3205 } finally {
3206 Binder.restoreCallingIdentity(ident);
3207 }
3208 }
3209
3210 @Override
3211 public boolean releaseActivityInstance(IBinder token) {
3212 synchronized (mGlobalLock) {
3213 final long origId = Binder.clearCallingIdentity();
3214 try {
3215 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3216 if (r == null) {
3217 return false;
3218 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003219 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 } finally {
3221 Binder.restoreCallingIdentity(origId);
3222 }
3223 }
3224 }
3225
3226 @Override
3227 public void releaseSomeActivities(IApplicationThread appInt) {
3228 synchronized (mGlobalLock) {
3229 final long origId = Binder.clearCallingIdentity();
3230 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003231 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003232 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 } finally {
3234 Binder.restoreCallingIdentity(origId);
3235 }
3236 }
3237 }
3238
3239 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003240 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 != PackageManager.PERMISSION_GRANTED) {
3243 throw new SecurityException("Requires permission "
3244 + android.Manifest.permission.DEVICE_POWER);
3245 }
3246
3247 synchronized (mGlobalLock) {
3248 long ident = Binder.clearCallingIdentity();
3249 if (mKeyguardShown != keyguardShowing) {
3250 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003251 final Message msg = PooledLambda.obtainMessage(
3252 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3253 keyguardShowing);
3254 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 }
3256 try {
wilsonshih177261f2019-02-22 12:02:18 +08003257 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 } finally {
3259 Binder.restoreCallingIdentity(ident);
3260 }
3261 }
3262
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003263 mH.post(() -> {
3264 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3265 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3266 }
3267 });
3268 }
3269
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003270 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003271 mH.post(() -> {
3272 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3273 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3274 }
3275 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276 }
3277
3278 @Override
3279 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3281 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003282
3283 final File passedIconFile = new File(filePath);
3284 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3285 passedIconFile.getName());
3286 if (!legitIconFile.getPath().equals(filePath)
3287 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3288 throw new IllegalArgumentException("Bad file path: " + filePath
3289 + " passed for userId " + userId);
3290 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003291 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292 }
3293
3294 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003295 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3297 final ActivityOptions activityOptions = safeOptions != null
3298 ? safeOptions.getOptions(mStackSupervisor)
3299 : null;
3300 if (activityOptions == null
3301 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3302 || activityOptions.getCustomInPlaceResId() == 0) {
3303 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3304 "with valid animation");
3305 }
lumark588a3e82018-07-20 18:53:54 +08003306 // Get top display of front most application.
3307 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3308 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003309 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3310 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3311 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003312 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003313 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003314 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 }
3316
3317 @Override
3318 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003319 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 synchronized (mGlobalLock) {
3321 final long ident = Binder.clearCallingIdentity();
3322 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003323 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 if (stack == null) {
3325 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3326 return;
3327 }
3328 if (!stack.isActivityTypeStandardOrUndefined()) {
3329 throw new IllegalArgumentException(
3330 "Removing non-standard stack is not allowed.");
3331 }
3332 mStackSupervisor.removeStack(stack);
3333 } finally {
3334 Binder.restoreCallingIdentity(ident);
3335 }
3336 }
3337 }
3338
3339 @Override
3340 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003341 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003342
3343 synchronized (mGlobalLock) {
3344 final long ident = Binder.clearCallingIdentity();
3345 try {
3346 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3347 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003348 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 } finally {
3350 Binder.restoreCallingIdentity(ident);
3351 }
3352 }
3353 }
3354
3355 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003356 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 synchronized (mGlobalLock) {
3358 long ident = Binder.clearCallingIdentity();
3359 try {
3360 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3361 if (r == null) {
3362 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003363 "toggleFreeformWindowingMode: No activity record matching token="
3364 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 }
3366
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003367 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003368 if (stack == null) {
3369 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3370 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 }
3372
Yunfan Chend967af82019-01-17 18:30:18 +09003373 if (!stack.inFreeformWindowingMode()
3374 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3375 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3376 + "toggle between fullscreen and freeform.");
3377 }
3378
3379 if (stack.inFreeformWindowingMode()) {
3380 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003381 } else if (stack.getParent().inFreeformWindowingMode()) {
3382 // If the window is on a freeform display, set it to undefined. It will be
3383 // resolved to freeform and it can adjust windowing mode when the display mode
3384 // changes in runtime.
3385 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003386 } else {
3387 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3388 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003389 } finally {
3390 Binder.restoreCallingIdentity(ident);
3391 }
3392 }
3393 }
3394
3395 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3396 @Override
3397 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003398 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003400 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 }
3402
3403 /** Unregister a task stack listener so that it stops receiving callbacks. */
3404 @Override
3405 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003406 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003407 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003408 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409 }
3410
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411 @Override
3412 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3413 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3414 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3415 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3416 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3417 }
3418
3419 @Override
3420 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3421 IBinder activityToken, int flags) {
3422 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3423 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3424 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3425 }
3426
3427 @Override
3428 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3429 Bundle args) {
3430 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3431 true /* focused */, true /* newSessionId */, userHandle, args,
3432 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3433 }
3434
3435 @Override
3436 public Bundle getAssistContextExtras(int requestType) {
3437 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3438 null, null, true /* focused */, true /* newSessionId */,
3439 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3440 if (pae == null) {
3441 return null;
3442 }
3443 synchronized (pae) {
3444 while (!pae.haveResult) {
3445 try {
3446 pae.wait();
3447 } catch (InterruptedException e) {
3448 }
3449 }
3450 }
3451 synchronized (mGlobalLock) {
3452 buildAssistBundleLocked(pae, pae.result);
3453 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003454 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 }
3456 return pae.extras;
3457 }
3458
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 /**
3460 * Binder IPC calls go through the public entry point.
3461 * This can be called with or without the global lock held.
3462 */
3463 private static int checkCallingPermission(String permission) {
3464 return checkPermission(
3465 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3466 }
3467
3468 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003469 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003470 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3471 mAmInternal.enforceCallingPermission(permission, func);
3472 }
3473 }
3474
3475 @VisibleForTesting
3476 int checkGetTasksPermission(String permission, int pid, int uid) {
3477 return checkPermission(permission, pid, uid);
3478 }
3479
3480 static int checkPermission(String permission, int pid, int uid) {
3481 if (permission == null) {
3482 return PackageManager.PERMISSION_DENIED;
3483 }
3484 return checkComponentPermission(permission, pid, uid, -1, true);
3485 }
3486
Wale Ogunwale214f3482018-10-04 11:00:47 -07003487 public static int checkComponentPermission(String permission, int pid, int uid,
3488 int owningUid, boolean exported) {
3489 return ActivityManagerService.checkComponentPermission(
3490 permission, pid, uid, owningUid, exported);
3491 }
3492
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003493 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3494 if (getRecentTasks().isCallerRecents(callingUid)) {
3495 // Always allow the recents component to get tasks
3496 return true;
3497 }
3498
3499 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3500 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3501 if (!allowed) {
3502 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3503 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3504 // Temporary compatibility: some existing apps on the system image may
3505 // still be requesting the old permission and not switched to the new
3506 // one; if so, we'll still allow them full access. This means we need
3507 // to see if they are holding the old permission and are a system app.
3508 try {
3509 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3510 allowed = true;
3511 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3512 + " is using old GET_TASKS but privileged; allowing");
3513 }
3514 } catch (RemoteException e) {
3515 }
3516 }
3517 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3518 + " does not hold REAL_GET_TASKS; limiting output");
3519 }
3520 return allowed;
3521 }
3522
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3524 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3525 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3526 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 "enqueueAssistContext()");
3529
3530 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003531 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 if (activity == null) {
3533 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3534 return null;
3535 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003536 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003537 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3538 return null;
3539 }
3540 if (focused) {
3541 if (activityToken != null) {
3542 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3543 if (activity != caller) {
3544 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3545 + " is not current top " + activity);
3546 return null;
3547 }
3548 }
3549 } else {
3550 activity = ActivityRecord.forTokenLocked(activityToken);
3551 if (activity == null) {
3552 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3553 + " couldn't be found");
3554 return null;
3555 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003556 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3558 return null;
3559 }
3560 }
3561
3562 PendingAssistExtras pae;
3563 Bundle extras = new Bundle();
3564 if (args != null) {
3565 extras.putAll(args);
3566 }
3567 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003568 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003569
3570 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3571 userHandle);
3572 pae.isHome = activity.isActivityTypeHome();
3573
3574 // Increment the sessionId if necessary
3575 if (newSessionId) {
3576 mViSessionId++;
3577 }
3578 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003579 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3580 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003581 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003582 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 } catch (RemoteException e) {
3584 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3585 return null;
3586 }
3587 return pae;
3588 }
3589 }
3590
3591 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3592 if (result != null) {
3593 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3594 }
3595 if (pae.hint != null) {
3596 pae.extras.putBoolean(pae.hint, true);
3597 }
3598 }
3599
3600 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3601 IAssistDataReceiver receiver;
3602 synchronized (mGlobalLock) {
3603 mPendingAssistExtras.remove(pae);
3604 receiver = pae.receiver;
3605 }
3606 if (receiver != null) {
3607 // Caller wants result sent back to them.
3608 Bundle sendBundle = new Bundle();
3609 // At least return the receiver extras
3610 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3611 try {
3612 pae.receiver.onHandleAssistData(sendBundle);
3613 } catch (RemoteException e) {
3614 }
3615 }
3616 }
3617
3618 public class PendingAssistExtras extends Binder implements Runnable {
3619 public final ActivityRecord activity;
3620 public boolean isHome;
3621 public final Bundle extras;
3622 public final Intent intent;
3623 public final String hint;
3624 public final IAssistDataReceiver receiver;
3625 public final int userHandle;
3626 public boolean haveResult = false;
3627 public Bundle result = null;
3628 public AssistStructure structure = null;
3629 public AssistContent content = null;
3630 public Bundle receiverExtras;
3631
3632 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3633 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3634 int _userHandle) {
3635 activity = _activity;
3636 extras = _extras;
3637 intent = _intent;
3638 hint = _hint;
3639 receiver = _receiver;
3640 receiverExtras = _receiverExtras;
3641 userHandle = _userHandle;
3642 }
3643
3644 @Override
3645 public void run() {
3646 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3647 synchronized (this) {
3648 haveResult = true;
3649 notifyAll();
3650 }
3651 pendingAssistExtrasTimedOut(this);
3652 }
3653 }
3654
3655 @Override
3656 public boolean isAssistDataAllowedOnCurrentActivity() {
3657 int userId;
3658 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003659 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003660 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3661 return false;
3662 }
3663
3664 final ActivityRecord activity = focusedStack.getTopActivity();
3665 if (activity == null) {
3666 return false;
3667 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003668 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 }
3670 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3671 }
3672
3673 @Override
3674 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3675 long ident = Binder.clearCallingIdentity();
3676 try {
3677 synchronized (mGlobalLock) {
3678 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003679 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 if (top != caller) {
3681 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3682 + " is not current top " + top);
3683 return false;
3684 }
3685 if (!top.nowVisible) {
3686 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3687 + " is not visible");
3688 return false;
3689 }
3690 }
3691 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3692 token);
3693 } finally {
3694 Binder.restoreCallingIdentity(ident);
3695 }
3696 }
3697
3698 @Override
3699 public boolean isRootVoiceInteraction(IBinder token) {
3700 synchronized (mGlobalLock) {
3701 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3702 if (r == null) {
3703 return false;
3704 }
3705 return r.rootVoiceInteraction;
3706 }
3707 }
3708
Wale Ogunwalef6733932018-06-27 05:14:34 -07003709 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3710 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3711 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3712 if (activityToCallback == null) return;
3713 activityToCallback.setVoiceSessionLocked(voiceSession);
3714
3715 // Inform the activity
3716 try {
3717 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3718 voiceInteractor);
3719 long token = Binder.clearCallingIdentity();
3720 try {
3721 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3722 } finally {
3723 Binder.restoreCallingIdentity(token);
3724 }
3725 // TODO: VI Should we cache the activity so that it's easier to find later
3726 // rather than scan through all the stacks and activities?
3727 } catch (RemoteException re) {
3728 activityToCallback.clearVoiceSessionLocked();
3729 // TODO: VI Should this terminate the voice session?
3730 }
3731 }
3732
3733 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3734 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3735 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3736 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3737 boolean wasRunningVoice = mRunningVoice != null;
3738 mRunningVoice = session;
3739 if (!wasRunningVoice) {
3740 mVoiceWakeLock.acquire();
3741 updateSleepIfNeededLocked();
3742 }
3743 }
3744 }
3745
3746 void finishRunningVoiceLocked() {
3747 if (mRunningVoice != null) {
3748 mRunningVoice = null;
3749 mVoiceWakeLock.release();
3750 updateSleepIfNeededLocked();
3751 }
3752 }
3753
3754 @Override
3755 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3756 synchronized (mGlobalLock) {
3757 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3758 if (keepAwake) {
3759 mVoiceWakeLock.acquire();
3760 } else {
3761 mVoiceWakeLock.release();
3762 }
3763 }
3764 }
3765 }
3766
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003767 @Override
3768 public ComponentName getActivityClassForToken(IBinder token) {
3769 synchronized (mGlobalLock) {
3770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3771 if (r == null) {
3772 return null;
3773 }
3774 return r.intent.getComponent();
3775 }
3776 }
3777
3778 @Override
3779 public String getPackageForToken(IBinder token) {
3780 synchronized (mGlobalLock) {
3781 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3782 if (r == null) {
3783 return null;
3784 }
3785 return r.packageName;
3786 }
3787 }
3788
3789 @Override
3790 public void showLockTaskEscapeMessage(IBinder token) {
3791 synchronized (mGlobalLock) {
3792 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3793 if (r == null) {
3794 return;
3795 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003796 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003797 }
3798 }
3799
3800 @Override
3801 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003802 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003803 final long token = Binder.clearCallingIdentity();
3804 try {
3805 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003806 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003807 }
3808 } finally {
3809 Binder.restoreCallingIdentity(token);
3810 }
3811 }
3812
3813 /**
3814 * Try to place task to provided position. The final position might be different depending on
3815 * current user and stacks state. The task will be moved to target stack if it's currently in
3816 * different stack.
3817 */
3818 @Override
3819 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003820 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 synchronized (mGlobalLock) {
3822 long ident = Binder.clearCallingIdentity();
3823 try {
3824 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3825 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003826 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 if (task == null) {
3828 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3829 + taskId);
3830 }
3831
Wale Ogunwaled32da472018-11-16 07:19:28 -08003832 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833
3834 if (stack == null) {
3835 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3836 + stackId);
3837 }
3838 if (!stack.isActivityTypeStandardOrUndefined()) {
3839 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3840 + " the position of task " + taskId + " in/to non-standard stack");
3841 }
3842
3843 // TODO: Have the callers of this API call a separate reparent method if that is
3844 // what they intended to do vs. having this method also do reparenting.
3845 if (task.getStack() == stack) {
3846 // Change position in current stack.
3847 stack.positionChildAt(task, position);
3848 } else {
3849 // Reparent to new stack.
3850 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3851 !DEFER_RESUME, "positionTaskInStack");
3852 }
3853 } finally {
3854 Binder.restoreCallingIdentity(ident);
3855 }
3856 }
3857 }
3858
3859 @Override
3860 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3861 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3862 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3863 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3864 synchronized (mGlobalLock) {
3865 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3866 if (record == null) {
3867 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3868 + "found for: " + token);
3869 }
3870 record.setSizeConfigurations(horizontalSizeConfiguration,
3871 verticalSizeConfigurations, smallestSizeConfigurations);
3872 }
3873 }
3874
3875 /**
3876 * Dismisses split-screen multi-window mode.
3877 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3878 */
3879 @Override
3880 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003881 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3883 final long ident = Binder.clearCallingIdentity();
3884 try {
3885 synchronized (mGlobalLock) {
3886 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003887 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 if (stack == null) {
3889 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3890 return;
3891 }
3892
3893 if (toTop) {
3894 // Caller wants the current split-screen primary stack to be the top stack after
3895 // it goes fullscreen, so move it to the front.
3896 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003897 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 // In this case the current split-screen primary stack shouldn't be the top
3899 // stack after it goes fullscreen, but it current has focus, so we move the
3900 // focus to the top-most split-screen secondary stack next to it.
3901 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3902 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3903 if (otherStack != null) {
3904 otherStack.moveToFront("dismissSplitScreenMode_other");
3905 }
3906 }
3907
Evan Rosky10475742018-09-05 19:02:48 -07003908 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 }
3910 } finally {
3911 Binder.restoreCallingIdentity(ident);
3912 }
3913 }
3914
3915 /**
3916 * Dismisses Pip
3917 * @param animate True if the dismissal should be animated.
3918 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3919 * default animation duration should be used.
3920 */
3921 @Override
3922 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003923 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 final long ident = Binder.clearCallingIdentity();
3925 try {
3926 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003927 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003928 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 if (stack == null) {
3930 Slog.w(TAG, "dismissPip: pinned stack not found.");
3931 return;
3932 }
3933 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3934 throw new IllegalArgumentException("Stack: " + stack
3935 + " doesn't support animated resize.");
3936 }
3937 if (animate) {
3938 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3939 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3940 } else {
3941 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3942 }
3943 }
3944 } finally {
3945 Binder.restoreCallingIdentity(ident);
3946 }
3947 }
3948
3949 @Override
3950 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 synchronized (mGlobalLock) {
3953 mSuppressResizeConfigChanges = suppress;
3954 }
3955 }
3956
3957 /**
3958 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3959 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3960 * activity and clearing the task at the same time.
3961 */
3962 @Override
3963 // TODO: API should just be about changing windowing modes...
3964 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003965 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 "moveTasksToFullscreenStack()");
3967 synchronized (mGlobalLock) {
3968 final long origId = Binder.clearCallingIdentity();
3969 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003970 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 if (stack != null){
3972 if (!stack.isActivityTypeStandardOrUndefined()) {
3973 throw new IllegalArgumentException(
3974 "You can't move tasks from non-standard stacks.");
3975 }
3976 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3977 }
3978 } finally {
3979 Binder.restoreCallingIdentity(origId);
3980 }
3981 }
3982 }
3983
3984 /**
3985 * Moves the top activity in the input stackId to the pinned stack.
3986 *
3987 * @param stackId Id of stack to move the top activity to pinned stack.
3988 * @param bounds Bounds to use for pinned stack.
3989 *
3990 * @return True if the top activity of the input stack was successfully moved to the pinned
3991 * stack.
3992 */
3993 @Override
3994 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003995 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003996 "moveTopActivityToPinnedStack()");
3997 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003998 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4000 + "Device doesn't support picture-in-picture mode");
4001 }
4002
4003 long ident = Binder.clearCallingIdentity();
4004 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004005 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
4009 }
4010 }
4011
4012 @Override
4013 public boolean isInMultiWindowMode(IBinder token) {
4014 final long origId = Binder.clearCallingIdentity();
4015 try {
4016 synchronized (mGlobalLock) {
4017 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4018 if (r == null) {
4019 return false;
4020 }
4021 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4022 return r.inMultiWindowMode();
4023 }
4024 } finally {
4025 Binder.restoreCallingIdentity(origId);
4026 }
4027 }
4028
4029 @Override
4030 public boolean isInPictureInPictureMode(IBinder token) {
4031 final long origId = Binder.clearCallingIdentity();
4032 try {
4033 synchronized (mGlobalLock) {
4034 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4035 }
4036 } finally {
4037 Binder.restoreCallingIdentity(origId);
4038 }
4039 }
4040
4041 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004042 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4043 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 return false;
4045 }
4046
4047 // If we are animating to fullscreen then we have already dispatched the PIP mode
4048 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004049 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4050 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 }
4052
4053 @Override
4054 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4055 final long origId = Binder.clearCallingIdentity();
4056 try {
4057 synchronized (mGlobalLock) {
4058 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4059 "enterPictureInPictureMode", token, params);
4060
4061 // If the activity is already in picture in picture mode, then just return early
4062 if (isInPictureInPictureMode(r)) {
4063 return true;
4064 }
4065
4066 // Activity supports picture-in-picture, now check that we can enter PiP at this
4067 // point, if it is
4068 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4069 false /* beforeStopping */)) {
4070 return false;
4071 }
4072
4073 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004074 synchronized (mGlobalLock) {
4075 // Only update the saved args from the args that are set
4076 r.pictureInPictureArgs.copyOnlySet(params);
4077 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4078 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4079 // Adjust the source bounds by the insets for the transition down
4080 final Rect sourceBounds = new Rect(
4081 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004082 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004083 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004084 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004085 stack.setPictureInPictureAspectRatio(aspectRatio);
4086 stack.setPictureInPictureActions(actions);
4087 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4088 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4089 logPictureInPictureArgs(params);
4090 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 };
4092
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004093 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 // If the keyguard is showing or occluded, then try and dismiss it before
4095 // entering picture-in-picture (this will prompt the user to authenticate if the
4096 // device is currently locked).
4097 dismissKeyguard(token, new KeyguardDismissCallback() {
4098 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004099 public void onDismissSucceeded() {
4100 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004101 }
4102 }, null /* message */);
4103 } else {
4104 // Enter picture in picture immediately otherwise
4105 enterPipRunnable.run();
4106 }
4107 return true;
4108 }
4109 } finally {
4110 Binder.restoreCallingIdentity(origId);
4111 }
4112 }
4113
4114 @Override
4115 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4116 final long origId = Binder.clearCallingIdentity();
4117 try {
4118 synchronized (mGlobalLock) {
4119 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4120 "setPictureInPictureParams", token, params);
4121
4122 // Only update the saved args from the args that are set
4123 r.pictureInPictureArgs.copyOnlySet(params);
4124 if (r.inPinnedWindowingMode()) {
4125 // If the activity is already in picture-in-picture, update the pinned stack now
4126 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4127 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004128 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 if (!stack.isAnimatingBoundsToFullscreen()) {
4130 stack.setPictureInPictureAspectRatio(
4131 r.pictureInPictureArgs.getAspectRatio());
4132 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4133 }
4134 }
4135 logPictureInPictureArgs(params);
4136 }
4137 } finally {
4138 Binder.restoreCallingIdentity(origId);
4139 }
4140 }
4141
4142 @Override
4143 public int getMaxNumPictureInPictureActions(IBinder token) {
4144 // Currently, this is a static constant, but later, we may change this to be dependent on
4145 // the context of the activity
4146 return 3;
4147 }
4148
4149 private void logPictureInPictureArgs(PictureInPictureParams params) {
4150 if (params.hasSetActions()) {
4151 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4152 params.getActions().size());
4153 }
4154 if (params.hasSetAspectRatio()) {
4155 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4156 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4157 MetricsLogger.action(lm);
4158 }
4159 }
4160
4161 /**
4162 * Checks the state of the system and the activity associated with the given {@param token} to
4163 * verify that picture-in-picture is supported for that activity.
4164 *
4165 * @return the activity record for the given {@param token} if all the checks pass.
4166 */
4167 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4168 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004169 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 throw new IllegalStateException(caller
4171 + ": Device doesn't support picture-in-picture mode.");
4172 }
4173
4174 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4175 if (r == null) {
4176 throw new IllegalStateException(caller
4177 + ": Can't find activity for token=" + token);
4178 }
4179
4180 if (!r.supportsPictureInPicture()) {
4181 throw new IllegalStateException(caller
4182 + ": Current activity does not support picture-in-picture.");
4183 }
4184
4185 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004186 && !mWindowManager.isValidPictureInPictureAspectRatio(
4187 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 final float minAspectRatio = mContext.getResources().getFloat(
4189 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4190 final float maxAspectRatio = mContext.getResources().getFloat(
4191 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4192 throw new IllegalArgumentException(String.format(caller
4193 + ": Aspect ratio is too extreme (must be between %f and %f).",
4194 minAspectRatio, maxAspectRatio));
4195 }
4196
4197 // Truncate the number of actions if necessary
4198 params.truncateActions(getMaxNumPictureInPictureActions(token));
4199
4200 return r;
4201 }
4202
4203 @Override
4204 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004205 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 synchronized (mGlobalLock) {
4207 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4208 if (r == null) {
4209 throw new IllegalArgumentException("Activity does not exist; token="
4210 + activityToken);
4211 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004212 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 }
4214 }
4215
4216 @Override
4217 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4218 Rect tempDockedTaskInsetBounds,
4219 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004220 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 long ident = Binder.clearCallingIdentity();
4222 try {
4223 synchronized (mGlobalLock) {
4224 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4225 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4226 PRESERVE_WINDOWS);
4227 }
4228 } finally {
4229 Binder.restoreCallingIdentity(ident);
4230 }
4231 }
4232
4233 @Override
4234 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 final long ident = Binder.clearCallingIdentity();
4237 try {
4238 synchronized (mGlobalLock) {
4239 mStackSupervisor.setSplitScreenResizing(resizing);
4240 }
4241 } finally {
4242 Binder.restoreCallingIdentity(ident);
4243 }
4244 }
4245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004246 /**
4247 * Check that we have the features required for VR-related API calls, and throw an exception if
4248 * not.
4249 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004250 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004251 if (!mContext.getPackageManager().hasSystemFeature(
4252 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4253 throw new UnsupportedOperationException("VR mode not supported on this device!");
4254 }
4255 }
4256
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 @Override
4258 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260
4261 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4262
4263 ActivityRecord r;
4264 synchronized (mGlobalLock) {
4265 r = ActivityRecord.isInStackLocked(token);
4266 }
4267
4268 if (r == null) {
4269 throw new IllegalArgumentException();
4270 }
4271
4272 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004273 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 VrManagerInternal.NO_ERROR) {
4275 return err;
4276 }
4277
4278 // Clear the binder calling uid since this path may call moveToTask().
4279 final long callingId = Binder.clearCallingIdentity();
4280 try {
4281 synchronized (mGlobalLock) {
4282 r.requestedVrComponent = (enabled) ? packageName : null;
4283
4284 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004285 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004286 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 }
4288 return 0;
4289 }
4290 } finally {
4291 Binder.restoreCallingIdentity(callingId);
4292 }
4293 }
4294
4295 @Override
4296 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4297 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4298 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004299 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4301 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4302 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004303 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 || activity.voiceSession != null) {
4305 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4306 return;
4307 }
4308 if (activity.pendingVoiceInteractionStart) {
4309 Slog.w(TAG, "Pending start of voice interaction already.");
4310 return;
4311 }
4312 activity.pendingVoiceInteractionStart = true;
4313 }
4314 LocalServices.getService(VoiceInteractionManagerInternal.class)
4315 .startLocalVoiceInteraction(callingActivity, options);
4316 }
4317
4318 @Override
4319 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4320 LocalServices.getService(VoiceInteractionManagerInternal.class)
4321 .stopLocalVoiceInteraction(callingActivity);
4322 }
4323
4324 @Override
4325 public boolean supportsLocalVoiceInteraction() {
4326 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4327 .supportsLocalVoiceInteraction();
4328 }
4329
4330 /** Notifies all listeners when the pinned stack animation starts. */
4331 @Override
4332 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004333 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 }
4335
4336 /** Notifies all listeners when the pinned stack animation ends. */
4337 @Override
4338 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004339 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 }
4341
4342 @Override
4343 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004344 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 final long ident = Binder.clearCallingIdentity();
4346 try {
4347 synchronized (mGlobalLock) {
4348 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4349 }
4350 } finally {
4351 Binder.restoreCallingIdentity(ident);
4352 }
4353 }
4354
4355 @Override
4356 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004357 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004358
4359 synchronized (mGlobalLock) {
4360 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004361 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 // Call might come when display is not yet added or has already been removed.
4363 if (DEBUG_CONFIGURATION) {
4364 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4365 + displayId);
4366 }
4367 return false;
4368 }
4369
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004370 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004376 final Message msg = PooledLambda.obtainMessage(
4377 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4378 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380
4381 final long origId = Binder.clearCallingIdentity();
4382 try {
4383 if (values != null) {
4384 Settings.System.clearConfiguration(values);
4385 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4388 return mTmpUpdateConfigurationResult.changes != 0;
4389 } finally {
4390 Binder.restoreCallingIdentity(origId);
4391 }
4392 }
4393 }
4394
4395 @Override
4396 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398
4399 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004402 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 }
4404
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004406 final Message msg = PooledLambda.obtainMessage(
4407 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4408 DEFAULT_DISPLAY);
4409 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 }
4411
4412 final long origId = Binder.clearCallingIdentity();
4413 try {
4414 if (values != null) {
4415 Settings.System.clearConfiguration(values);
4416 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004417 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004418 UserHandle.USER_NULL, false /* deferResume */,
4419 mTmpUpdateConfigurationResult);
4420 return mTmpUpdateConfigurationResult.changes != 0;
4421 } finally {
4422 Binder.restoreCallingIdentity(origId);
4423 }
4424 }
4425 }
4426
4427 @Override
4428 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4429 CharSequence message) {
4430 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004431 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4433 }
4434 final long callingId = Binder.clearCallingIdentity();
4435 try {
4436 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004437 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004438 }
4439 } finally {
4440 Binder.restoreCallingIdentity(callingId);
4441 }
4442 }
4443
4444 @Override
4445 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004446 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 "cancelTaskWindowTransition()");
4448 final long ident = Binder.clearCallingIdentity();
4449 try {
4450 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004451 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 MATCH_TASK_IN_STACKS_ONLY);
4453 if (task == null) {
4454 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4455 return;
4456 }
4457 task.cancelWindowTransition();
4458 }
4459 } finally {
4460 Binder.restoreCallingIdentity(ident);
4461 }
4462 }
4463
4464 @Override
4465 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004466 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 final long ident = Binder.clearCallingIdentity();
4468 try {
4469 final TaskRecord task;
4470 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004471 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4473 if (task == null) {
4474 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4475 return null;
4476 }
4477 }
4478 // Don't call this while holding the lock as this operation might hit the disk.
4479 return task.getSnapshot(reducedResolution);
4480 } finally {
4481 Binder.restoreCallingIdentity(ident);
4482 }
4483 }
4484
4485 @Override
4486 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4487 synchronized (mGlobalLock) {
4488 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4489 if (r == null) {
4490 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4491 + token);
4492 return;
4493 }
4494 final long origId = Binder.clearCallingIdentity();
4495 try {
4496 r.setDisablePreviewScreenshots(disable);
4497 } finally {
4498 Binder.restoreCallingIdentity(origId);
4499 }
4500 }
4501 }
4502
4503 /** Return the user id of the last resumed activity. */
4504 @Override
4505 public @UserIdInt
4506 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4509 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004510 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004511 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004512 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004513 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004514 }
4515 }
4516
4517 @Override
4518 public void updateLockTaskFeatures(int userId, int flags) {
4519 final int callingUid = Binder.getCallingUid();
4520 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 "updateLockTaskFeatures()");
4523 }
4524 synchronized (mGlobalLock) {
4525 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4526 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004527 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528 }
4529 }
4530
4531 @Override
4532 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4533 synchronized (mGlobalLock) {
4534 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4535 if (r == null) {
4536 return;
4537 }
4538 final long origId = Binder.clearCallingIdentity();
4539 try {
4540 r.setShowWhenLocked(showWhenLocked);
4541 } finally {
4542 Binder.restoreCallingIdentity(origId);
4543 }
4544 }
4545 }
4546
4547 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004548 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4549 synchronized (mGlobalLock) {
4550 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4551 if (r == null) {
4552 return;
4553 }
4554 final long origId = Binder.clearCallingIdentity();
4555 try {
4556 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4557 } finally {
4558 Binder.restoreCallingIdentity(origId);
4559 }
4560 }
4561 }
4562
4563 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4565 synchronized (mGlobalLock) {
4566 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4567 if (r == null) {
4568 return;
4569 }
4570 final long origId = Binder.clearCallingIdentity();
4571 try {
4572 r.setTurnScreenOn(turnScreenOn);
4573 } finally {
4574 Binder.restoreCallingIdentity(origId);
4575 }
4576 }
4577 }
4578
4579 @Override
4580 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004581 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004582 "registerRemoteAnimations");
4583 definition.setCallingPid(Binder.getCallingPid());
4584 synchronized (mGlobalLock) {
4585 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4586 if (r == null) {
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.registerRemoteAnimations(definition);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
4598 @Override
4599 public void registerRemoteAnimationForNextActivityStart(String packageName,
4600 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004601 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004602 "registerRemoteAnimationForNextActivityStart");
4603 adapter.setCallingPid(Binder.getCallingPid());
4604 synchronized (mGlobalLock) {
4605 final long origId = Binder.clearCallingIdentity();
4606 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004607 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 packageName, adapter);
4609 } finally {
4610 Binder.restoreCallingIdentity(origId);
4611 }
4612 }
4613 }
4614
Evan Rosky966759f2019-01-15 10:33:58 -08004615 @Override
4616 public void registerRemoteAnimationsForDisplay(int displayId,
4617 RemoteAnimationDefinition definition) {
4618 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4619 "registerRemoteAnimations");
4620 definition.setCallingPid(Binder.getCallingPid());
4621 synchronized (mGlobalLock) {
4622 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4623 if (display == null) {
4624 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4625 return;
4626 }
4627 final long origId = Binder.clearCallingIdentity();
4628 try {
4629 display.mDisplayContent.registerRemoteAnimations(definition);
4630 } finally {
4631 Binder.restoreCallingIdentity(origId);
4632 }
4633 }
4634 }
4635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004636 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4637 @Override
4638 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4639 synchronized (mGlobalLock) {
4640 final long origId = Binder.clearCallingIdentity();
4641 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004642 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004643 } finally {
4644 Binder.restoreCallingIdentity(origId);
4645 }
4646 }
4647 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004648
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 @Override
4650 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004651 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004653 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004654 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004655 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004656 }
4657 }
4658
4659 @Override
4660 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004661 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004662 != PERMISSION_GRANTED) {
4663 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4664 + Binder.getCallingPid()
4665 + ", uid=" + Binder.getCallingUid()
4666 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4667 Slog.w(TAG, msg);
4668 throw new SecurityException(msg);
4669 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004672 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004673 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004674 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 }
4676 }
4677
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004678 @Override
4679 public void stopAppSwitches() {
4680 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4681 synchronized (mGlobalLock) {
4682 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4683 mDidAppSwitch = false;
4684 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4685 }
4686 }
4687
4688 @Override
4689 public void resumeAppSwitches() {
4690 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4691 synchronized (mGlobalLock) {
4692 // Note that we don't execute any pending app switches... we will
4693 // let those wait until either the timeout, or the next start
4694 // activity request.
4695 mAppSwitchesAllowedTime = 0;
4696 }
4697 }
4698
4699 void onStartActivitySetDidAppSwitch() {
4700 if (mDidAppSwitch) {
4701 // This is the second allowed switch since we stopped switches, so now just generally
4702 // allow switches. Use case:
4703 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4704 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4705 // anyone to switch again).
4706 mAppSwitchesAllowedTime = 0;
4707 } else {
4708 mDidAppSwitch = true;
4709 }
4710 }
4711
4712 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 boolean shouldDisableNonVrUiLocked() {
4714 return mVrController.shouldDisableNonVrUiLocked();
4715 }
4716
Wale Ogunwale53783742018-09-16 10:21:51 -07004717 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 // VR apps are expected to run in a main display. If an app is turning on VR for
4719 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4720 // fullscreen stack before enabling VR Mode.
4721 // TODO: The goal of this code is to keep the VR app on the main display. When the
4722 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4723 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4724 // option would be a better choice here.
4725 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4726 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4727 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004728 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004729 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004730 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 mH.post(() -> {
4733 if (!mVrController.onVrModeChanged(r)) {
4734 return;
4735 }
4736 synchronized (mGlobalLock) {
4737 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4738 mWindowManager.disableNonVrUi(disableNonVrUi);
4739 if (disableNonVrUi) {
4740 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4741 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004742 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 }
4744 }
4745 });
4746 }
4747
Wale Ogunwale53783742018-09-16 10:21:51 -07004748 @Override
4749 public int getPackageScreenCompatMode(String packageName) {
4750 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4751 synchronized (mGlobalLock) {
4752 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4753 }
4754 }
4755
4756 @Override
4757 public void setPackageScreenCompatMode(String packageName, int mode) {
4758 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4759 "setPackageScreenCompatMode");
4760 synchronized (mGlobalLock) {
4761 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4762 }
4763 }
4764
4765 @Override
4766 public boolean getPackageAskScreenCompat(String packageName) {
4767 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4768 synchronized (mGlobalLock) {
4769 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4770 }
4771 }
4772
4773 @Override
4774 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4775 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4776 "setPackageAskScreenCompat");
4777 synchronized (mGlobalLock) {
4778 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4779 }
4780 }
4781
Wale Ogunwale64258362018-10-16 15:13:37 -07004782 public static String relaunchReasonToString(int relaunchReason) {
4783 switch (relaunchReason) {
4784 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4785 return "window_resize";
4786 case RELAUNCH_REASON_FREE_RESIZE:
4787 return "free_resize";
4788 default:
4789 return null;
4790 }
4791 }
4792
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004793 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004794 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004795 }
4796
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004797 /** Pokes the task persister. */
4798 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4799 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4800 }
4801
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 boolean isKeyguardLocked() {
4803 return mKeyguardController.isKeyguardLocked();
4804 }
4805
Garfield Tan01548632018-11-27 10:15:48 -08004806 /**
4807 * Clears launch params for the given package.
4808 * @param packageNames the names of the packages of which the launch params are to be cleared
4809 */
4810 @Override
4811 public void clearLaunchParamsForPackages(List<String> packageNames) {
4812 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4813 "clearLaunchParamsForPackages");
4814 synchronized (mGlobalLock) {
4815 for (int i = 0; i < packageNames.size(); ++i) {
4816 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4817 }
4818 }
4819 }
4820
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004821 /**
4822 * Makes the display with the given id a single task instance display. I.e the display can only
4823 * contain one task.
4824 */
4825 @Override
4826 public void setDisplayToSingleTaskInstance(int displayId) {
4827 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4828 "setDisplayToSingleTaskInstance");
4829 final long origId = Binder.clearCallingIdentity();
4830 try {
4831 final ActivityDisplay display =
4832 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4833 if (display != null) {
4834 display.setDisplayToSingleTaskInstance();
4835 }
4836 } finally {
4837 Binder.restoreCallingIdentity(origId);
4838 }
4839 }
4840
Wale Ogunwale31913b52018-10-13 08:29:31 -07004841 void dumpLastANRLocked(PrintWriter pw) {
4842 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4843 if (mLastANRState == null) {
4844 pw.println(" <no ANR has occurred since boot>");
4845 } else {
4846 pw.println(mLastANRState);
4847 }
4848 }
4849
4850 void dumpLastANRTracesLocked(PrintWriter pw) {
4851 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4852
4853 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4854 if (ArrayUtils.isEmpty(files)) {
4855 pw.println(" <no ANR has occurred since boot>");
4856 return;
4857 }
4858 // Find the latest file.
4859 File latest = null;
4860 for (File f : files) {
4861 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4862 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004863 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004864 }
4865 pw.print("File: ");
4866 pw.print(latest.getName());
4867 pw.println();
4868 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4869 String line;
4870 while ((line = in.readLine()) != null) {
4871 pw.println(line);
4872 }
4873 } catch (IOException e) {
4874 pw.print("Unable to read: ");
4875 pw.print(e);
4876 pw.println();
4877 }
4878 }
4879
4880 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4881 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4882 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4883 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4884 }
4885
4886 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4887 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4888 pw.println(header);
4889
Wale Ogunwaled32da472018-11-16 07:19:28 -08004890 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004891 dumpPackage);
4892 boolean needSep = printedAnything;
4893
4894 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004895 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004896 " ResumedActivity: ");
4897 if (printed) {
4898 printedAnything = true;
4899 needSep = false;
4900 }
4901
4902 if (dumpPackage == null) {
4903 if (needSep) {
4904 pw.println();
4905 }
4906 printedAnything = true;
4907 mStackSupervisor.dump(pw, " ");
4908 }
4909
4910 if (!printedAnything) {
4911 pw.println(" (nothing)");
4912 }
4913 }
4914
4915 void dumpActivityContainersLocked(PrintWriter pw) {
4916 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004917 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004918 pw.println(" ");
4919 }
4920
4921 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4922 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4923 getActivityStartController().dump(pw, "", dumpPackage);
4924 }
4925
4926 /**
4927 * There are three things that cmd can be:
4928 * - a flattened component name that matches an existing activity
4929 * - the cmd arg isn't the flattened component name of an existing activity:
4930 * dump all activity whose component contains the cmd as a substring
4931 * - A hex number of the ActivityRecord object instance.
4932 *
4933 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4934 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4935 */
4936 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4937 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4938 ArrayList<ActivityRecord> activities;
4939
4940 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004941 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004942 dumpFocusedStackOnly);
4943 }
4944
4945 if (activities.size() <= 0) {
4946 return false;
4947 }
4948
4949 String[] newArgs = new String[args.length - opti];
4950 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4951
4952 TaskRecord lastTask = null;
4953 boolean needSep = false;
4954 for (int i = activities.size() - 1; i >= 0; i--) {
4955 ActivityRecord r = activities.get(i);
4956 if (needSep) {
4957 pw.println();
4958 }
4959 needSep = true;
4960 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004961 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 if (lastTask != task) {
4963 lastTask = task;
4964 pw.print("TASK "); pw.print(lastTask.affinity);
4965 pw.print(" id="); pw.print(lastTask.taskId);
4966 pw.print(" userId="); pw.println(lastTask.userId);
4967 if (dumpAll) {
4968 lastTask.dump(pw, " ");
4969 }
4970 }
4971 }
4972 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4973 }
4974 return true;
4975 }
4976
4977 /**
4978 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4979 * there is a thread associated with the activity.
4980 */
4981 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4982 final ActivityRecord r, String[] args, boolean dumpAll) {
4983 String innerPrefix = prefix + " ";
4984 synchronized (mGlobalLock) {
4985 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4986 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4987 pw.print(" pid=");
4988 if (r.hasProcess()) pw.println(r.app.getPid());
4989 else pw.println("(not running)");
4990 if (dumpAll) {
4991 r.dump(pw, innerPrefix);
4992 }
4993 }
4994 if (r.attachedToProcess()) {
4995 // flush anything that is already in the PrintWriter since the thread is going
4996 // to write to the file descriptor directly
4997 pw.flush();
4998 try {
4999 TransferPipe tp = new TransferPipe();
5000 try {
5001 r.app.getThread().dumpActivity(tp.getWriteFd(),
5002 r.appToken, innerPrefix, args);
5003 tp.go(fd);
5004 } finally {
5005 tp.kill();
5006 }
5007 } catch (IOException e) {
5008 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5009 } catch (RemoteException e) {
5010 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5011 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005012 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005013 }
5014
sanryhuang498e77e2018-12-06 14:57:01 +08005015 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5016 boolean testPssMode) {
5017 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5018 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5019 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005020 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005021 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5022 st.toString());
5023 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005024 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5026 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005027 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5028 testPssMode);
5029 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005030 }
5031
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005032 int getCurrentUserId() {
5033 return mAmInternal.getCurrentUserId();
5034 }
5035
5036 private void enforceNotIsolatedCaller(String caller) {
5037 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5038 throw new SecurityException("Isolated process not allowed to call " + caller);
5039 }
5040 }
5041
Wale Ogunwalef6733932018-06-27 05:14:34 -07005042 public Configuration getConfiguration() {
5043 Configuration ci;
5044 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005045 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005046 ci.userSetLocale = false;
5047 }
5048 return ci;
5049 }
5050
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051 /**
5052 * Current global configuration information. Contains general settings for the entire system,
5053 * also corresponds to the merged configuration of the default display.
5054 */
5055 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005056 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005057 }
5058
5059 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5060 boolean initLocale) {
5061 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5062 }
5063
5064 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5065 boolean initLocale, boolean deferResume) {
5066 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5067 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5068 UserHandle.USER_NULL, deferResume);
5069 }
5070
Wale Ogunwale59507092018-10-29 09:00:30 -07005071 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 final long origId = Binder.clearCallingIdentity();
5073 try {
5074 synchronized (mGlobalLock) {
5075 updateConfigurationLocked(values, null, false, true, userId,
5076 false /* deferResume */);
5077 }
5078 } finally {
5079 Binder.restoreCallingIdentity(origId);
5080 }
5081 }
5082
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005083 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5084 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5085 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5086 deferResume, null /* result */);
5087 }
5088
5089 /**
5090 * Do either or both things: (1) change the current configuration, and (2)
5091 * make sure the given activity is running with the (now) current
5092 * configuration. Returns true if the activity has been left running, or
5093 * false if <var>starting</var> is being destroyed to match the new
5094 * configuration.
5095 *
5096 * @param userId is only used when persistent parameter is set to true to persist configuration
5097 * for that particular user
5098 */
5099 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5100 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5101 ActivityTaskManagerService.UpdateConfigurationResult result) {
5102 int changes = 0;
5103 boolean kept = true;
5104
5105 if (mWindowManager != null) {
5106 mWindowManager.deferSurfaceLayout();
5107 }
5108 try {
5109 if (values != null) {
5110 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5111 deferResume);
5112 }
5113
5114 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5115 } finally {
5116 if (mWindowManager != null) {
5117 mWindowManager.continueSurfaceLayout();
5118 }
5119 }
5120
5121 if (result != null) {
5122 result.changes = changes;
5123 result.activityRelaunched = !kept;
5124 }
5125 return kept;
5126 }
5127
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005128 /** Update default (global) configuration and notify listeners about changes. */
5129 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5130 boolean persistent, int userId, boolean deferResume) {
5131 mTempConfig.setTo(getGlobalConfiguration());
5132 final int changes = mTempConfig.updateFrom(values);
5133 if (changes == 0) {
5134 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5135 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5136 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5137 // (even if there are no actual changes) to unfreeze the window.
5138 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5139 return 0;
5140 }
5141
5142 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5143 "Updating global configuration to: " + values);
5144
5145 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5146 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5147 values.colorMode,
5148 values.densityDpi,
5149 values.fontScale,
5150 values.hardKeyboardHidden,
5151 values.keyboard,
5152 values.keyboardHidden,
5153 values.mcc,
5154 values.mnc,
5155 values.navigation,
5156 values.navigationHidden,
5157 values.orientation,
5158 values.screenHeightDp,
5159 values.screenLayout,
5160 values.screenWidthDp,
5161 values.smallestScreenWidthDp,
5162 values.touchscreen,
5163 values.uiMode);
5164
5165
5166 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5167 final LocaleList locales = values.getLocales();
5168 int bestLocaleIndex = 0;
5169 if (locales.size() > 1) {
5170 if (mSupportedSystemLocales == null) {
5171 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5172 }
5173 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5174 }
5175 SystemProperties.set("persist.sys.locale",
5176 locales.get(bestLocaleIndex).toLanguageTag());
5177 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005178
5179 final Message m = PooledLambda.obtainMessage(
5180 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5181 locales.get(bestLocaleIndex));
5182 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183 }
5184
Yunfan Chen75157d72018-07-27 14:47:21 +09005185 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186
5187 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005188 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189
5190 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5191 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005192 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193
5194 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005195 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 AttributeCache ac = AttributeCache.instance();
5198 if (ac != null) {
5199 ac.updateConfiguration(mTempConfig);
5200 }
5201
5202 // Make sure all resources in our process are updated right now, so that anyone who is going
5203 // to retrieve resource values after we return will be sure to get the new ones. This is
5204 // especially important during boot, where the first config change needs to guarantee all
5205 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005206 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005207
5208 // We need another copy of global config because we're scheduling some calls instead of
5209 // running them in place. We need to be sure that object we send will be handled unchanged.
5210 final Configuration configCopy = new Configuration(mTempConfig);
5211 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005212 final Message msg = PooledLambda.obtainMessage(
5213 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5214 this, userId, configCopy);
5215 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 }
5217
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005218 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5219 for (int i = pidMap.size() - 1; i >= 0; i--) {
5220 final int pid = pidMap.keyAt(i);
5221 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005222 if (DEBUG_CONFIGURATION) {
5223 Slog.v(TAG_CONFIGURATION, "Update process config of "
5224 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005226 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227 }
5228
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005229 final Message msg = PooledLambda.obtainMessage(
5230 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5231 mAmInternal, changes, initLocale);
5232 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233
5234 // Override configuration of the default display duplicates global config, so we need to
5235 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005236 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237 DEFAULT_DISPLAY);
5238
5239 return changes;
5240 }
5241
5242 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5243 boolean deferResume, int displayId) {
5244 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5245 displayId, null /* result */);
5246 }
5247
5248 /**
5249 * Updates override configuration specific for the selected display. If no config is provided,
5250 * new one will be computed in WM based on current display info.
5251 */
5252 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5253 ActivityRecord starting, boolean deferResume, int displayId,
5254 ActivityTaskManagerService.UpdateConfigurationResult result) {
5255 int changes = 0;
5256 boolean kept = true;
5257
5258 if (mWindowManager != null) {
5259 mWindowManager.deferSurfaceLayout();
5260 }
5261 try {
5262 if (values != null) {
5263 if (displayId == DEFAULT_DISPLAY) {
5264 // Override configuration of the default display duplicates global config, so
5265 // we're calling global config update instead for default display. It will also
5266 // apply the correct override config.
5267 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5268 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5269 } else {
5270 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5271 }
5272 }
5273
5274 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5275 } finally {
5276 if (mWindowManager != null) {
5277 mWindowManager.continueSurfaceLayout();
5278 }
5279 }
5280
5281 if (result != null) {
5282 result.changes = changes;
5283 result.activityRelaunched = !kept;
5284 }
5285 return kept;
5286 }
5287
5288 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5289 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005290 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291 final int changes = mTempConfig.updateFrom(values);
5292 if (changes != 0) {
5293 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5294 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005295 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296
5297 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5298 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005299 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300
Wale Ogunwale5c918702018-10-18 11:06:33 -07005301 // Post message to start process to avoid possible deadlock of calling into AMS with
5302 // the ATMS lock held.
5303 final Message msg = PooledLambda.obtainMessage(
5304 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005305 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005306 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 }
5308 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309 return changes;
5310 }
5311
Wale Ogunwalef6733932018-06-27 05:14:34 -07005312 private void updateEventDispatchingLocked(boolean booted) {
5313 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5314 }
5315
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005316 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5317 final ContentResolver resolver = mContext.getContentResolver();
5318 Settings.System.putConfigurationForUser(resolver, config, userId);
5319 }
5320
5321 private void sendLocaleToMountDaemonMsg(Locale l) {
5322 try {
5323 IBinder service = ServiceManager.getService("mount");
5324 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5325 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5326 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5327 } catch (RemoteException e) {
5328 Log.e(TAG, "Error storing locale for decryption UI", e);
5329 }
5330 }
5331
Alison Cichowlas3e340502018-08-07 17:15:01 -04005332 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5333 mStartActivitySources.remove(permissionToken);
5334 mExpiredStartAsCallerTokens.add(permissionToken);
5335 }
5336
5337 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5338 mExpiredStartAsCallerTokens.remove(permissionToken);
5339 }
5340
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005341 boolean isActivityStartsLoggingEnabled() {
5342 return mAmInternal.isActivityStartsLoggingEnabled();
5343 }
5344
Michal Karpinski8596ded2018-11-14 14:43:48 +00005345 boolean isBackgroundActivityStartsEnabled() {
5346 return mAmInternal.isBackgroundActivityStartsEnabled();
5347 }
5348
Ricky Waiaca8a772019-04-04 16:01:06 +01005349 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5350 if (packageName == null) {
5351 return false;
5352 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005353 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5354 }
5355
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 void enableScreenAfterBoot(boolean booted) {
5357 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5358 SystemClock.uptimeMillis());
5359 mWindowManager.enableScreenAfterBoot();
5360
5361 synchronized (mGlobalLock) {
5362 updateEventDispatchingLocked(booted);
5363 }
5364 }
5365
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005366 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5367 if (r == null || !r.hasProcess()) {
5368 return KEY_DISPATCHING_TIMEOUT_MS;
5369 }
5370 return getInputDispatchingTimeoutLocked(r.app);
5371 }
5372
5373 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005374 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005375 }
5376
Wale Ogunwalef6733932018-06-27 05:14:34 -07005377 /**
5378 * Decide based on the configuration whether we should show the ANR,
5379 * crash, etc dialogs. The idea is that if there is no affordance to
5380 * press the on-screen buttons, or the user experience would be more
5381 * greatly impacted than the crash itself, we shouldn't show the dialog.
5382 *
5383 * A thought: SystemUI might also want to get told about this, the Power
5384 * dialog / global actions also might want different behaviors.
5385 */
5386 private void updateShouldShowDialogsLocked(Configuration config) {
5387 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5388 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5389 && config.navigation == Configuration.NAVIGATION_NONAV);
5390 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5391 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5392 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5393 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5394 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5395 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5396 HIDE_ERROR_DIALOGS, 0) != 0;
5397 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5398 }
5399
5400 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5401 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5402 FONT_SCALE, 1.0f, userId);
5403
5404 synchronized (this) {
5405 if (getGlobalConfiguration().fontScale == scaleFactor) {
5406 return;
5407 }
5408
5409 final Configuration configuration
5410 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5411 configuration.fontScale = scaleFactor;
5412 updatePersistentConfiguration(configuration, userId);
5413 }
5414 }
5415
5416 // Actually is sleeping or shutting down or whatever else in the future
5417 // is an inactive state.
5418 boolean isSleepingOrShuttingDownLocked() {
5419 return isSleepingLocked() || mShuttingDown;
5420 }
5421
5422 boolean isSleepingLocked() {
5423 return mSleeping;
5424 }
5425
Riddle Hsu16567132018-08-16 21:37:47 +08005426 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005427 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005428 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 if (task.isActivityTypeStandard()) {
5430 if (mCurAppTimeTracker != r.appTimeTracker) {
5431 // We are switching app tracking. Complete the current one.
5432 if (mCurAppTimeTracker != null) {
5433 mCurAppTimeTracker.stop();
5434 mH.obtainMessage(
5435 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005436 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 mCurAppTimeTracker = null;
5438 }
5439 if (r.appTimeTracker != null) {
5440 mCurAppTimeTracker = r.appTimeTracker;
5441 startTimeTrackingFocusedActivityLocked();
5442 }
5443 } else {
5444 startTimeTrackingFocusedActivityLocked();
5445 }
5446 } else {
5447 r.appTimeTracker = null;
5448 }
5449 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5450 // TODO: Probably not, because we don't want to resume voice on switching
5451 // back to this activity
5452 if (task.voiceInteractor != null) {
5453 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5454 } else {
5455 finishRunningVoiceLocked();
5456
5457 if (mLastResumedActivity != null) {
5458 final IVoiceInteractionSession session;
5459
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005460 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 if (lastResumedActivityTask != null
5462 && lastResumedActivityTask.voiceSession != null) {
5463 session = lastResumedActivityTask.voiceSession;
5464 } else {
5465 session = mLastResumedActivity.voiceSession;
5466 }
5467
5468 if (session != null) {
5469 // We had been in a voice interaction session, but now focused has
5470 // move to something different. Just finish the session, we can't
5471 // return to it and retain the proper state and synchronization with
5472 // the voice interaction service.
5473 finishVoiceTask(session);
5474 }
5475 }
5476 }
5477
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005478 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5479 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005480 }
5481 updateResumedAppTrace(r);
5482 mLastResumedActivity = r;
5483
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005484 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485
5486 applyUpdateLockStateLocked(r);
5487 applyUpdateVrModeLocked(r);
5488
5489 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005490 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005491 r == null ? "NULL" : r.shortComponentName,
5492 reason);
5493 }
5494
5495 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5496 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005497 final ActivityTaskManagerInternal.SleepToken token =
5498 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005499 updateSleepIfNeededLocked();
5500 return token;
5501 }
5502 }
5503
5504 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005505 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 final boolean wasSleeping = mSleeping;
5507 boolean updateOomAdj = false;
5508
5509 if (!shouldSleep) {
5510 // If wasSleeping is true, we need to wake up activity manager state from when
5511 // we started sleeping. In either case, we need to apply the sleep tokens, which
5512 // will wake up stacks or put them to sleep as appropriate.
5513 if (wasSleeping) {
5514 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005515 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5516 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 startTimeTrackingFocusedActivityLocked();
5518 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005519 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5521 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005522 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005523 if (wasSleeping) {
5524 updateOomAdj = true;
5525 }
5526 } else if (!mSleeping && shouldSleep) {
5527 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005528 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5529 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005530 if (mCurAppTimeTracker != null) {
5531 mCurAppTimeTracker.stop();
5532 }
5533 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005534 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 mStackSupervisor.goingToSleepLocked();
5536 updateResumedAppTrace(null /* resumed */);
5537 updateOomAdj = true;
5538 }
5539 if (updateOomAdj) {
5540 mH.post(mAmInternal::updateOomAdj);
5541 }
5542 }
5543
5544 void updateOomAdj() {
5545 mH.post(mAmInternal::updateOomAdj);
5546 }
5547
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 void updateCpuStats() {
5549 mH.post(mAmInternal::updateCpuStats);
5550 }
5551
Hui Yu03d12402018-12-06 18:00:37 -08005552 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5553 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005554 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5555 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005556 mH.sendMessage(m);
5557 }
5558
Hui Yu03d12402018-12-06 18:00:37 -08005559 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005560 ComponentName taskRoot = null;
5561 final TaskRecord task = activity.getTaskRecord();
5562 if (task != null) {
5563 final ActivityRecord rootActivity = task.getRootActivity();
5564 if (rootActivity != null) {
5565 taskRoot = rootActivity.mActivityComponent;
5566 }
5567 }
5568
Hui Yu03d12402018-12-06 18:00:37 -08005569 final Message m = PooledLambda.obtainMessage(
5570 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005571 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005572 mH.sendMessage(m);
5573 }
5574
Wale Ogunwale53783742018-09-16 10:21:51 -07005575 void setBooting(boolean booting) {
5576 mAmInternal.setBooting(booting);
5577 }
5578
5579 boolean isBooting() {
5580 return mAmInternal.isBooting();
5581 }
5582
5583 void setBooted(boolean booted) {
5584 mAmInternal.setBooted(booted);
5585 }
5586
5587 boolean isBooted() {
5588 return mAmInternal.isBooted();
5589 }
5590
5591 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5592 mH.post(() -> {
5593 if (finishBooting) {
5594 mAmInternal.finishBooting();
5595 }
5596 if (enableScreen) {
5597 mInternal.enableScreenAfterBoot(isBooted());
5598 }
5599 });
5600 }
5601
5602 void setHeavyWeightProcess(ActivityRecord root) {
5603 mHeavyWeightProcess = root.app;
5604 final Message m = PooledLambda.obtainMessage(
5605 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005606 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005607 mH.sendMessage(m);
5608 }
5609
5610 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5611 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5612 return;
5613 }
5614
5615 mHeavyWeightProcess = null;
5616 final Message m = PooledLambda.obtainMessage(
5617 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5618 proc.mUserId);
5619 mH.sendMessage(m);
5620 }
5621
5622 private void cancelHeavyWeightProcessNotification(int userId) {
5623 final INotificationManager inm = NotificationManager.getService();
5624 if (inm == null) {
5625 return;
5626 }
5627 try {
5628 inm.cancelNotificationWithTag("android", null,
5629 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5630 } catch (RuntimeException e) {
5631 Slog.w(TAG, "Error canceling notification for service", e);
5632 } catch (RemoteException e) {
5633 }
5634
5635 }
5636
5637 private void postHeavyWeightProcessNotification(
5638 WindowProcessController proc, Intent intent, int userId) {
5639 if (proc == null) {
5640 return;
5641 }
5642
5643 final INotificationManager inm = NotificationManager.getService();
5644 if (inm == null) {
5645 return;
5646 }
5647
5648 try {
5649 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5650 String text = mContext.getString(R.string.heavy_weight_notification,
5651 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5652 Notification notification =
5653 new Notification.Builder(context,
5654 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5655 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5656 .setWhen(0)
5657 .setOngoing(true)
5658 .setTicker(text)
5659 .setColor(mContext.getColor(
5660 com.android.internal.R.color.system_notification_accent_color))
5661 .setContentTitle(text)
5662 .setContentText(
5663 mContext.getText(R.string.heavy_weight_notification_detail))
5664 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5665 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5666 new UserHandle(userId)))
5667 .build();
5668 try {
5669 inm.enqueueNotificationWithTag("android", "android", null,
5670 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5671 } catch (RuntimeException e) {
5672 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5673 } catch (RemoteException e) {
5674 }
5675 } catch (PackageManager.NameNotFoundException e) {
5676 Slog.w(TAG, "Unable to create context for heavy notification", e);
5677 }
5678
5679 }
5680
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005681 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5682 IBinder token, String resultWho, int requestCode, Intent[] intents,
5683 String[] resolvedTypes, int flags, Bundle bOptions) {
5684
5685 ActivityRecord activity = null;
5686 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5687 activity = ActivityRecord.isInStackLocked(token);
5688 if (activity == null) {
5689 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5690 return null;
5691 }
5692 if (activity.finishing) {
5693 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5694 return null;
5695 }
5696 }
5697
5698 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5699 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5700 bOptions);
5701 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5702 if (noCreate) {
5703 return rec;
5704 }
5705 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5706 if (activity.pendingResults == null) {
5707 activity.pendingResults = new HashSet<>();
5708 }
5709 activity.pendingResults.add(rec.ref);
5710 }
5711 return rec;
5712 }
5713
Andrii Kulian52d255c2018-07-13 11:32:19 -07005714 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005715 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005716 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005717 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5718 mCurAppTimeTracker.start(resumedActivity.packageName);
5719 }
5720 }
5721
5722 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5723 if (mTracedResumedActivity != null) {
5724 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5725 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5726 }
5727 if (resumed != null) {
5728 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5729 constructResumedTraceName(resumed.packageName), 0);
5730 }
5731 mTracedResumedActivity = resumed;
5732 }
5733
5734 private String constructResumedTraceName(String packageName) {
5735 return "focused app: " + packageName;
5736 }
5737
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005738 /** Applies latest configuration and/or visibility updates if needed. */
5739 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5740 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005741 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005742 // mainStack is null during startup.
5743 if (mainStack != null) {
5744 if (changes != 0 && starting == null) {
5745 // If the configuration changed, and the caller is not already
5746 // in the process of starting an activity, then find the top
5747 // activity to check if its configuration needs to change.
5748 starting = mainStack.topRunningActivityLocked();
5749 }
5750
5751 if (starting != null) {
5752 kept = starting.ensureActivityConfiguration(changes,
5753 false /* preserveWindow */);
5754 // And we need to make sure at this point that all other activities
5755 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005756 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005757 !PRESERVE_WINDOWS);
5758 }
5759 }
5760
5761 return kept;
5762 }
5763
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005764 void scheduleAppGcsLocked() {
5765 mH.post(() -> mAmInternal.scheduleAppGcs());
5766 }
5767
Wale Ogunwale53783742018-09-16 10:21:51 -07005768 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5769 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5770 }
5771
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005772 /**
5773 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5774 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5775 * on demand.
5776 */
5777 IPackageManager getPackageManager() {
5778 return AppGlobals.getPackageManager();
5779 }
5780
5781 PackageManagerInternal getPackageManagerInternalLocked() {
5782 if (mPmInternal == null) {
5783 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5784 }
5785 return mPmInternal;
5786 }
5787
Hai Zhangf4da9be2019-05-01 13:46:06 +08005788 PermissionPolicyInternal getPermissionPolicyInternal() {
5789 if (mPermissionPolicyInternal == null) {
5790 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5791 }
5792 return mPermissionPolicyInternal;
5793 }
5794
Wale Ogunwale008163e2018-07-23 23:11:08 -07005795 AppWarnings getAppWarningsLocked() {
5796 return mAppWarnings;
5797 }
5798
Wale Ogunwale214f3482018-10-04 11:00:47 -07005799 Intent getHomeIntent() {
5800 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5801 intent.setComponent(mTopComponent);
5802 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5803 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5804 intent.addCategory(Intent.CATEGORY_HOME);
5805 }
5806 return intent;
5807 }
5808
Chilun2ef71f72018-11-16 17:57:15 +08005809 /**
5810 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5811 * activities.
5812 *
5813 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5814 * component defined in config_secondaryHomeComponent.
5815 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5816 */
5817 Intent getSecondaryHomeIntent(String preferredPackage) {
5818 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5819 if (preferredPackage == null) {
5820 // Using the component stored in config if no package name.
5821 final String secondaryHomeComponent = mContext.getResources().getString(
5822 com.android.internal.R.string.config_secondaryHomeComponent);
5823 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5824 } else {
5825 intent.setPackage(preferredPackage);
5826 }
5827 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5828 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5829 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5830 }
5831 return intent;
5832 }
5833
Wale Ogunwale214f3482018-10-04 11:00:47 -07005834 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5835 if (info == null) return null;
5836 ApplicationInfo newInfo = new ApplicationInfo(info);
5837 newInfo.initForUser(userId);
5838 return newInfo;
5839 }
5840
Wale Ogunwale9c103022018-10-18 07:44:54 -07005841 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005842 if (uid == SYSTEM_UID) {
5843 // The system gets to run in any process. If there are multiple processes with the same
5844 // uid, just pick the first (this should never happen).
5845 final SparseArray<WindowProcessController> procs =
5846 mProcessNames.getMap().get(processName);
5847 if (procs == null) return null;
5848 final int procCount = procs.size();
5849 for (int i = 0; i < procCount; i++) {
5850 final int procUid = procs.keyAt(i);
5851 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5852 // Don't use an app process or different user process for system component.
5853 continue;
5854 }
5855 return procs.valueAt(i);
5856 }
5857 }
5858
5859 return mProcessNames.get(processName, uid);
5860 }
5861
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005862 WindowProcessController getProcessController(IApplicationThread thread) {
5863 if (thread == null) {
5864 return null;
5865 }
5866
5867 final IBinder threadBinder = thread.asBinder();
5868 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5869 for (int i = pmap.size()-1; i >= 0; i--) {
5870 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5871 for (int j = procs.size() - 1; j >= 0; j--) {
5872 final WindowProcessController proc = procs.valueAt(j);
5873 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5874 return proc;
5875 }
5876 }
5877 }
5878
5879 return null;
5880 }
5881
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005882 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005883 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005884 if (proc == null) return null;
5885 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5886 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005887 }
5888 return null;
5889 }
5890
Riddle Hsua0536432019-02-16 00:38:59 +08005891 int getUidState(int uid) {
5892 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005893 }
5894
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005895 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005896 // A uid is considered to be foreground if it has a visible non-toast window.
5897 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005898 }
5899
Ricky Wai96f5c352019-04-10 18:40:17 +01005900 boolean isDeviceOwner(int uid) {
5901 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005902 }
5903
Ricky Wai96f5c352019-04-10 18:40:17 +01005904 void setDeviceOwnerUid(int uid) {
5905 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005906 }
5907
Wale Ogunwale9de19442018-10-18 19:05:03 -07005908 /**
5909 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5910 * the whitelist
5911 */
5912 String getPendingTempWhitelistTagForUidLocked(int uid) {
5913 return mPendingTempWhitelist.get(uid);
5914 }
5915
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005916 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5917 if (true || Build.IS_USER) {
5918 return;
5919 }
5920
5921 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5922 StrictMode.allowThreadDiskWrites();
5923 try {
5924 File tracesDir = new File("/data/anr");
5925 File tracesFile = null;
5926 try {
5927 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5928
5929 StringBuilder sb = new StringBuilder();
5930 Time tobj = new Time();
5931 tobj.set(System.currentTimeMillis());
5932 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5933 sb.append(": ");
5934 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5935 sb.append(" since ");
5936 sb.append(msg);
5937 FileOutputStream fos = new FileOutputStream(tracesFile);
5938 fos.write(sb.toString().getBytes());
5939 if (app == null) {
5940 fos.write("\n*** No application process!".getBytes());
5941 }
5942 fos.close();
5943 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5944 } catch (IOException e) {
5945 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5946 return;
5947 }
5948
5949 if (app != null && app.getPid() > 0) {
5950 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5951 firstPids.add(app.getPid());
5952 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5953 }
5954
5955 File lastTracesFile = null;
5956 File curTracesFile = null;
5957 for (int i=9; i>=0; i--) {
5958 String name = String.format(Locale.US, "slow%02d.txt", i);
5959 curTracesFile = new File(tracesDir, name);
5960 if (curTracesFile.exists()) {
5961 if (lastTracesFile != null) {
5962 curTracesFile.renameTo(lastTracesFile);
5963 } else {
5964 curTracesFile.delete();
5965 }
5966 }
5967 lastTracesFile = curTracesFile;
5968 }
5969 tracesFile.renameTo(curTracesFile);
5970 } finally {
5971 StrictMode.setThreadPolicy(oldPolicy);
5972 }
5973 }
5974
Michal Karpinskida34cd42019-04-02 19:46:52 +01005975 boolean isAssociatedCompanionApp(int userId, int uid) {
5976 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5977 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005978 return false;
5979 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005980 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005981 }
5982
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005983 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005984 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005985
5986
Wale Ogunwale98875612018-10-12 07:53:02 -07005987 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5988 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005989
Riddle Hsud93a6c42018-11-29 21:50:06 +08005990 H(Looper looper) {
5991 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005992 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005993
5994 @Override
5995 public void handleMessage(Message msg) {
5996 switch (msg.what) {
5997 case REPORT_TIME_TRACKER_MSG: {
5998 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5999 tracker.deliverResult(mContext);
6000 } break;
6001 }
6002 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006003 }
6004
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006005 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006006 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006007
6008 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006009 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006010 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006011
6012 @Override
6013 public void handleMessage(Message msg) {
6014 switch (msg.what) {
6015 case DISMISS_DIALOG_UI_MSG: {
6016 final Dialog d = (Dialog) msg.obj;
6017 d.dismiss();
6018 break;
6019 }
6020 }
6021 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006022 }
6023
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024 final class LocalService extends ActivityTaskManagerInternal {
6025 @Override
6026 public SleepToken acquireSleepToken(String tag, int displayId) {
6027 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006028 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006029 }
6030
6031 @Override
6032 public ComponentName getHomeActivityForUser(int userId) {
6033 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006034 final ActivityRecord homeActivity =
6035 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006036 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006037 }
6038 }
6039
6040 @Override
6041 public void onLocalVoiceInteractionStarted(IBinder activity,
6042 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6043 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006044 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046 }
6047
6048 @Override
6049 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6050 synchronized (mGlobalLock) {
6051 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6052 reasons, timestamp);
6053 }
6054 }
6055
6056 @Override
6057 public void notifyAppTransitionFinished() {
6058 synchronized (mGlobalLock) {
6059 mStackSupervisor.notifyAppTransitionDone();
6060 }
6061 }
6062
6063 @Override
6064 public void notifyAppTransitionCancelled() {
6065 synchronized (mGlobalLock) {
6066 mStackSupervisor.notifyAppTransitionDone();
6067 }
6068 }
6069
6070 @Override
6071 public List<IBinder> getTopVisibleActivities() {
6072 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006073 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006074 }
6075 }
6076
6077 @Override
6078 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6079 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006080 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006081 }
6082 }
6083
6084 @Override
6085 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6086 Bundle bOptions) {
6087 Preconditions.checkNotNull(intents, "intents");
6088 final String[] resolvedTypes = new String[intents.length];
6089
6090 // UID of the package on user userId.
6091 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6092 // packageUid may not be initialized.
6093 int packageUid = 0;
6094 final long ident = Binder.clearCallingIdentity();
6095
6096 try {
6097 for (int i = 0; i < intents.length; i++) {
6098 resolvedTypes[i] =
6099 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6100 }
6101
6102 packageUid = AppGlobals.getPackageManager().getPackageUid(
6103 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6104 } catch (RemoteException e) {
6105 // Shouldn't happen.
6106 } finally {
6107 Binder.restoreCallingIdentity(ident);
6108 }
6109
Riddle Hsu591bf612019-02-14 17:55:31 +08006110 return getActivityStartController().startActivitiesInPackage(
6111 packageUid, packageName,
6112 intents, resolvedTypes, null /* resultTo */,
6113 SafeActivityOptions.fromBundle(bOptions), userId,
6114 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6115 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117
6118 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006119 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6120 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6121 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6122 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006123 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006124 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006125 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6126 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6127 userId, validateIncomingUser, originatingPendingIntent,
6128 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006129 }
6130 }
6131
6132 @Override
6133 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6134 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6135 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6136 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006137 PendingIntentRecord originatingPendingIntent,
6138 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006139 synchronized (mGlobalLock) {
6140 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6141 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6142 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006143 validateIncomingUser, originatingPendingIntent,
6144 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006145 }
6146 }
6147
6148 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006149 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6150 Intent intent, Bundle options, int userId) {
6151 return ActivityTaskManagerService.this.startActivityAsUser(
6152 caller, callerPacakge, intent,
6153 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6154 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6155 false /*validateIncomingUser*/);
6156 }
6157
6158 @Override
lumark588a3e82018-07-20 18:53:54 +08006159 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 synchronized (mGlobalLock) {
6161
6162 // We might change the visibilities here, so prepare an empty app transition which
6163 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006164 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006165 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006166 if (activityDisplay == null) {
6167 return;
6168 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006169 final DisplayContent dc = activityDisplay.mDisplayContent;
6170 final boolean wasTransitionSet =
6171 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006173 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006175 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176
6177 // If there was a transition set already we don't want to interfere with it as we
6178 // might be starting it too early.
6179 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006180 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183 if (callback != null) {
6184 callback.run();
6185 }
6186 }
6187
6188 @Override
6189 public void notifyKeyguardTrustedChanged() {
6190 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006191 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006192 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 }
6194 }
6195 }
6196
6197 /**
6198 * Called after virtual display Id is updated by
6199 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6200 * {@param vrVr2dDisplayId}.
6201 */
6202 @Override
6203 public void setVr2dDisplayId(int vr2dDisplayId) {
6204 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6205 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006206 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 }
6208 }
6209
6210 @Override
6211 public void setFocusedActivity(IBinder token) {
6212 synchronized (mGlobalLock) {
6213 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6214 if (r == null) {
6215 throw new IllegalArgumentException(
6216 "setFocusedActivity: No activity record matching token=" + token);
6217 }
Louis Chang19443452018-10-09 12:10:21 +08006218 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006219 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006220 }
6221 }
6222 }
6223
6224 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006225 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006226 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 }
6228
6229 @Override
6230 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006231 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 }
6233
6234 @Override
6235 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006236 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006237 }
6238
6239 @Override
6240 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6241 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6242 }
6243
6244 @Override
6245 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006246 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006247 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006248
6249 @Override
6250 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6251 synchronized (mGlobalLock) {
6252 mActiveVoiceInteractionServiceComponent = component;
6253 }
6254 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006255
6256 @Override
6257 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6258 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6259 return;
6260 }
6261 synchronized (mGlobalLock) {
6262 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6263 if (types == null) {
6264 if (uid < 0) {
6265 return;
6266 }
6267 types = new ArrayMap<>();
6268 mAllowAppSwitchUids.put(userId, types);
6269 }
6270 if (uid < 0) {
6271 types.remove(type);
6272 } else {
6273 types.put(type, uid);
6274 }
6275 }
6276 }
6277
6278 @Override
6279 public void onUserStopped(int userId) {
6280 synchronized (mGlobalLock) {
6281 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6282 mAllowAppSwitchUids.remove(userId);
6283 }
6284 }
6285
6286 @Override
6287 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6288 synchronized (mGlobalLock) {
6289 return ActivityTaskManagerService.this.isGetTasksAllowed(
6290 caller, callingPid, callingUid);
6291 }
6292 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006293
Riddle Hsua0536432019-02-16 00:38:59 +08006294 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006295 @Override
6296 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006298 mProcessNames.put(proc.mName, proc.mUid, proc);
6299 }
6300 }
6301
Riddle Hsua0536432019-02-16 00:38:59 +08006302 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006303 @Override
6304 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006306 mProcessNames.remove(name, uid);
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006311 @Override
6312 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006314 if (proc == mHomeProcess) {
6315 mHomeProcess = null;
6316 }
6317 if (proc == mPreviousProcess) {
6318 mPreviousProcess = null;
6319 }
6320 }
6321 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006322
Riddle Hsua0536432019-02-16 00:38:59 +08006323 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006324 @Override
6325 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006326 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006327 return mTopProcessState;
6328 }
6329 }
6330
Riddle Hsua0536432019-02-16 00:38:59 +08006331 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006332 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006333 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006334 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006335 return proc == mHeavyWeightProcess;
6336 }
6337 }
6338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006340 @Override
6341 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006343 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6344 }
6345 }
6346
6347 @Override
6348 public void finishHeavyWeightApp() {
6349 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006350 if (mHeavyWeightProcess != null) {
6351 mHeavyWeightProcess.finishActivities();
6352 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006353 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6354 mHeavyWeightProcess);
6355 }
6356 }
6357
Riddle Hsua0536432019-02-16 00:38:59 +08006358 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006359 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006360 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006361 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006362 return isSleepingLocked();
6363 }
6364 }
6365
6366 @Override
6367 public boolean isShuttingDown() {
6368 synchronized (mGlobalLock) {
6369 return mShuttingDown;
6370 }
6371 }
6372
6373 @Override
6374 public boolean shuttingDown(boolean booted, int timeout) {
6375 synchronized (mGlobalLock) {
6376 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006377 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006379 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006380 return mStackSupervisor.shutdownLocked(timeout);
6381 }
6382 }
6383
6384 @Override
6385 public void enableScreenAfterBoot(boolean booted) {
6386 synchronized (mGlobalLock) {
6387 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6388 SystemClock.uptimeMillis());
6389 mWindowManager.enableScreenAfterBoot();
6390 updateEventDispatchingLocked(booted);
6391 }
6392 }
6393
6394 @Override
6395 public boolean showStrictModeViolationDialog() {
6396 synchronized (mGlobalLock) {
6397 return mShowDialogs && !mSleeping && !mShuttingDown;
6398 }
6399 }
6400
6401 @Override
6402 public void showSystemReadyErrorDialogsIfNeeded() {
6403 synchronized (mGlobalLock) {
6404 try {
6405 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6406 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6407 + " data partition or your device will be unstable.");
6408 mUiHandler.post(() -> {
6409 if (mShowDialogs) {
6410 AlertDialog d = new BaseErrorDialog(mUiContext);
6411 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6412 d.setCancelable(false);
6413 d.setTitle(mUiContext.getText(R.string.android_system_label));
6414 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6415 d.setButton(DialogInterface.BUTTON_POSITIVE,
6416 mUiContext.getText(R.string.ok),
6417 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6418 d.show();
6419 }
6420 });
6421 }
6422 } catch (RemoteException e) {
6423 }
6424
6425 if (!Build.isBuildConsistent()) {
6426 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6427 mUiHandler.post(() -> {
6428 if (mShowDialogs) {
6429 AlertDialog d = new BaseErrorDialog(mUiContext);
6430 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6431 d.setCancelable(false);
6432 d.setTitle(mUiContext.getText(R.string.android_system_label));
6433 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6434 d.setButton(DialogInterface.BUTTON_POSITIVE,
6435 mUiContext.getText(R.string.ok),
6436 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6437 d.show();
6438 }
6439 });
6440 }
6441 }
6442 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006443
6444 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006445 public void onProcessMapped(int pid, WindowProcessController proc) {
6446 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006447 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006448 }
6449 }
6450
6451 @Override
6452 public void onProcessUnMapped(int pid) {
6453 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006454 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006455 }
6456 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006457
6458 @Override
6459 public void onPackageDataCleared(String name) {
6460 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006461 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006462 mAppWarnings.onPackageDataCleared(name);
6463 }
6464 }
6465
6466 @Override
6467 public void onPackageUninstalled(String name) {
6468 synchronized (mGlobalLock) {
6469 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006470 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006471 }
6472 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006473
6474 @Override
6475 public void onPackageAdded(String name, boolean replacing) {
6476 synchronized (mGlobalLock) {
6477 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6478 }
6479 }
6480
6481 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006482 public void onPackageReplaced(ApplicationInfo aInfo) {
6483 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006484 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006485 }
6486 }
6487
6488 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006489 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6490 synchronized (mGlobalLock) {
6491 return compatibilityInfoForPackageLocked(ai);
6492 }
6493 }
6494
Yunfan Chen75157d72018-07-27 14:47:21 +09006495 /**
6496 * Set the corresponding display information for the process global configuration. To be
6497 * called when we need to show IME on a different display.
6498 *
6499 * @param pid The process id associated with the IME window.
6500 * @param displayId The ID of the display showing the IME.
6501 */
6502 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006503 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006504 // Don't update process-level configuration for Multi-Client IME process since other
6505 // IMEs on other displays will also receive this configuration change due to IME
6506 // services use the same application config/context.
6507 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006508
Yunfan Chen75157d72018-07-27 14:47:21 +09006509 if (pid == MY_PID || pid < 0) {
6510 if (DEBUG_CONFIGURATION) {
6511 Slog.w(TAG,
6512 "Trying to update display configuration for system/invalid process.");
6513 }
6514 return;
6515 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006516 synchronized (mGlobalLock) {
6517 final ActivityDisplay activityDisplay =
6518 mRootActivityContainer.getActivityDisplay(displayId);
6519 if (activityDisplay == null) {
6520 // Call might come when display is not yet added or has been removed.
6521 if (DEBUG_CONFIGURATION) {
6522 Slog.w(TAG, "Trying to update display configuration for non-existing "
6523 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006524 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006525 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006526 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006527 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006528 if (process == null) {
6529 if (DEBUG_CONFIGURATION) {
6530 Slog.w(TAG, "Trying to update display configuration for invalid "
6531 + "process, pid=" + pid);
6532 }
6533 return;
6534 }
6535 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6536 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006537 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006538
6539 @Override
6540 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6541 int requestCode, int resultCode, Intent data) {
6542 synchronized (mGlobalLock) {
6543 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006544 if (r != null && r.getActivityStack() != null) {
6545 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6546 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006547 }
6548 }
6549 }
6550
6551 @Override
6552 public void clearPendingResultForActivity(IBinder activityToken,
6553 WeakReference<PendingIntentRecord> pir) {
6554 synchronized (mGlobalLock) {
6555 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6556 if (r != null && r.pendingResults != null) {
6557 r.pendingResults.remove(pir);
6558 }
6559 }
6560 }
6561
6562 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006563 public ActivityTokens getTopActivityForTask(int taskId) {
6564 synchronized (mGlobalLock) {
6565 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6566 if (taskRecord == null) {
6567 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6568 + " Requested task not found");
6569 return null;
6570 }
6571 final ActivityRecord activity = taskRecord.getTopActivity();
6572 if (activity == null) {
6573 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6574 + " Requested activity not found");
6575 return null;
6576 }
6577 if (!activity.attachedToProcess()) {
6578 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6579 + activity);
6580 return null;
6581 }
6582 return new ActivityTokens(activity.appToken, activity.assistToken,
6583 activity.app.getThread());
6584 }
6585 }
6586
6587 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006588 public IIntentSender getIntentSender(int type, String packageName,
6589 int callingUid, int userId, IBinder token, String resultWho,
6590 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6591 Bundle bOptions) {
6592 synchronized (mGlobalLock) {
6593 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6594 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6595 }
6596 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006597
6598 @Override
6599 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6600 synchronized (mGlobalLock) {
6601 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6602 if (r == null) {
6603 return null;
6604 }
6605 if (r.mServiceConnectionsHolder == null) {
6606 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6607 ActivityTaskManagerService.this, r);
6608 }
6609
6610 return r.mServiceConnectionsHolder;
6611 }
6612 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006613
6614 @Override
6615 public Intent getHomeIntent() {
6616 synchronized (mGlobalLock) {
6617 return ActivityTaskManagerService.this.getHomeIntent();
6618 }
6619 }
6620
6621 @Override
6622 public boolean startHomeActivity(int userId, String reason) {
6623 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006624 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006625 }
6626 }
6627
6628 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006629 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006630 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006631 synchronized (mGlobalLock) {
6632 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006633 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006634 }
Chilun8b1f1be2019-03-13 17:14:36 +08006635 }
6636
6637 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006638 public boolean startHomeOnAllDisplays(int userId, String reason) {
6639 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006640 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006641 }
6642 }
6643
Riddle Hsua0536432019-02-16 00:38:59 +08006644 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006645 @Override
6646 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006647 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006648 if (mFactoryTest == FACTORY_TEST_OFF) {
6649 return false;
6650 }
6651 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6652 && wpc.mName.equals(mTopComponent.getPackageName())) {
6653 return true;
6654 }
6655 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6656 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6657 }
6658 }
6659
6660 @Override
6661 public void updateTopComponentForFactoryTest() {
6662 synchronized (mGlobalLock) {
6663 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6664 return;
6665 }
6666 final ResolveInfo ri = mContext.getPackageManager()
6667 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6668 final CharSequence errorMsg;
6669 if (ri != null) {
6670 final ActivityInfo ai = ri.activityInfo;
6671 final ApplicationInfo app = ai.applicationInfo;
6672 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6673 mTopAction = Intent.ACTION_FACTORY_TEST;
6674 mTopData = null;
6675 mTopComponent = new ComponentName(app.packageName, ai.name);
6676 errorMsg = null;
6677 } else {
6678 errorMsg = mContext.getResources().getText(
6679 com.android.internal.R.string.factorytest_not_system);
6680 }
6681 } else {
6682 errorMsg = mContext.getResources().getText(
6683 com.android.internal.R.string.factorytest_no_action);
6684 }
6685 if (errorMsg == null) {
6686 return;
6687 }
6688
6689 mTopAction = null;
6690 mTopData = null;
6691 mTopComponent = null;
6692 mUiHandler.post(() -> {
6693 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6694 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006695 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006696 });
6697 }
6698 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699
Riddle Hsua0536432019-02-16 00:38:59 +08006700 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 @Override
6702 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6703 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006704 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006705 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006706 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707
6708 wpc.clearRecentTasks();
6709 wpc.clearActivities();
6710
6711 if (wpc.isInstrumenting()) {
6712 finishInstrumentationCallback.run();
6713 }
6714
Jorim Jaggid0752812018-10-16 16:07:20 +02006715 if (!restarting && hasVisibleActivities) {
6716 mWindowManager.deferSurfaceLayout();
6717 try {
6718 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6719 // If there was nothing to resume, and we are not already restarting
6720 // this process, but there is a visible activity that is hosted by the
6721 // process...then make sure all visible activities are running, taking
6722 // care of restarting this process.
6723 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6724 !PRESERVE_WINDOWS);
6725 }
6726 } finally {
6727 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006728 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 }
6730 }
6731 }
6732
6733 @Override
6734 public void closeSystemDialogs(String reason) {
6735 enforceNotIsolatedCaller("closeSystemDialogs");
6736
6737 final int pid = Binder.getCallingPid();
6738 final int uid = Binder.getCallingUid();
6739 final long origId = Binder.clearCallingIdentity();
6740 try {
6741 synchronized (mGlobalLock) {
6742 // Only allow this from foreground processes, so that background
6743 // applications can't abuse it to prevent system UI from being shown.
6744 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006745 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 if (!proc.isPerceptible()) {
6747 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6748 + " from background process " + proc);
6749 return;
6750 }
6751 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 mWindowManager.closeSystemDialogs(reason);
6753
Wale Ogunwaled32da472018-11-16 07:19:28 -08006754 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006756 // Call into AM outside the synchronized block.
6757 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 } finally {
6759 Binder.restoreCallingIdentity(origId);
6760 }
6761 }
6762
6763 @Override
6764 public void cleanupDisabledPackageComponents(
6765 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6766 synchronized (mGlobalLock) {
6767 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006768 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006769 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 mStackSupervisor.scheduleIdleLocked();
6772 }
6773
6774 // Clean-up disabled tasks
6775 getRecentTasks().cleanupDisabledPackageTasksLocked(
6776 packageName, disabledClasses, userId);
6777 }
6778 }
6779
6780 @Override
6781 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6782 int userId) {
6783 synchronized (mGlobalLock) {
6784
6785 boolean didSomething =
6786 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006787 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006788 null, doit, evenPersistent, userId);
6789 return didSomething;
6790 }
6791 }
6792
6793 @Override
6794 public void resumeTopActivities(boolean scheduleIdle) {
6795 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006796 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 if (scheduleIdle) {
6798 mStackSupervisor.scheduleIdleLocked();
6799 }
6800 }
6801 }
6802
Riddle Hsua0536432019-02-16 00:38:59 +08006803 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 @Override
6805 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006806 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6808 }
6809 }
6810
Riddle Hsua0536432019-02-16 00:38:59 +08006811 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 @Override
6813 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006814 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006815 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 }
6817 }
6818
6819 @Override
6820 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6821 try {
6822 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6823 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6824 }
6825 } catch (RemoteException ex) {
6826 throw new SecurityException("Fail to check is caller a privileged app", ex);
6827 }
6828
6829 synchronized (mGlobalLock) {
6830 final long ident = Binder.clearCallingIdentity();
6831 try {
6832 if (mAmInternal.shouldConfirmCredentials(userId)) {
6833 if (mKeyguardController.isKeyguardLocked()) {
6834 // Showing launcher to avoid user entering credential twice.
6835 startHomeActivity(currentUserId, "notifyLockedProfile");
6836 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006837 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 }
6839 } finally {
6840 Binder.restoreCallingIdentity(ident);
6841 }
6842 }
6843 }
6844
6845 @Override
6846 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6847 mAmInternal.enforceCallingPermission(
6848 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6849
6850 synchronized (mGlobalLock) {
6851 final long ident = Binder.clearCallingIdentity();
6852 try {
6853 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6854 FLAG_ACTIVITY_TASK_ON_HOME);
6855 ActivityOptions activityOptions = options != null
6856 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006857 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006858 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006859 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006860 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006861 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6863 UserHandle.CURRENT);
6864 } finally {
6865 Binder.restoreCallingIdentity(ident);
6866 }
6867 }
6868 }
6869
6870 @Override
6871 public void writeActivitiesToProto(ProtoOutputStream proto) {
6872 synchronized (mGlobalLock) {
6873 // The output proto of "activity --proto activities"
6874 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006875 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006876 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6877 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 }
6879 }
6880
6881 @Override
6882 public void saveANRState(String reason) {
6883 synchronized (mGlobalLock) {
6884 final StringWriter sw = new StringWriter();
6885 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6886 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6887 if (reason != null) {
6888 pw.println(" Reason: " + reason);
6889 }
6890 pw.println();
6891 getActivityStartController().dump(pw, " ", null);
6892 pw.println();
6893 pw.println("-------------------------------------------------------------------------------");
6894 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6895 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6896 "" /* header */);
6897 pw.println();
6898 pw.close();
6899
6900 mLastANRState = sw.toString();
6901 }
6902 }
6903
6904 @Override
6905 public void clearSavedANRState() {
6906 synchronized (mGlobalLock) {
6907 mLastANRState = null;
6908 }
6909 }
6910
6911 @Override
6912 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6913 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6914 synchronized (mGlobalLock) {
6915 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6916 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6917 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6918 dumpLastANRLocked(pw);
6919 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6920 dumpLastANRTracesLocked(pw);
6921 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6922 dumpActivityStarterLocked(pw, dumpPackage);
6923 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6924 dumpActivityContainersLocked(pw);
6925 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6926 if (getRecentTasks() != null) {
6927 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6928 }
6929 }
6930 }
6931 }
6932
6933 @Override
6934 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6935 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6936 int wakefulness) {
6937 synchronized (mGlobalLock) {
6938 if (mHomeProcess != null && (dumpPackage == null
6939 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6940 if (needSep) {
6941 pw.println();
6942 needSep = false;
6943 }
6944 pw.println(" mHomeProcess: " + mHomeProcess);
6945 }
6946 if (mPreviousProcess != null && (dumpPackage == null
6947 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6948 if (needSep) {
6949 pw.println();
6950 needSep = false;
6951 }
6952 pw.println(" mPreviousProcess: " + mPreviousProcess);
6953 }
6954 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6955 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6956 StringBuilder sb = new StringBuilder(128);
6957 sb.append(" mPreviousProcessVisibleTime: ");
6958 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6959 pw.println(sb);
6960 }
6961 if (mHeavyWeightProcess != null && (dumpPackage == null
6962 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6963 if (needSep) {
6964 pw.println();
6965 needSep = false;
6966 }
6967 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6968 }
6969 if (dumpPackage == null) {
6970 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006971 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006972 }
6973 if (dumpAll) {
6974 if (dumpPackage == null) {
6975 pw.println(" mConfigWillChange: "
6976 + getTopDisplayFocusedStack().mConfigWillChange);
6977 }
6978 if (mCompatModePackages.getPackages().size() > 0) {
6979 boolean printed = false;
6980 for (Map.Entry<String, Integer> entry
6981 : mCompatModePackages.getPackages().entrySet()) {
6982 String pkg = entry.getKey();
6983 int mode = entry.getValue();
6984 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6985 continue;
6986 }
6987 if (!printed) {
6988 pw.println(" mScreenCompatPackages:");
6989 printed = true;
6990 }
6991 pw.println(" " + pkg + ": " + mode);
6992 }
6993 }
6994 }
6995
6996 if (dumpPackage == null) {
6997 pw.println(" mWakefulness="
6998 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006999 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007000 if (mRunningVoice != null) {
7001 pw.println(" mRunningVoice=" + mRunningVoice);
7002 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7003 }
7004 pw.println(" mSleeping=" + mSleeping);
7005 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7006 pw.println(" mVrController=" + mVrController);
7007 }
7008 if (mCurAppTimeTracker != null) {
7009 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7010 }
7011 if (mAllowAppSwitchUids.size() > 0) {
7012 boolean printed = false;
7013 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7014 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7015 for (int j = 0; j < types.size(); j++) {
7016 if (dumpPackage == null ||
7017 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7018 if (needSep) {
7019 pw.println();
7020 needSep = false;
7021 }
7022 if (!printed) {
7023 pw.println(" mAllowAppSwitchUids:");
7024 printed = true;
7025 }
7026 pw.print(" User ");
7027 pw.print(mAllowAppSwitchUids.keyAt(i));
7028 pw.print(": Type ");
7029 pw.print(types.keyAt(j));
7030 pw.print(" = ");
7031 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7032 pw.println();
7033 }
7034 }
7035 }
7036 }
7037 if (dumpPackage == null) {
7038 if (mController != null) {
7039 pw.println(" mController=" + mController
7040 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7041 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007042 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7043 pw.println(" mLaunchingActivityWakeLock="
7044 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007045 }
7046
7047 return needSep;
7048 }
7049 }
7050
7051 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007052 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7053 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007054 synchronized (mGlobalLock) {
7055 if (dumpPackage == null) {
7056 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7057 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007058 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7059 if (mRunningVoice != null) {
7060 final long vrToken = proto.start(
7061 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7062 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7063 mRunningVoice.toString());
7064 mVoiceWakeLock.writeToProto(
7065 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7066 proto.end(vrToken);
7067 }
7068 mVrController.writeToProto(proto,
7069 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007070 if (mController != null) {
7071 final long token = proto.start(CONTROLLER);
7072 proto.write(CONTROLLER, mController.toString());
7073 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7074 proto.end(token);
7075 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007076 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7077 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7078 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 }
7080
7081 if (mHomeProcess != null && (dumpPackage == null
7082 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007083 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 }
7085
7086 if (mPreviousProcess != null && (dumpPackage == null
7087 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007088 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7090 }
7091
7092 if (mHeavyWeightProcess != null && (dumpPackage == null
7093 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007094 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007095 }
7096
7097 for (Map.Entry<String, Integer> entry
7098 : mCompatModePackages.getPackages().entrySet()) {
7099 String pkg = entry.getKey();
7100 int mode = entry.getValue();
7101 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7102 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7103 proto.write(PACKAGE, pkg);
7104 proto.write(MODE, mode);
7105 proto.end(compatToken);
7106 }
7107 }
7108
7109 if (mCurAppTimeTracker != null) {
7110 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7111 }
7112
7113 }
7114 }
7115
7116 @Override
7117 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7118 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7119 boolean dumpFocusedStackOnly) {
7120 synchronized (mGlobalLock) {
7121 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7122 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7123 }
7124 }
7125
7126 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007127 public void dumpForOom(PrintWriter pw) {
7128 synchronized (mGlobalLock) {
7129 pw.println(" mHomeProcess: " + mHomeProcess);
7130 pw.println(" mPreviousProcess: " + mPreviousProcess);
7131 if (mHeavyWeightProcess != null) {
7132 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7133 }
7134 }
7135 }
7136
7137 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007138 public boolean canGcNow() {
7139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007140 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 }
7142 }
7143
Riddle Hsua0536432019-02-16 00:38:59 +08007144 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 @Override
7146 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007147 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007148 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007149 return top != null ? top.app : null;
7150 }
7151 }
7152
Riddle Hsua0536432019-02-16 00:38:59 +08007153 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 @Override
7155 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007156 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007157 if (mRootActivityContainer != null) {
7158 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007159 }
7160 }
7161 }
7162
7163 @Override
7164 public void scheduleDestroyAllActivities(String reason) {
7165 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007166 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007167 }
7168 }
7169
7170 @Override
7171 public void removeUser(int userId) {
7172 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007173 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 }
7175 }
7176
7177 @Override
7178 public boolean switchUser(int userId, UserState userState) {
7179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007180 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 }
7182 }
7183
7184 @Override
7185 public void onHandleAppCrash(WindowProcessController wpc) {
7186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007187 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007190
7191 @Override
7192 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007194 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007195 }
7196 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007197
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 onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007201 mActiveUids.onUidActive(uid, procState);
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007207 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007213 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007214 }
7215
Riddle Hsua0536432019-02-16 00:38:59 +08007216 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007217 @Override
7218 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007219 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007220 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007221
7222 @Override
7223 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007224 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007225 mPendingTempWhitelist.put(uid, tag);
7226 }
7227 }
7228
7229 @Override
7230 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007231 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007232 mPendingTempWhitelist.remove(uid);
7233 }
7234 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007235
7236 @Override
7237 public boolean handleAppCrashInActivityController(String processName, int pid,
7238 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7239 Runnable killCrashingAppCallback) {
7240 synchronized (mGlobalLock) {
7241 if (mController == null) {
7242 return false;
7243 }
7244
7245 try {
7246 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7247 stackTrace)) {
7248 killCrashingAppCallback.run();
7249 return true;
7250 }
7251 } catch (RemoteException e) {
7252 mController = null;
7253 Watchdog.getInstance().setActivityController(null);
7254 }
7255 return false;
7256 }
7257 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007258
7259 @Override
7260 public void removeRecentTasksByPackageName(String packageName, int userId) {
7261 synchronized (mGlobalLock) {
7262 mRecentTasks.removeTasksByPackageName(packageName, userId);
7263 }
7264 }
7265
7266 @Override
7267 public void cleanupRecentTasksForUser(int userId) {
7268 synchronized (mGlobalLock) {
7269 mRecentTasks.cleanupLocked(userId);
7270 }
7271 }
7272
7273 @Override
7274 public void loadRecentTasksForUser(int userId) {
7275 synchronized (mGlobalLock) {
7276 mRecentTasks.loadUserRecentsLocked(userId);
7277 }
7278 }
7279
7280 @Override
7281 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7282 synchronized (mGlobalLock) {
7283 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7284 }
7285 }
7286
7287 @Override
7288 public void flushRecentTasks() {
7289 mRecentTasks.flush();
7290 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007291
7292 @Override
7293 public WindowProcessController getHomeProcess() {
7294 synchronized (mGlobalLock) {
7295 return mHomeProcess;
7296 }
7297 }
7298
7299 @Override
7300 public WindowProcessController getPreviousProcess() {
7301 synchronized (mGlobalLock) {
7302 return mPreviousProcess;
7303 }
7304 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007305
7306 @Override
7307 public void clearLockedTasks(String reason) {
7308 synchronized (mGlobalLock) {
7309 getLockTaskController().clearLockedTasks(reason);
7310 }
7311 }
7312
7313 @Override
7314 public void updateUserConfiguration() {
7315 synchronized (mGlobalLock) {
7316 final Configuration configuration = new Configuration(getGlobalConfiguration());
7317 final int currentUserId = mAmInternal.getCurrentUserId();
7318 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7319 configuration, currentUserId, Settings.System.canWrite(mContext));
7320 updateConfigurationLocked(configuration, null /* starting */,
7321 false /* initLocale */, false /* persistent */, currentUserId,
7322 false /* deferResume */);
7323 }
7324 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007325
7326 @Override
7327 public boolean canShowErrorDialogs() {
7328 synchronized (mGlobalLock) {
7329 return mShowDialogs && !mSleeping && !mShuttingDown
7330 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7331 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7332 mAmInternal.getCurrentUserId())
7333 && !(UserManager.isDeviceInDemoMode(mContext)
7334 && mAmInternal.getCurrentUser().isDemo());
7335 }
7336 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007337
7338 @Override
7339 public void setProfileApp(String profileApp) {
7340 synchronized (mGlobalLock) {
7341 mProfileApp = profileApp;
7342 }
7343 }
7344
7345 @Override
7346 public void setProfileProc(WindowProcessController wpc) {
7347 synchronized (mGlobalLock) {
7348 mProfileProc = wpc;
7349 }
7350 }
7351
7352 @Override
7353 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7354 synchronized (mGlobalLock) {
7355 mProfilerInfo = profilerInfo;
7356 }
7357 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007358
7359 @Override
7360 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7361 synchronized (mGlobalLock) {
7362 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7363 }
7364 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007365
7366 @Override
7367 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7368 synchronized (mGlobalLock) {
7369 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7370 }
7371 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007372
7373 @Override
7374 public boolean isUidForeground(int uid) {
7375 synchronized (mGlobalLock) {
7376 return ActivityTaskManagerService.this.isUidForeground(uid);
7377 }
7378 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007379
7380 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007381 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007382 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007383 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007384 }
7385 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007386
7387 @Override
7388 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007389 // Translate package names into UIDs
7390 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007391 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007392 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7393 if (uid >= 0) {
7394 result.add(uid);
7395 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007396 }
7397 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007398 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007399 }
7400 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007401 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007402}