blob: e885996cfbbe57d77750bbc4bb798a8772409ec6 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800227import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100248import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800277import java.lang.annotation.ElementType;
278import java.lang.annotation.Retention;
279import java.lang.annotation.RetentionPolicy;
280import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700282import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700284import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400286import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700289import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Map;
291import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292
293/**
294 * System service for managing activities and their containers (task, stacks, displays,... ).
295 *
296 * {@hide}
297 */
298public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700299 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700301 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
302 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
303 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
304 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
305 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700306 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700307
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700309 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312
Wale Ogunwale98875612018-10-12 07:53:02 -0700313 /** Used to indicate that an app transition should be animated. */
314 static final boolean ANIMATE = true;
315
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700316 /** Hardware-reported OpenGLES version. */
317 final int GL_ES_VERSION;
318
Wale Ogunwale31913b52018-10-13 08:29:31 -0700319 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
320 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
321 public static final String DUMP_LASTANR_CMD = "lastanr" ;
322 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
323 public static final String DUMP_STARTER_CMD = "starter" ;
324 public static final String DUMP_CONTAINERS_CMD = "containers" ;
325 public static final String DUMP_RECENTS_CMD = "recents" ;
326 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
327
Wale Ogunwale64258362018-10-16 15:13:37 -0700328 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
329 public static final int RELAUNCH_REASON_NONE = 0;
330 /** This activity is being relaunched due to windowing mode change. */
331 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
332 /** This activity is being relaunched due to a free-resize operation. */
333 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
334
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700335 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700336
Wale Ogunwalef6733932018-06-27 05:14:34 -0700337 /**
338 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
339 * change at runtime. Use mContext for non-UI purposes.
340 */
341 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700342 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700343 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700345 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700346 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700347 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800348 @VisibleForTesting
349 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 PowerManagerInternal mPowerManagerInternal;
351 private UsageStatsManagerInternal mUsageStatsInternal;
352
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700353 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 IntentFirewall mIntentFirewall;
355
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700356 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800357 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800358 /**
359 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
360 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
361 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
362 *
363 * @see WindowManagerThreadPriorityBooster
364 */
365 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700366 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800367 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700368 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700369 private UserManagerService mUserManager;
370 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700371 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800372 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700373 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700374 /** All processes currently running that might have a window organized by name. */
375 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700376 /** All processes we currently have running mapped by pid */
377 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700378 /** This is the process holding what we currently consider to be the "home" activity. */
379 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700380 /** The currently running heavy-weight process, if any. */
381 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700382 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /**
384 * This is the process holding the activity the user last visited that is in a different process
385 * from the one they are currently in.
386 */
387 WindowProcessController mPreviousProcess;
388 /** The time at which the previous process was last visible. */
389 long mPreviousProcessVisibleTime;
390
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700391 /** List of intents that were used to start the most recent tasks. */
392 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700393 /** State of external calls telling us if the device is awake or asleep. */
394 private boolean mKeyguardShown = false;
395
396 // Wrapper around VoiceInteractionServiceManager
397 private AssistUtils mAssistUtils;
398
399 // VoiceInteraction session ID that changes for each new request except when
400 // being called for multi-window assist in a single session.
401 private int mViSessionId = 1000;
402
403 // How long to wait in getAssistContextExtras for the activity and foreground services
404 // to respond with the result.
405 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
406
407 // How long top wait when going through the modern assist (which doesn't need to block
408 // on getting this result before starting to launch its UI).
409 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
410
411 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
412 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
413
Alison Cichowlas3e340502018-08-07 17:15:01 -0400414 // Permission tokens are used to temporarily granted a trusted app the ability to call
415 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
416 // showing any appropriate error messages to the user.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
418 10 * MINUTE_IN_MILLIS;
419
420 // How long before the service actually expires a token. This is slightly longer than
421 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
422 // expiration exception.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
424 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
425
426 // How long the service will remember expired tokens, for the purpose of providing error
427 // messaging when a client uses an expired token.
428 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
429 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
430
Marvin Ramin830d4e32019-03-12 13:16:58 +0100431 // How long to whitelist the Services for when requested.
432 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
433
Alison Cichowlas3e340502018-08-07 17:15:01 -0400434 // Activity tokens of system activities that are delegating their call to
435 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
436 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
437
438 // Permission tokens that have expired, but we remember for error reporting.
439 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700441 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
442
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700443 // Keeps track of the active voice interaction service component, notified from
444 // VoiceInteractionManagerService
445 ComponentName mActiveVoiceInteractionServiceComponent;
446
Michal Karpinskida34cd42019-04-02 19:46:52 +0100447 // A map userId and all its companion app uids
448 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000449
Wale Ogunwalee2172292018-10-25 10:11:10 -0700450 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 KeyguardController mKeyguardController;
452 private final ClientLifecycleManager mLifecycleManager;
453 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700454 /** The controller for all operations related to locktask. */
455 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700456 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700458 boolean mSuppressResizeConfigChanges;
459
460 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
461 new UpdateConfigurationResult();
462
463 static final class UpdateConfigurationResult {
464 // Configuration changes that were updated.
465 int changes;
466 // If the activity was relaunched to match the new configuration.
467 boolean activityRelaunched;
468
469 void reset() {
470 changes = 0;
471 activityRelaunched = false;
472 }
473 }
474
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700475 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700476 private int mConfigurationSeq;
477 // To cache the list of supported system locales
478 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479
480 /**
481 * Temp object used when global and/or display override configuration is updated. It is also
482 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
483 * anyone...
484 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private Configuration mTempConfig = new Configuration();
486
Wale Ogunwalef6733932018-06-27 05:14:34 -0700487 /** Temporary to avoid allocations. */
488 final StringBuilder mStringBuilder = new StringBuilder(256);
489
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 // Amount of time after a call to stopAppSwitches() during which we will
491 // prevent further untrusted switches from happening.
492 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
493
494 /**
495 * The time at which we will allow normal application switches again,
496 * after a call to {@link #stopAppSwitches()}.
497 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700498 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 /**
500 * This is set to true after the first switch after mAppSwitchesAllowedTime
501 * is set; any switches after that will clear the time.
502 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700503 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504
505 IActivityController mController = null;
506 boolean mControllerIsAMonkey = false;
507
Wale Ogunwale214f3482018-10-04 11:00:47 -0700508 final int mFactoryTest;
509
510 /** Used to control how we initialize the service. */
511 ComponentName mTopComponent;
512 String mTopAction = Intent.ACTION_MAIN;
513 String mTopData;
514
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800515 /** Profiling app information. */
516 String mProfileApp = null;
517 WindowProcessController mProfileProc = null;
518 ProfilerInfo mProfilerInfo = null;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700521 * Dump of the activity state at the time of the last ANR. Cleared after
522 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
523 */
524 String mLastANRState;
525
526 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527 * Used to retain an update lock when the foreground activity is in
528 * immersive mode.
529 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700530 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700531
532 /**
533 * Packages that are being allowed to perform unrestricted app switches. Mapping is
534 * User -> Type -> uid.
535 */
536 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
537
538 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700539 private int mThumbnailWidth;
540 private int mThumbnailHeight;
541 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542
543 /**
544 * Flag that indicates if multi-window is enabled.
545 *
546 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
547 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
548 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
549 * At least one of the forms of multi-window must be enabled in order for this flag to be
550 * initialized to 'true'.
551 *
552 * @see #mSupportsSplitScreenMultiWindow
553 * @see #mSupportsFreeformWindowManagement
554 * @see #mSupportsPictureInPicture
555 * @see #mSupportsMultiDisplay
556 */
557 boolean mSupportsMultiWindow;
558 boolean mSupportsSplitScreenMultiWindow;
559 boolean mSupportsFreeformWindowManagement;
560 boolean mSupportsPictureInPicture;
561 boolean mSupportsMultiDisplay;
562 boolean mForceResizableActivities;
563
564 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
565
566 // VR Vr2d Display Id.
567 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700568
Wale Ogunwalef6733932018-06-27 05:14:34 -0700569 /**
570 * Set while we are wanting to sleep, to prevent any
571 * activities from being started/resumed.
572 *
573 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
574 *
575 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
576 * while in the sleep state until there is a pending transition out of sleep, in which case
577 * mSleeping is set to false, and remains false while awake.
578 *
579 * Whether mSleeping can quickly toggled between true/false without the device actually
580 * display changing states is undefined.
581 */
582 private boolean mSleeping = false;
583
584 /**
585 * The process state used for processes that are running the top activities.
586 * This changes between TOP and TOP_SLEEPING to following mSleeping.
587 */
588 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
589
590 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
591 // automatically. Important for devices without direct input devices.
592 private boolean mShowDialogs = true;
593
594 /** Set if we are shutting down the system, similar to sleeping. */
595 boolean mShuttingDown = false;
596
597 /**
598 * We want to hold a wake lock while running a voice interaction session, since
599 * this may happen with the screen off and we need to keep the CPU running to
600 * be able to continue to interact with the user.
601 */
602 PowerManager.WakeLock mVoiceWakeLock;
603
604 /**
605 * Set while we are running a voice interaction. This overrides sleeping while it is active.
606 */
607 IVoiceInteractionSession mRunningVoice;
608
609 /**
610 * The last resumed activity. This is identical to the current resumed activity most
611 * of the time but could be different when we're pausing one activity before we resume
612 * another activity.
613 */
614 ActivityRecord mLastResumedActivity;
615
616 /**
617 * The activity that is currently being traced as the active resumed activity.
618 *
619 * @see #updateResumedAppTrace
620 */
621 private @Nullable ActivityRecord mTracedResumedActivity;
622
623 /** If non-null, we are tracking the time the user spends in the currently focused app. */
624 AppTimeTracker mCurAppTimeTracker;
625
Wale Ogunwale008163e2018-07-23 23:11:08 -0700626 private AppWarnings mAppWarnings;
627
Wale Ogunwale53783742018-09-16 10:21:51 -0700628 /**
629 * Packages that the user has asked to have run in screen size
630 * compatibility mode instead of filling the screen.
631 */
632 CompatModePackages mCompatModePackages;
633
Wale Ogunwalef6733932018-06-27 05:14:34 -0700634 private FontScaleSettingObserver mFontScaleSettingObserver;
635
Ricky Wai96f5c352019-04-10 18:40:17 +0100636 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000637
Wale Ogunwalef6733932018-06-27 05:14:34 -0700638 private final class FontScaleSettingObserver extends ContentObserver {
639 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
640 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
641
642 public FontScaleSettingObserver() {
643 super(mH);
644 final ContentResolver resolver = mContext.getContentResolver();
645 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
646 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
647 UserHandle.USER_ALL);
648 }
649
650 @Override
651 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
652 if (mFontScaleUri.equals(uri)) {
653 updateFontScaleIfNeeded(userId);
654 } else if (mHideErrorDialogsUri.equals(uri)) {
655 synchronized (mGlobalLock) {
656 updateShouldShowDialogsLocked(getGlobalConfiguration());
657 }
658 }
659 }
660 }
661
Riddle Hsua0536432019-02-16 00:38:59 +0800662 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
663 @Target(ElementType.METHOD)
664 @Retention(RetentionPolicy.SOURCE)
665 @interface HotPath {
666 int NONE = 0;
667 int OOM_ADJUSTMENT = 1;
668 int LRU_UPDATE = 2;
669 int PROCESS_CHANGE = 3;
670 int caller() default NONE;
671 }
672
Charles Chen8d98dd22018-12-26 17:36:54 +0800673 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
674 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700675 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700676 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700677 mSystemThread = ActivityThread.currentActivityThread();
678 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700679 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800680 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700681 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700682 }
683
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700684 public void onSystemReady() {
685 synchronized (mGlobalLock) {
686 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
687 PackageManager.FEATURE_CANT_SAVE_STATE);
688 mAssistUtils = new AssistUtils(mContext);
689 mVrController.onSystemReady();
690 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700691 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700693 }
694
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700695 public void onInitPowerManagement() {
696 synchronized (mGlobalLock) {
697 mStackSupervisor.initPowerManagement();
698 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
699 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
700 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
701 mVoiceWakeLock.setReferenceCounted(false);
702 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700703 }
704
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700705 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700706 mFontScaleSettingObserver = new FontScaleSettingObserver();
707 }
708
Wale Ogunwale59507092018-10-29 09:00:30 -0700709 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700710 final boolean freeformWindowManagement =
711 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
712 || Settings.Global.getInt(
713 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
714
715 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
716 final boolean supportsPictureInPicture = supportsMultiWindow &&
717 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
718 final boolean supportsSplitScreenMultiWindow =
719 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
720 final boolean supportsMultiDisplay = mContext.getPackageManager()
721 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
723 final boolean forceResizable = Settings.Global.getInt(
724 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700725 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700726
727 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900728 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700729
730 final Configuration configuration = new Configuration();
731 Settings.System.getConfiguration(resolver, configuration);
732 if (forceRtl) {
733 // This will take care of setting the correct layout direction flags
734 configuration.setLayoutDirection(configuration.locale);
735 }
736
737 synchronized (mGlobalLock) {
738 mForceResizableActivities = forceResizable;
739 final boolean multiWindowFormEnabled = freeformWindowManagement
740 || supportsSplitScreenMultiWindow
741 || supportsPictureInPicture
742 || supportsMultiDisplay;
743 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
744 mSupportsMultiWindow = true;
745 mSupportsFreeformWindowManagement = freeformWindowManagement;
746 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
747 mSupportsPictureInPicture = supportsPictureInPicture;
748 mSupportsMultiDisplay = supportsMultiDisplay;
749 } else {
750 mSupportsMultiWindow = false;
751 mSupportsFreeformWindowManagement = false;
752 mSupportsSplitScreenMultiWindow = false;
753 mSupportsPictureInPicture = false;
754 mSupportsMultiDisplay = false;
755 }
756 mWindowManager.setForceResizableTasks(mForceResizableActivities);
757 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700758 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
759 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700760 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 // This happens before any activities are started, so we can change global configuration
762 // in-place.
763 updateConfigurationLocked(configuration, null, true);
764 final Configuration globalConfig = getGlobalConfiguration();
765 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
766
767 // Load resources only after the current configuration has been set.
768 final Resources res = mContext.getResources();
769 mThumbnailWidth = res.getDimensionPixelSize(
770 com.android.internal.R.dimen.thumbnail_width);
771 mThumbnailHeight = res.getDimensionPixelSize(
772 com.android.internal.R.dimen.thumbnail_height);
773
774 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
775 mFullscreenThumbnailScale = (float) res
776 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
777 (float) globalConfig.screenWidthDp;
778 } else {
779 mFullscreenThumbnailScale = res.getFraction(
780 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
781 }
782 }
783 }
784
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800785 public WindowManagerGlobalLock getGlobalLock() {
786 return mGlobalLock;
787 }
788
Yunfan Chen585f2932019-01-29 16:04:45 +0900789 /** For test purpose only. */
790 @VisibleForTesting
791 public ActivityTaskManagerInternal getAtmInternal() {
792 return mInternal;
793 }
794
Riddle Hsud93a6c42018-11-29 21:50:06 +0800795 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
796 Looper looper) {
797 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700799 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700800 final File systemDir = SystemServiceManager.ensureSystemDir();
801 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
802 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700803 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804
805 mTempConfig.setToDefaults();
806 mTempConfig.setLocales(LocaleList.getDefault());
807 mConfigurationSeq = mTempConfig.seq = 1;
808 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800809 mRootActivityContainer = new RootActivityContainer(this);
810 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700811
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700812 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700814 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700815 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700816 mRecentTasks = createRecentTasks();
817 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700818 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700819 mKeyguardController = mStackSupervisor.getKeyguardController();
820 }
821
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700822 public void onActivityManagerInternalAdded() {
823 synchronized (mGlobalLock) {
824 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
825 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
826 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700827 }
828
Yunfan Chen75157d72018-07-27 14:47:21 +0900829 int increaseConfigurationSeqLocked() {
830 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
831 return mConfigurationSeq;
832 }
833
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700834 protected ActivityStackSupervisor createStackSupervisor() {
835 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
836 supervisor.initialize();
837 return supervisor;
838 }
839
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700840 public void setWindowManager(WindowManagerService wm) {
841 synchronized (mGlobalLock) {
842 mWindowManager = wm;
843 mLockTaskController.setWindowManager(wm);
844 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800845 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700846 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700847 }
848
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
850 synchronized (mGlobalLock) {
851 mUsageStatsInternal = usageStatsManager;
852 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700853 }
854
Wale Ogunwalef6733932018-06-27 05:14:34 -0700855 UserManagerService getUserManager() {
856 if (mUserManager == null) {
857 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
858 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
859 }
860 return mUserManager;
861 }
862
863 AppOpsService getAppOpsService() {
864 if (mAppOpsService == null) {
865 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
866 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
867 }
868 return mAppOpsService;
869 }
870
871 boolean hasUserRestriction(String restriction, int userId) {
872 return getUserManager().hasUserRestriction(restriction, userId);
873 }
874
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700875 protected RecentTasks createRecentTasks() {
876 return new RecentTasks(this, mStackSupervisor);
877 }
878
879 RecentTasks getRecentTasks() {
880 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700881 }
882
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700883 ClientLifecycleManager getLifecycleManager() {
884 return mLifecycleManager;
885 }
886
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700887 ActivityStartController getActivityStartController() {
888 return mActivityStartController;
889 }
890
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700891 TaskChangeNotificationController getTaskChangeNotificationController() {
892 return mTaskChangeNotificationController;
893 }
894
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700895 LockTaskController getLockTaskController() {
896 return mLockTaskController;
897 }
898
Yunfan Chen75157d72018-07-27 14:47:21 +0900899 /**
900 * Return the global configuration used by the process corresponding to the input pid. This is
901 * usually the global configuration with some overrides specific to that process.
902 */
903 Configuration getGlobalConfigurationForCallingPid() {
904 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800905 return getGlobalConfigurationForPid(pid);
906 }
907
908 /**
909 * Return the global configuration used by the process corresponding to the given pid.
910 */
911 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 if (pid == MY_PID || pid < 0) {
913 return getGlobalConfiguration();
914 }
915 synchronized (mGlobalLock) {
916 final WindowProcessController app = mPidMap.get(pid);
917 return app != null ? app.getConfiguration() : getGlobalConfiguration();
918 }
919 }
920
921 /**
922 * Return the device configuration info used by the process corresponding to the input pid.
923 * The value is consistent with the global configuration for the process.
924 */
925 @Override
926 public ConfigurationInfo getDeviceConfigurationInfo() {
927 ConfigurationInfo config = new ConfigurationInfo();
928 synchronized (mGlobalLock) {
929 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
930 config.reqTouchScreen = globalConfig.touchscreen;
931 config.reqKeyboardType = globalConfig.keyboard;
932 config.reqNavigation = globalConfig.navigation;
933 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
934 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
935 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
936 }
937 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
938 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
939 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
940 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700941 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 }
943 return config;
944 }
945
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700946 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700947 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700948 }
949
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700950 public static final class Lifecycle extends SystemService {
951 private final ActivityTaskManagerService mService;
952
953 public Lifecycle(Context context) {
954 super(context);
955 mService = new ActivityTaskManagerService(context);
956 }
957
958 @Override
959 public void onStart() {
960 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700962 }
963
Garfield Tan891146c2018-10-09 12:14:00 -0700964 @Override
965 public void onUnlockUser(int userId) {
966 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800967 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700968 }
969 }
970
971 @Override
972 public void onCleanupUser(int userId) {
973 synchronized (mService.getGlobalLock()) {
974 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
975 }
976 }
977
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700978 public ActivityTaskManagerService getService() {
979 return mService;
980 }
981 }
982
983 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700984 public final int startActivity(IApplicationThread caller, String callingPackage,
985 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
986 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
987 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
988 resultWho, requestCode, startFlags, profilerInfo, bOptions,
989 UserHandle.getCallingUserId());
990 }
991
992 @Override
993 public final int startActivities(IApplicationThread caller, String callingPackage,
994 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
995 int userId) {
996 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700997 enforceNotIsolatedCaller(reason);
998 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001000 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1001 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1002 reason, null /* originatingPendingIntent */,
1003 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 }
1005
1006 @Override
1007 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1008 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1009 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1010 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1011 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1012 true /*validateIncomingUser*/);
1013 }
1014
1015 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1016 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1017 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1018 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001019 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001021 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1023
1024 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001025 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 .setCaller(caller)
1027 .setCallingPackage(callingPackage)
1028 .setResolvedType(resolvedType)
1029 .setResultTo(resultTo)
1030 .setResultWho(resultWho)
1031 .setRequestCode(requestCode)
1032 .setStartFlags(startFlags)
1033 .setProfilerInfo(profilerInfo)
1034 .setActivityOptions(bOptions)
1035 .setMayWait(userId)
1036 .execute();
1037
1038 }
1039
1040 @Override
1041 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1042 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1044 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // Refuse possible leaked file descriptors
1046 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1047 throw new IllegalArgumentException("File descriptors passed in Intent");
1048 }
1049
1050 if (!(target instanceof PendingIntentRecord)) {
1051 throw new IllegalArgumentException("Bad PendingIntent object");
1052 }
1053
1054 PendingIntentRecord pir = (PendingIntentRecord)target;
1055
1056 synchronized (mGlobalLock) {
1057 // If this is coming from the currently resumed activity, it is
1058 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001059 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 if (stack.mResumedActivity != null &&
1061 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001062 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 }
1064 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001065 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 }
1068
1069 @Override
1070 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1071 Bundle bOptions) {
1072 // Refuse possible leaked file descriptors
1073 if (intent != null && intent.hasFileDescriptors()) {
1074 throw new IllegalArgumentException("File descriptors passed in Intent");
1075 }
1076 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1077
1078 synchronized (mGlobalLock) {
1079 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1080 if (r == null) {
1081 SafeActivityOptions.abort(options);
1082 return false;
1083 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001084 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 // The caller is not running... d'oh!
1086 SafeActivityOptions.abort(options);
1087 return false;
1088 }
1089 intent = new Intent(intent);
1090 // The caller is not allowed to change the data.
1091 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1092 // And we are resetting to find the next component...
1093 intent.setComponent(null);
1094
1095 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1096
1097 ActivityInfo aInfo = null;
1098 try {
1099 List<ResolveInfo> resolves =
1100 AppGlobals.getPackageManager().queryIntentActivities(
1101 intent, r.resolvedType,
1102 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1103 UserHandle.getCallingUserId()).getList();
1104
1105 // Look for the original activity in the list...
1106 final int N = resolves != null ? resolves.size() : 0;
1107 for (int i=0; i<N; i++) {
1108 ResolveInfo rInfo = resolves.get(i);
1109 if (rInfo.activityInfo.packageName.equals(r.packageName)
1110 && rInfo.activityInfo.name.equals(r.info.name)) {
1111 // We found the current one... the next matching is
1112 // after it.
1113 i++;
1114 if (i<N) {
1115 aInfo = resolves.get(i).activityInfo;
1116 }
1117 if (debug) {
1118 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1119 + "/" + r.info.name);
1120 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1121 ? "null" : aInfo.packageName + "/" + aInfo.name));
1122 }
1123 break;
1124 }
1125 }
1126 } catch (RemoteException e) {
1127 }
1128
1129 if (aInfo == null) {
1130 // Nobody who is next!
1131 SafeActivityOptions.abort(options);
1132 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1133 return false;
1134 }
1135
1136 intent.setComponent(new ComponentName(
1137 aInfo.applicationInfo.packageName, aInfo.name));
1138 intent.setFlags(intent.getFlags()&~(
1139 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1140 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1141 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1142 FLAG_ACTIVITY_NEW_TASK));
1143
1144 // Okay now we need to start the new activity, replacing the currently running activity.
1145 // This is a little tricky because we want to start the new one as if the current one is
1146 // finished, but not finish the current one first so that there is no flicker.
1147 // And thus...
1148 final boolean wasFinishing = r.finishing;
1149 r.finishing = true;
1150
1151 // Propagate reply information over to the new activity.
1152 final ActivityRecord resultTo = r.resultTo;
1153 final String resultWho = r.resultWho;
1154 final int requestCode = r.requestCode;
1155 r.resultTo = null;
1156 if (resultTo != null) {
1157 resultTo.removeResultsLocked(r, resultWho, requestCode);
1158 }
1159
1160 final long origId = Binder.clearCallingIdentity();
1161 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001162 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001163 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001164 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001165 .setResolvedType(r.resolvedType)
1166 .setActivityInfo(aInfo)
1167 .setResultTo(resultTo != null ? resultTo.appToken : null)
1168 .setResultWho(resultWho)
1169 .setRequestCode(requestCode)
1170 .setCallingPid(-1)
1171 .setCallingUid(r.launchedFromUid)
1172 .setCallingPackage(r.launchedFromPackage)
1173 .setRealCallingPid(-1)
1174 .setRealCallingUid(r.launchedFromUid)
1175 .setActivityOptions(options)
1176 .execute();
1177 Binder.restoreCallingIdentity(origId);
1178
1179 r.finishing = wasFinishing;
1180 if (res != ActivityManager.START_SUCCESS) {
1181 return false;
1182 }
1183 return true;
1184 }
1185 }
1186
1187 @Override
1188 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1189 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1190 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1191 final WaitResult res = new WaitResult();
1192 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001193 enforceNotIsolatedCaller("startActivityAndWait");
1194 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1195 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001196 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001197 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001198 .setCaller(caller)
1199 .setCallingPackage(callingPackage)
1200 .setResolvedType(resolvedType)
1201 .setResultTo(resultTo)
1202 .setResultWho(resultWho)
1203 .setRequestCode(requestCode)
1204 .setStartFlags(startFlags)
1205 .setActivityOptions(bOptions)
1206 .setMayWait(userId)
1207 .setProfilerInfo(profilerInfo)
1208 .setWaitResult(res)
1209 .execute();
1210 }
1211 return res;
1212 }
1213
1214 @Override
1215 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1216 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1217 int startFlags, Configuration config, Bundle bOptions, int userId) {
1218 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001219 enforceNotIsolatedCaller("startActivityWithConfig");
1220 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1221 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001223 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 .setCaller(caller)
1225 .setCallingPackage(callingPackage)
1226 .setResolvedType(resolvedType)
1227 .setResultTo(resultTo)
1228 .setResultWho(resultWho)
1229 .setRequestCode(requestCode)
1230 .setStartFlags(startFlags)
1231 .setGlobalConfiguration(config)
1232 .setActivityOptions(bOptions)
1233 .setMayWait(userId)
1234 .execute();
1235 }
1236 }
1237
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238
1239 @Override
1240 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1241 int callingUid = Binder.getCallingUid();
1242 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1243 throw new SecurityException("Only the system process can request a permission token, "
1244 + "received request from uid: " + callingUid);
1245 }
1246 IBinder permissionToken = new Binder();
1247 synchronized (mGlobalLock) {
1248 mStartActivitySources.put(permissionToken, delegatorToken);
1249 }
1250
1251 Message expireMsg = PooledLambda.obtainMessage(
1252 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1253 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1254
1255 Message forgetMsg = PooledLambda.obtainMessage(
1256 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1257 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1258
1259 return permissionToken;
1260 }
1261
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001262 @Override
1263 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1264 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001265 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1266 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001267 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268 // permission grants) as any app that may launch one of your own activities. So we only
1269 // allow this in two cases:
1270 // 1) The caller is an activity that is part of the core framework, and then only when it
1271 // is running as the system.
1272 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1273 // can only be requested by a system activity, which may then delegate this call to
1274 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 final ActivityRecord sourceRecord;
1276 final int targetUid;
1277 final String targetPackage;
1278 final boolean isResolver;
1279 synchronized (mGlobalLock) {
1280 if (resultTo == null) {
1281 throw new SecurityException("Must be called from an activity");
1282 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 final IBinder sourceToken;
1284 if (permissionToken != null) {
1285 // To even attempt to use a permissionToken, an app must also have this signature
1286 // permission.
1287 mAmInternal.enforceCallingPermission(
1288 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1289 "startActivityAsCaller");
1290 // If called with a permissionToken, we want the sourceRecord from the delegator
1291 // activity that requested this token.
1292 sourceToken = mStartActivitySources.remove(permissionToken);
1293 if (sourceToken == null) {
1294 // Invalid permissionToken, check if it recently expired.
1295 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1296 throw new SecurityException("Called with expired permission token: "
1297 + permissionToken);
1298 } else {
1299 throw new SecurityException("Called with invalid permission token: "
1300 + permissionToken);
1301 }
1302 }
1303 } else {
1304 // This method was called directly by the source.
1305 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307
Wale Ogunwaled32da472018-11-16 07:19:28 -08001308 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001309 if (sourceRecord == null) {
1310 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 }
1312 if (sourceRecord.app == null) {
1313 throw new SecurityException("Called without a process attached to activity");
1314 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001315
1316 // Whether called directly or from a delegate, the source activity must be from the
1317 // android package.
1318 if (!sourceRecord.info.packageName.equals("android")) {
1319 throw new SecurityException("Must be called from an activity that is "
1320 + "declared in the android package");
1321 }
1322
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001323 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 // This is still okay, as long as this activity is running under the
1325 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001326 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001328 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 + " must be system uid or original calling uid "
1330 + sourceRecord.launchedFromUid);
1331 }
1332 }
1333 if (ignoreTargetSecurity) {
1334 if (intent.getComponent() == null) {
1335 throw new SecurityException(
1336 "Component must be specified with ignoreTargetSecurity");
1337 }
1338 if (intent.getSelector() != null) {
1339 throw new SecurityException(
1340 "Selector not allowed with ignoreTargetSecurity");
1341 }
1342 }
1343 targetUid = sourceRecord.launchedFromUid;
1344 targetPackage = sourceRecord.launchedFromPackage;
1345 isResolver = sourceRecord.isResolverOrChildActivity();
1346 }
1347
1348 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001349 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 }
1351
1352 // TODO: Switch to user app stacks here.
1353 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001354 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001355 .setCallingUid(targetUid)
1356 .setCallingPackage(targetPackage)
1357 .setResolvedType(resolvedType)
1358 .setResultTo(resultTo)
1359 .setResultWho(resultWho)
1360 .setRequestCode(requestCode)
1361 .setStartFlags(startFlags)
1362 .setActivityOptions(bOptions)
1363 .setMayWait(userId)
1364 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1365 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1366 .execute();
1367 } catch (SecurityException e) {
1368 // XXX need to figure out how to propagate to original app.
1369 // A SecurityException here is generally actually a fault of the original
1370 // calling activity (such as a fairly granting permissions), so propagate it
1371 // back to them.
1372 /*
1373 StringBuilder msg = new StringBuilder();
1374 msg.append("While launching");
1375 msg.append(intent.toString());
1376 msg.append(": ");
1377 msg.append(e.getMessage());
1378 */
1379 throw e;
1380 }
1381 }
1382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001383 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1384 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1385 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1386 }
1387
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388 @Override
1389 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1390 Intent intent, String resolvedType, IVoiceInteractionSession session,
1391 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1392 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001393 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 if (session == null || interactor == null) {
1395 throw new NullPointerException("null session or interactor");
1396 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001397 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001398 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001399 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .setCallingUid(callingUid)
1401 .setCallingPackage(callingPackage)
1402 .setResolvedType(resolvedType)
1403 .setVoiceSession(session)
1404 .setVoiceInteractor(interactor)
1405 .setStartFlags(startFlags)
1406 .setProfilerInfo(profilerInfo)
1407 .setActivityOptions(bOptions)
1408 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001409 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 .execute();
1411 }
1412
1413 @Override
1414 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1415 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1417 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001419 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 .setCallingUid(callingUid)
1421 .setCallingPackage(callingPackage)
1422 .setResolvedType(resolvedType)
1423 .setActivityOptions(bOptions)
1424 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001425 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .execute();
1427 }
1428
1429 @Override
1430 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1431 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 final int callingPid = Binder.getCallingPid();
1434 final long origId = Binder.clearCallingIdentity();
1435 try {
1436 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001437 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1438 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439
1440 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001441 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1442 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1444 recentsUid, assistDataReceiver);
1445 }
1446 } finally {
1447 Binder.restoreCallingIdentity(origId);
1448 }
1449 }
1450
1451 @Override
1452 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 "startActivityFromRecents()");
1455
1456 final int callingPid = Binder.getCallingPid();
1457 final int callingUid = Binder.getCallingUid();
1458 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1459 final long origId = Binder.clearCallingIdentity();
1460 try {
1461 synchronized (mGlobalLock) {
1462 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1463 safeOptions);
1464 }
1465 } finally {
1466 Binder.restoreCallingIdentity(origId);
1467 }
1468 }
1469
1470 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001471 * Public API to check if the client is allowed to start an activity on specified display.
1472 *
1473 * If the target display is private or virtual, some restrictions will apply.
1474 *
1475 * @param displayId Target display id.
1476 * @param intent Intent used to launch the activity.
1477 * @param resolvedType The MIME type of the intent.
1478 * @param userId The id of the user for whom the call is made.
1479 * @return {@code true} if a call to start an activity on the target display should succeed and
1480 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1481 */
1482 @Override
1483 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1484 String resolvedType, int userId) {
1485 final int callingUid = Binder.getCallingUid();
1486 final int callingPid = Binder.getCallingPid();
1487 final long origId = Binder.clearCallingIdentity();
1488
1489 try {
1490 // Collect information about the target of the Intent.
1491 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1492 0 /* startFlags */, null /* profilerInfo */, userId,
1493 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1494 UserHandle.USER_NULL));
1495 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1496
1497 synchronized (mGlobalLock) {
1498 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1499 aInfo);
1500 }
1501 } finally {
1502 Binder.restoreCallingIdentity(origId);
1503 }
1504 }
1505
1506 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001507 * This is the internal entry point for handling Activity.finish().
1508 *
1509 * @param token The Binder token referencing the Activity we want to finish.
1510 * @param resultCode Result code, if any, from this Activity.
1511 * @param resultData Result data (Intent), if any, from this Activity.
1512 * @param finishTask Whether to finish the task associated with this Activity.
1513 *
1514 * @return Returns true if the activity successfully finished, or false if it is still running.
1515 */
1516 @Override
1517 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1518 int finishTask) {
1519 // Refuse possible leaked file descriptors
1520 if (resultData != null && resultData.hasFileDescriptors()) {
1521 throw new IllegalArgumentException("File descriptors passed in Intent");
1522 }
1523
1524 synchronized (mGlobalLock) {
1525 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1526 if (r == null) {
1527 return true;
1528 }
1529 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001530 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001531 ActivityRecord rootR = tr.getRootActivity();
1532 if (rootR == null) {
1533 Slog.w(TAG, "Finishing task with all activities already finished");
1534 }
1535 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1536 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001537 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 return false;
1539 }
1540
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001541 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1542 // We should consolidate.
1543 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001544 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001545 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 if (next != null) {
1547 // ask watcher if this is allowed
1548 boolean resumeOK = true;
1549 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001550 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001552 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 Watchdog.getInstance().setActivityController(null);
1554 }
1555
1556 if (!resumeOK) {
1557 Slog.i(TAG, "Not finishing activity because controller resumed");
1558 return false;
1559 }
1560 }
1561 }
1562 final long origId = Binder.clearCallingIdentity();
1563 try {
1564 boolean res;
1565 final boolean finishWithRootActivity =
1566 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1567 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1568 || (finishWithRootActivity && r == rootR)) {
1569 // If requested, remove the task that is associated to this activity only if it
1570 // was the root activity in the task. The result code and data is ignored
1571 // because we don't support returning them across task boundaries. Also, to
1572 // keep backwards compatibility we remove the task from recents when finishing
1573 // task with root activity.
1574 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1575 finishWithRootActivity, "finish-activity");
1576 if (!res) {
1577 Slog.i(TAG, "Removing task failed to finish activity");
1578 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001579 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001580 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 } else {
1582 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1583 resultData, "app-request", true);
1584 if (!res) {
1585 Slog.i(TAG, "Failed to finish by app-request");
1586 }
1587 }
1588 return res;
1589 } finally {
1590 Binder.restoreCallingIdentity(origId);
1591 }
1592 }
1593 }
1594
1595 @Override
1596 public boolean finishActivityAffinity(IBinder token) {
1597 synchronized (mGlobalLock) {
1598 final long origId = Binder.clearCallingIdentity();
1599 try {
1600 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1601 if (r == null) {
1602 return false;
1603 }
1604
1605 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1606 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001607 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001608 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 return false;
1610 }
1611 return task.getStack().finishActivityAffinityLocked(r);
1612 } finally {
1613 Binder.restoreCallingIdentity(origId);
1614 }
1615 }
1616 }
1617
1618 @Override
1619 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1620 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001621 try {
1622 WindowProcessController proc = null;
1623 synchronized (mGlobalLock) {
1624 ActivityStack stack = ActivityRecord.getStackLocked(token);
1625 if (stack == null) {
1626 return;
1627 }
1628 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1629 false /* fromTimeout */, false /* processPausingActivities */, config);
1630 if (r != null) {
1631 proc = r.app;
1632 }
1633 if (stopProfiling && proc != null) {
1634 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 }
1636 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001637 } finally {
1638 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001640 }
1641
1642 @Override
1643 public final void activityResumed(IBinder token) {
1644 final long origId = Binder.clearCallingIdentity();
1645 synchronized (mGlobalLock) {
1646 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001647 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 }
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651
1652 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001653 public final void activityTopResumedStateLost() {
1654 final long origId = Binder.clearCallingIdentity();
1655 synchronized (mGlobalLock) {
1656 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1657 }
1658 Binder.restoreCallingIdentity(origId);
1659 }
1660
1661 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 public final void activityPaused(IBinder token) {
1663 final long origId = Binder.clearCallingIdentity();
1664 synchronized (mGlobalLock) {
1665 ActivityStack stack = ActivityRecord.getStackLocked(token);
1666 if (stack != null) {
1667 stack.activityPausedLocked(token, false);
1668 }
1669 }
1670 Binder.restoreCallingIdentity(origId);
1671 }
1672
1673 @Override
1674 public final void activityStopped(IBinder token, Bundle icicle,
1675 PersistableBundle persistentState, CharSequence description) {
1676 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1677
1678 // Refuse possible leaked file descriptors
1679 if (icicle != null && icicle.hasFileDescriptors()) {
1680 throw new IllegalArgumentException("File descriptors passed in Bundle");
1681 }
1682
1683 final long origId = Binder.clearCallingIdentity();
1684
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001685 String restartingName = null;
1686 int restartingUid = 0;
1687 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001688 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001689 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001691 if (r.attachedToProcess()
1692 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1693 // The activity was requested to restart from
1694 // {@link #restartActivityProcessIfVisible}.
1695 restartingName = r.app.mName;
1696 restartingUid = r.app.mUid;
1697 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 r.activityStoppedLocked(icicle, persistentState, description);
1699 }
1700 }
1701
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001702 if (restartingName != null) {
1703 // In order to let the foreground activity can be restarted with its saved state from
1704 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1705 // until the activity reports stopped with the state. And the activity record will be
1706 // kept because the record state is restarting, then the activity will be restarted
1707 // immediately if it is still the top one.
1708 mStackSupervisor.removeRestartTimeouts(r);
1709 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1710 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001711 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
1717 public final void activityDestroyed(IBinder token) {
1718 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1719 synchronized (mGlobalLock) {
1720 ActivityStack stack = ActivityRecord.getStackLocked(token);
1721 if (stack != null) {
1722 stack.activityDestroyedLocked(token, "activityDestroyed");
1723 }
1724 }
1725 }
1726
1727 @Override
1728 public final void activityRelaunched(IBinder token) {
1729 final long origId = Binder.clearCallingIdentity();
1730 synchronized (mGlobalLock) {
1731 mStackSupervisor.activityRelaunchedLocked(token);
1732 }
1733 Binder.restoreCallingIdentity(origId);
1734 }
1735
1736 public final void activitySlept(IBinder token) {
1737 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1738
1739 final long origId = Binder.clearCallingIdentity();
1740
1741 synchronized (mGlobalLock) {
1742 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1743 if (r != null) {
1744 mStackSupervisor.activitySleptLocked(r);
1745 }
1746 }
1747
1748 Binder.restoreCallingIdentity(origId);
1749 }
1750
1751 @Override
1752 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1753 synchronized (mGlobalLock) {
1754 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1755 if (r == null) {
1756 return;
1757 }
1758 final long origId = Binder.clearCallingIdentity();
1759 try {
1760 r.setRequestedOrientation(requestedOrientation);
1761 } finally {
1762 Binder.restoreCallingIdentity(origId);
1763 }
1764 }
1765 }
1766
1767 @Override
1768 public int getRequestedOrientation(IBinder token) {
1769 synchronized (mGlobalLock) {
1770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1771 if (r == null) {
1772 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1773 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001774 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776 }
1777
1778 @Override
1779 public void setImmersive(IBinder token, boolean immersive) {
1780 synchronized (mGlobalLock) {
1781 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1782 if (r == null) {
1783 throw new IllegalArgumentException();
1784 }
1785 r.immersive = immersive;
1786
1787 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001788 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792 }
1793 }
1794
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001795 void applyUpdateLockStateLocked(ActivityRecord r) {
1796 // Modifications to the UpdateLock state are done on our handler, outside
1797 // the activity manager's locks. The new state is determined based on the
1798 // state *now* of the relevant activity record. The object is passed to
1799 // the handler solely for logging detail, not to be consulted/modified.
1800 final boolean nextState = r != null && r.immersive;
1801 mH.post(() -> {
1802 if (mUpdateLock.isHeld() != nextState) {
1803 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1804 "Applying new update lock state '" + nextState + "' for " + r);
1805 if (nextState) {
1806 mUpdateLock.acquire();
1807 } else {
1808 mUpdateLock.release();
1809 }
1810 }
1811 });
1812 }
1813
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 @Override
1815 public boolean isImmersive(IBinder token) {
1816 synchronized (mGlobalLock) {
1817 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 throw new IllegalArgumentException();
1820 }
1821 return r.immersive;
1822 }
1823 }
1824
1825 @Override
1826 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001827 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001828 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001829 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 return (r != null) ? r.immersive : false;
1831 }
1832 }
1833
1834 @Override
1835 public void overridePendingTransition(IBinder token, String packageName,
1836 int enterAnim, int exitAnim) {
1837 synchronized (mGlobalLock) {
1838 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1839 if (self == null) {
1840 return;
1841 }
1842
1843 final long origId = Binder.clearCallingIdentity();
1844
1845 if (self.isState(
1846 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001847 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001848 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
1850
1851 Binder.restoreCallingIdentity(origId);
1852 }
1853 }
1854
1855 @Override
1856 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001859 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 if (r == null) {
1861 return ActivityManager.COMPAT_MODE_UNKNOWN;
1862 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001863 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 }
1865 }
1866
1867 @Override
1868 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001873 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001874 if (r == null) {
1875 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1876 return;
1877 }
1878 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001879 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 }
1881 }
1882
1883 @Override
1884 public int getLaunchedFromUid(IBinder activityToken) {
1885 ActivityRecord srec;
1886 synchronized (mGlobalLock) {
1887 srec = ActivityRecord.forTokenLocked(activityToken);
1888 }
1889 if (srec == null) {
1890 return -1;
1891 }
1892 return srec.launchedFromUid;
1893 }
1894
1895 @Override
1896 public String getLaunchedFromPackage(IBinder activityToken) {
1897 ActivityRecord srec;
1898 synchronized (mGlobalLock) {
1899 srec = ActivityRecord.forTokenLocked(activityToken);
1900 }
1901 if (srec == null) {
1902 return null;
1903 }
1904 return srec.launchedFromPackage;
1905 }
1906
1907 @Override
1908 public boolean convertFromTranslucent(IBinder token) {
1909 final long origId = Binder.clearCallingIdentity();
1910 try {
1911 synchronized (mGlobalLock) {
1912 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1913 if (r == null) {
1914 return false;
1915 }
1916 final boolean translucentChanged = r.changeWindowTranslucency(true);
1917 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001918 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001919 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001920 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 return translucentChanged;
1922 }
1923 } finally {
1924 Binder.restoreCallingIdentity(origId);
1925 }
1926 }
1927
1928 @Override
1929 public boolean convertToTranslucent(IBinder token, Bundle options) {
1930 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1931 final long origId = Binder.clearCallingIdentity();
1932 try {
1933 synchronized (mGlobalLock) {
1934 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1935 if (r == null) {
1936 return false;
1937 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001938 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 int index = task.mActivities.lastIndexOf(r);
1940 if (index > 0) {
1941 ActivityRecord under = task.mActivities.get(index - 1);
1942 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1943 }
1944 final boolean translucentChanged = r.changeWindowTranslucency(false);
1945 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001946 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001948 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001949 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 return translucentChanged;
1951 }
1952 } finally {
1953 Binder.restoreCallingIdentity(origId);
1954 }
1955 }
1956
1957 @Override
1958 public void notifyActivityDrawn(IBinder token) {
1959 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1960 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001961 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001963 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 }
1967
1968 @Override
1969 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1970 synchronized (mGlobalLock) {
1971 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1972 if (r == null) {
1973 return;
1974 }
1975 r.reportFullyDrawnLocked(restoredFromBundle);
1976 }
1977 }
1978
1979 @Override
1980 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1981 synchronized (mGlobalLock) {
1982 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1983 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1984 return stack.mDisplayId;
1985 }
1986 return DEFAULT_DISPLAY;
1987 }
1988 }
1989
1990 @Override
1991 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001992 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 long ident = Binder.clearCallingIdentity();
1994 try {
1995 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001996 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001997 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001998 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 }
2000 return null;
2001 }
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006
2007 @Override
2008 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002009 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2011 final long callingId = Binder.clearCallingIdentity();
2012 try {
2013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 if (stack == null) {
2016 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2017 return;
2018 }
2019 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002020 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002021 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 }
2023 }
2024 } finally {
2025 Binder.restoreCallingIdentity(callingId);
2026 }
2027 }
2028
2029 @Override
2030 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002031 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002032 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2033 final long callingId = Binder.clearCallingIdentity();
2034 try {
2035 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002036 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002037 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (task == null) {
2039 return;
2040 }
2041 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002042 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002043 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 }
2045 }
2046 } finally {
2047 Binder.restoreCallingIdentity(callingId);
2048 }
2049 }
2050
2051 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002052 public void restartActivityProcessIfVisible(IBinder activityToken) {
2053 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2054 final long callingId = Binder.clearCallingIdentity();
2055 try {
2056 synchronized (mGlobalLock) {
2057 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2058 if (r == null) {
2059 return;
2060 }
2061 r.restartProcessIfVisible();
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(callingId);
2065 }
2066 }
2067
2068 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 synchronized (mGlobalLock) {
2072 final long ident = Binder.clearCallingIdentity();
2073 try {
2074 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2075 "remove-task");
2076 } finally {
2077 Binder.restoreCallingIdentity(ident);
2078 }
2079 }
2080 }
2081
2082 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002083 public void removeAllVisibleRecentTasks() {
2084 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2085 synchronized (mGlobalLock) {
2086 final long ident = Binder.clearCallingIdentity();
2087 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002088 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002089 } finally {
2090 Binder.restoreCallingIdentity(ident);
2091 }
2092 }
2093 }
2094
2095 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2097 synchronized (mGlobalLock) {
2098 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2099 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002100 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 }
2102 }
2103 return false;
2104 }
2105
2106 @Override
2107 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2108 Intent resultData) {
2109
2110 synchronized (mGlobalLock) {
2111 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2112 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002113 return r.getActivityStack().navigateUpToLocked(
2114 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 }
2116 return false;
2117 }
2118 }
2119
2120 /**
2121 * Attempts to move a task backwards in z-order (the order of activities within the task is
2122 * unchanged).
2123 *
2124 * There are several possible results of this call:
2125 * - if the task is locked, then we will show the lock toast
2126 * - if there is a task behind the provided task, then that task is made visible and resumed as
2127 * this task is moved to the back
2128 * - otherwise, if there are no other tasks in the stack:
2129 * - if this task is in the pinned stack, then we remove the stack completely, which will
2130 * have the effect of moving the task to the top or bottom of the fullscreen stack
2131 * (depending on whether it is visible)
2132 * - otherwise, we simply return home and hide this task
2133 *
2134 * @param token A reference to the activity we wish to move
2135 * @param nonRoot If false then this only works if the activity is the root
2136 * of a task; if true it will work for any activity in a task.
2137 * @return Returns true if the move completed, false if not.
2138 */
2139 @Override
2140 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002141 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 synchronized (mGlobalLock) {
2143 final long origId = Binder.clearCallingIdentity();
2144 try {
2145 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002146 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 if (task != null) {
2148 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2149 }
2150 } finally {
2151 Binder.restoreCallingIdentity(origId);
2152 }
2153 }
2154 return false;
2155 }
2156
2157 @Override
2158 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002159 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 long ident = Binder.clearCallingIdentity();
2161 Rect rect = new Rect();
2162 try {
2163 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002164 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2166 if (task == null) {
2167 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2168 return rect;
2169 }
2170 if (task.getStack() != null) {
2171 // Return the bounds from window manager since it will be adjusted for various
2172 // things like the presense of a docked stack for tasks that aren't resizeable.
2173 task.getWindowContainerBounds(rect);
2174 } else {
2175 // Task isn't in window manager yet since it isn't associated with a stack.
2176 // Return the persist value from activity manager
2177 if (!task.matchParentBounds()) {
2178 rect.set(task.getBounds());
2179 } else if (task.mLastNonFullscreenBounds != null) {
2180 rect.set(task.mLastNonFullscreenBounds);
2181 }
2182 }
2183 }
2184 } finally {
2185 Binder.restoreCallingIdentity(ident);
2186 }
2187 return rect;
2188 }
2189
2190 @Override
2191 public ActivityManager.TaskDescription getTaskDescription(int id) {
2192 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002195 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2197 if (tr != null) {
2198 return tr.lastTaskDescription;
2199 }
2200 }
2201 return null;
2202 }
2203
2204 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002205 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2206 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2207 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2208 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2209 return;
2210 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002211 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002212 synchronized (mGlobalLock) {
2213 final long ident = Binder.clearCallingIdentity();
2214 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002215 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002216 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002217 if (task == null) {
2218 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2219 return;
2220 }
2221
2222 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2223 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2224
2225 if (!task.isActivityTypeStandardOrUndefined()) {
2226 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2227 + " non-standard task " + taskId + " to windowing mode="
2228 + windowingMode);
2229 }
2230
2231 final ActivityStack stack = task.getStack();
2232 if (toTop) {
2233 stack.moveToFront("setTaskWindowingMode", task);
2234 }
2235 stack.setWindowingMode(windowingMode);
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
2239 }
2240 }
2241
2242 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002244 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 ActivityRecord r = getCallingRecordLocked(token);
2246 return r != null ? r.info.packageName : null;
2247 }
2248 }
2249
2250 @Override
2251 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002252 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 ActivityRecord r = getCallingRecordLocked(token);
2254 return r != null ? r.intent.getComponent() : null;
2255 }
2256 }
2257
2258 private ActivityRecord getCallingRecordLocked(IBinder token) {
2259 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2260 if (r == null) {
2261 return null;
2262 }
2263 return r.resultTo;
2264 }
2265
2266 @Override
2267 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269
2270 synchronized (mGlobalLock) {
2271 final long origId = Binder.clearCallingIdentity();
2272 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002273 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 } finally {
2275 Binder.restoreCallingIdentity(origId);
2276 }
2277 }
2278 }
2279
2280 /**
2281 * TODO: Add mController hook
2282 */
2283 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002284 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2285 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002286 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002287
2288 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2289 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002290 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2291 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 }
2293 }
2294
Ricky Waiaca8a772019-04-04 16:01:06 +01002295 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2296 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 boolean fromRecents) {
2298
Ricky Waiaca8a772019-04-04 16:01:06 +01002299 final int callingPid = Binder.getCallingPid();
2300 final int callingUid = Binder.getCallingUid();
2301 if (!isSameApp(callingUid, callingPackage)) {
2302 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2303 + Binder.getCallingPid() + " as package " + callingPackage;
2304 Slog.w(TAG, msg);
2305 throw new SecurityException(msg);
2306 }
2307 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 SafeActivityOptions.abort(options);
2309 return;
2310 }
2311 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002312 WindowProcessController callerApp = null;
2313 if (appThread != null) {
2314 callerApp = getProcessController(appThread);
2315 }
2316 final ActivityStarter starter = getActivityStartController().obtainStarter(
2317 null /* intent */, "moveTaskToFront");
2318 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2319 -1, callerApp, null, false, null)) {
2320 boolean abort = !isBackgroundActivityStartsEnabled();
2321 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2322 if (abort) {
2323 return;
2324 }
2325 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002326 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002327 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 if (task == null) {
2329 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002330 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002331 return;
2332 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002333 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002335 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 return;
2337 }
2338 ActivityOptions realOptions = options != null
2339 ? options.getOptions(mStackSupervisor)
2340 : null;
2341 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2342 false /* forceNonResizable */);
2343
2344 final ActivityRecord topActivity = task.getTopActivity();
2345 if (topActivity != null) {
2346
2347 // We are reshowing a task, use a starting window to hide the initial draw delay
2348 // so the transition can start earlier.
2349 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2350 true /* taskSwitch */, fromRecents);
2351 }
2352 } finally {
2353 Binder.restoreCallingIdentity(origId);
2354 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 }
2356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 /**
2358 * Return true if callingUid is system, or packageName belongs to that callingUid.
2359 */
2360 boolean isSameApp(int callingUid, @Nullable String packageName) {
2361 try {
2362 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2363 if (packageName == null) {
2364 return false;
2365 }
2366 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2367 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2368 UserHandle.getUserId(callingUid));
2369 return UserHandle.isSameApp(callingUid, uid);
2370 }
2371 } catch (RemoteException e) {
2372 // Should not happen
2373 }
2374 return true;
2375 }
2376
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002377 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2378 int callingPid, int callingUid, String name) {
2379 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2380 return true;
2381 }
2382
2383 if (getRecentTasks().isCallerRecents(sourceUid)) {
2384 return true;
2385 }
2386
2387 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2388 if (perm == PackageManager.PERMISSION_GRANTED) {
2389 return true;
2390 }
2391 if (checkAllowAppSwitchUid(sourceUid)) {
2392 return true;
2393 }
2394
2395 // If the actual IPC caller is different from the logical source, then
2396 // also see if they are allowed to control app switches.
2397 if (callingUid != -1 && callingUid != sourceUid) {
2398 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2399 if (perm == PackageManager.PERMISSION_GRANTED) {
2400 return true;
2401 }
2402 if (checkAllowAppSwitchUid(callingUid)) {
2403 return true;
2404 }
2405 }
2406
2407 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2408 return false;
2409 }
2410
2411 private boolean checkAllowAppSwitchUid(int uid) {
2412 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2413 if (types != null) {
2414 for (int i = types.size() - 1; i >= 0; i--) {
2415 if (types.valueAt(i).intValue() == uid) {
2416 return true;
2417 }
2418 }
2419 }
2420 return false;
2421 }
2422
2423 @Override
2424 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2425 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2426 "setActivityController()");
2427 synchronized (mGlobalLock) {
2428 mController = controller;
2429 mControllerIsAMonkey = imAMonkey;
2430 Watchdog.getInstance().setActivityController(controller);
2431 }
2432 }
2433
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002434 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002435 synchronized (mGlobalLock) {
2436 return mController != null && mControllerIsAMonkey;
2437 }
2438 }
2439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002440 @Override
2441 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2442 synchronized (mGlobalLock) {
2443 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2444 }
2445 }
2446
2447 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2449 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2450 }
2451
2452 @Override
2453 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2454 @WindowConfiguration.ActivityType int ignoreActivityType,
2455 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2456 final int callingUid = Binder.getCallingUid();
2457 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2458
2459 synchronized (mGlobalLock) {
2460 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2461
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002462 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002463 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002464 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002465 ignoreWindowingMode, callingUid, allowed);
2466 }
2467
2468 return list;
2469 }
2470
2471 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002472 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2473 synchronized (mGlobalLock) {
2474 final long origId = Binder.clearCallingIdentity();
2475 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2476 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002477 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002478 }
2479 Binder.restoreCallingIdentity(origId);
2480 }
2481 }
2482
2483 @Override
2484 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002485 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 ActivityStack stack = ActivityRecord.getStackLocked(token);
2487 if (stack != null) {
2488 return stack.willActivityBeVisibleLocked(token);
2489 }
2490 return false;
2491 }
2492 }
2493
2494 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002495 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 synchronized (mGlobalLock) {
2498 final long ident = Binder.clearCallingIdentity();
2499 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002500 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002501 if (task == null) {
2502 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2503 return;
2504 }
2505
2506 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2507 + " to stackId=" + stackId + " toTop=" + toTop);
2508
Wale Ogunwaled32da472018-11-16 07:19:28 -08002509 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002510 if (stack == null) {
2511 throw new IllegalStateException(
2512 "moveTaskToStack: No stack for stackId=" + stackId);
2513 }
2514 if (!stack.isActivityTypeStandardOrUndefined()) {
2515 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2516 + taskId + " to stack " + stackId);
2517 }
2518 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002519 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002520 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2521 }
2522 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2523 "moveTaskToStack");
2524 } finally {
2525 Binder.restoreCallingIdentity(ident);
2526 }
2527 }
2528 }
2529
2530 @Override
2531 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2532 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002533 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002534
2535 final long ident = Binder.clearCallingIdentity();
2536 try {
2537 synchronized (mGlobalLock) {
2538 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002539 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002540 if (stack == null) {
2541 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2542 return;
2543 }
2544 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2545 throw new IllegalArgumentException("Stack: " + stackId
2546 + " doesn't support animated resize.");
2547 }
2548 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2549 animationDuration, false /* fromFullscreen */);
2550 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002551 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 if (stack == null) {
2553 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2554 return;
2555 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002556 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2558 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2559 }
2560 }
2561 } finally {
2562 Binder.restoreCallingIdentity(ident);
2563 }
2564 }
2565
wilsonshih5c4cf522019-01-25 09:03:47 +08002566 @Override
2567 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2568 int animationDuration) {
2569 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2570
2571 final long ident = Binder.clearCallingIdentity();
2572 try {
2573 synchronized (mGlobalLock) {
2574 if (xOffset == 0 && yOffset == 0) {
2575 return;
2576 }
2577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2578 if (stack == null) {
2579 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2580 return;
2581 }
2582 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2583 throw new IllegalArgumentException("Stack: " + stackId
2584 + " doesn't support animated resize.");
2585 }
2586 final Rect destBounds = new Rect();
2587 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002588 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002589 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2590 return;
2591 }
2592 destBounds.offset(xOffset, yOffset);
2593 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2594 animationDuration, false /* fromFullscreen */);
2595 }
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002600 /**
2601 * Moves the specified task to the primary-split-screen stack.
2602 *
2603 * @param taskId Id of task to move.
2604 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2605 * exist already. See
2606 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2607 * and
2608 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2609 * @param toTop If the task and stack should be moved to the top.
2610 * @param animate Whether we should play an animation for the moving the task.
2611 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2612 * stack. Pass {@code null} to use default bounds.
2613 * @param showRecents If the recents activity should be shown on the other side of the task
2614 * going into split-screen mode.
2615 */
2616 @Override
2617 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2618 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002619 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002620 "setTaskWindowingModeSplitScreenPrimary()");
2621 synchronized (mGlobalLock) {
2622 final long ident = Binder.clearCallingIdentity();
2623 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002624 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002625 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 if (task == null) {
2627 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2628 return false;
2629 }
2630 if (DEBUG_STACK) Slog.d(TAG_STACK,
2631 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2632 + " to createMode=" + createMode + " toTop=" + toTop);
2633 if (!task.isActivityTypeStandardOrUndefined()) {
2634 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2635 + " non-standard task " + taskId + " to split-screen windowing mode");
2636 }
2637
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002638 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002639 final int windowingMode = task.getWindowingMode();
2640 final ActivityStack stack = task.getStack();
2641 if (toTop) {
2642 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2643 }
2644 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002645 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2646 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002647 return windowingMode != task.getWindowingMode();
2648 } finally {
2649 Binder.restoreCallingIdentity(ident);
2650 }
2651 }
2652 }
2653
2654 /**
2655 * Removes stacks in the input windowing modes from the system if they are of activity type
2656 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2657 */
2658 @Override
2659 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002660 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002661 "removeStacksInWindowingModes()");
2662
2663 synchronized (mGlobalLock) {
2664 final long ident = Binder.clearCallingIdentity();
2665 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002666 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002667 } finally {
2668 Binder.restoreCallingIdentity(ident);
2669 }
2670 }
2671 }
2672
2673 @Override
2674 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 "removeStacksWithActivityTypes()");
2677
2678 synchronized (mGlobalLock) {
2679 final long ident = Binder.clearCallingIdentity();
2680 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002681 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002687
2688 @Override
2689 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2690 int userId) {
2691 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002692 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2693 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002694 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002695 final boolean detailed = checkGetTasksPermission(
2696 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2697 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698 == PackageManager.PERMISSION_GRANTED;
2699
2700 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002701 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 callingUid);
2703 }
2704 }
2705
2706 @Override
2707 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002708 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 long ident = Binder.clearCallingIdentity();
2710 try {
2711 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002712 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 }
2714 } finally {
2715 Binder.restoreCallingIdentity(ident);
2716 }
2717 }
2718
2719 @Override
2720 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002721 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002722 long ident = Binder.clearCallingIdentity();
2723 try {
2724 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002725 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002726 }
2727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731
2732 @Override
2733 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002734 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002735 final long callingUid = Binder.getCallingUid();
2736 final long origId = Binder.clearCallingIdentity();
2737 try {
2738 synchronized (mGlobalLock) {
2739 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2742 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2743 }
2744 } finally {
2745 Binder.restoreCallingIdentity(origId);
2746 }
2747 }
2748
2749 @Override
2750 public void startLockTaskModeByToken(IBinder token) {
2751 synchronized (mGlobalLock) {
2752 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2753 if (r == null) {
2754 return;
2755 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002756 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 }
2758 }
2759
2760 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002761 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 // This makes inner call to look as if it was initiated by system.
2764 long ident = Binder.clearCallingIdentity();
2765 try {
2766 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002767 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002768 MATCH_TASK_IN_STACKS_ONLY);
2769 if (task == null) {
2770 return;
2771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772
2773 // When starting lock task mode the stack must be in front and focused
2774 task.getStack().moveToFront("startSystemLockTaskMode");
2775 startLockTaskModeLocked(task, true /* isSystemCaller */);
2776 }
2777 } finally {
2778 Binder.restoreCallingIdentity(ident);
2779 }
2780 }
2781
2782 @Override
2783 public void stopLockTaskModeByToken(IBinder token) {
2784 synchronized (mGlobalLock) {
2785 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2786 if (r == null) {
2787 return;
2788 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002789 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 }
2792
2793 /**
2794 * This API should be called by SystemUI only when user perform certain action to dismiss
2795 * lock task mode. We should only dismiss pinned lock task mode in this case.
2796 */
2797 @Override
2798 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002799 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002800 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2801 }
2802
2803 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2804 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2805 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2806 return;
2807 }
2808
Wale Ogunwaled32da472018-11-16 07:19:28 -08002809 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810 if (stack == null || task != stack.topTask()) {
2811 throw new IllegalArgumentException("Invalid task, not in foreground");
2812 }
2813
2814 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2815 // system or a specific app.
2816 // * System-initiated requests will only start the pinned mode (screen pinning)
2817 // * App-initiated requests
2818 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2819 // - will start the pinned mode, otherwise
2820 final int callingUid = Binder.getCallingUid();
2821 long ident = Binder.clearCallingIdentity();
2822 try {
2823 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002824 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002825
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002826 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 } finally {
2828 Binder.restoreCallingIdentity(ident);
2829 }
2830 }
2831
2832 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2833 final int callingUid = Binder.getCallingUid();
2834 long ident = Binder.clearCallingIdentity();
2835 try {
2836 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002837 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 }
2839 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2840 // task and jumping straight into a call in the case of emergency call back.
2841 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2842 if (tm != null) {
2843 tm.showInCallScreen(false);
2844 }
2845 } finally {
2846 Binder.restoreCallingIdentity(ident);
2847 }
2848 }
2849
2850 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002851 public void updateLockTaskPackages(int userId, String[] packages) {
2852 final int callingUid = Binder.getCallingUid();
2853 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2854 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2855 "updateLockTaskPackages()");
2856 }
2857 synchronized (this) {
2858 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2859 + Arrays.toString(packages));
2860 getLockTaskController().updateLockTaskPackages(userId, packages);
2861 }
2862 }
2863
2864 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 public boolean isInLockTaskMode() {
2866 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2867 }
2868
2869 @Override
2870 public int getLockTaskModeState() {
2871 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002872 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002873 }
2874 }
2875
2876 @Override
2877 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2878 synchronized (mGlobalLock) {
2879 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2880 if (r != null) {
2881 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002882 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002884 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002885 }
2886 }
2887 }
2888
2889 @Override
2890 public Bundle getActivityOptions(IBinder token) {
2891 final long origId = Binder.clearCallingIdentity();
2892 try {
2893 synchronized (mGlobalLock) {
2894 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2895 if (r != null) {
2896 final ActivityOptions activityOptions = r.takeOptionsLocked();
2897 return activityOptions == null ? null : activityOptions.toBundle();
2898 }
2899 return null;
2900 }
2901 } finally {
2902 Binder.restoreCallingIdentity(origId);
2903 }
2904 }
2905
2906 @Override
2907 public List<IBinder> getAppTasks(String callingPackage) {
2908 int callingUid = Binder.getCallingUid();
2909 long ident = Binder.clearCallingIdentity();
2910 try {
2911 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002912 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002913 }
2914 } finally {
2915 Binder.restoreCallingIdentity(ident);
2916 }
2917 }
2918
2919 @Override
2920 public void finishVoiceTask(IVoiceInteractionSession session) {
2921 synchronized (mGlobalLock) {
2922 final long origId = Binder.clearCallingIdentity();
2923 try {
2924 // TODO: VI Consider treating local voice interactions and voice tasks
2925 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002926 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 } finally {
2928 Binder.restoreCallingIdentity(origId);
2929 }
2930 }
2931
2932 }
2933
2934 @Override
2935 public boolean isTopOfTask(IBinder token) {
2936 synchronized (mGlobalLock) {
2937 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002938 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941
2942 @Override
2943 public void notifyLaunchTaskBehindComplete(IBinder token) {
2944 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2945 }
2946
2947 @Override
2948 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002949 mH.post(() -> {
2950 synchronized (mGlobalLock) {
2951 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002952 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002953 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002954 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002955 } catch (RemoteException e) {
2956 }
2957 }
2958 }
2959
2960 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 }
2962
2963 /** Called from an app when assist data is ready. */
2964 @Override
2965 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2966 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002967 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 synchronized (pae) {
2969 pae.result = extras;
2970 pae.structure = structure;
2971 pae.content = content;
2972 if (referrer != null) {
2973 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2974 }
2975 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002976 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002977 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2978 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 structure.setHomeActivity(pae.isHome);
2980 }
2981 pae.haveResult = true;
2982 pae.notifyAll();
2983 if (pae.intent == null && pae.receiver == null) {
2984 // Caller is just waiting for the result.
2985 return;
2986 }
2987 }
2988 // We are now ready to launch the assist activity.
2989 IAssistDataReceiver sendReceiver = null;
2990 Bundle sendBundle = null;
2991 synchronized (mGlobalLock) {
2992 buildAssistBundleLocked(pae, extras);
2993 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002994 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 if (!exists) {
2996 // Timed out.
2997 return;
2998 }
2999
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003000 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 // Caller wants result sent back to them.
3002 sendBundle = new Bundle();
3003 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3004 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3005 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3006 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3007 }
3008 }
3009 if (sendReceiver != null) {
3010 try {
3011 sendReceiver.onHandleAssistData(sendBundle);
3012 } catch (RemoteException e) {
3013 }
3014 return;
3015 }
3016
3017 final long ident = Binder.clearCallingIdentity();
3018 try {
3019 if (TextUtils.equals(pae.intent.getAction(),
3020 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3021 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003022
3023 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 } else {
3025 pae.intent.replaceExtras(pae.extras);
3026 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3027 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3028 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003029 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030
3031 try {
3032 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3033 } catch (ActivityNotFoundException e) {
3034 Slog.w(TAG, "No activity to handle assist action.", e);
3035 }
3036 }
3037 } finally {
3038 Binder.restoreCallingIdentity(ident);
3039 }
3040 }
3041
Marvin Ramin830d4e32019-03-12 13:16:58 +01003042 /**
3043 * Workaround for historical API which starts the Assist service with a non-foreground
3044 * {@code startService()} call.
3045 */
3046 private void startVoiceInteractionServiceAsUser(
3047 Intent intent, int userHandle, String reason) {
3048 // Resolve the intent to find out which package we need to whitelist.
3049 ResolveInfo resolveInfo =
3050 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3051 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3052 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3053 return;
3054 }
3055 intent.setPackage(resolveInfo.serviceInfo.packageName);
3056
3057 // Whitelist background services temporarily.
3058 LocalServices.getService(DeviceIdleController.LocalService.class)
3059 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3060 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3061
3062 // Finally, try to start the service.
3063 try {
3064 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3065 } catch (RuntimeException e) {
3066 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3067 }
3068 }
3069
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 @Override
3071 public int addAppTask(IBinder activityToken, Intent intent,
3072 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3073 final int callingUid = Binder.getCallingUid();
3074 final long callingIdent = Binder.clearCallingIdentity();
3075
3076 try {
3077 synchronized (mGlobalLock) {
3078 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3079 if (r == null) {
3080 throw new IllegalArgumentException("Activity does not exist; token="
3081 + activityToken);
3082 }
3083 ComponentName comp = intent.getComponent();
3084 if (comp == null) {
3085 throw new IllegalArgumentException("Intent " + intent
3086 + " must specify explicit component");
3087 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003088 if (thumbnail.getWidth() != mThumbnailWidth
3089 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 throw new IllegalArgumentException("Bad thumbnail size: got "
3091 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003092 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 }
3094 if (intent.getSelector() != null) {
3095 intent.setSelector(null);
3096 }
3097 if (intent.getSourceBounds() != null) {
3098 intent.setSourceBounds(null);
3099 }
3100 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3101 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3102 // The caller has added this as an auto-remove task... that makes no
3103 // sense, so turn off auto-remove.
3104 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3105 }
3106 }
3107 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3108 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3109 if (ainfo.applicationInfo.uid != callingUid) {
3110 throw new SecurityException(
3111 "Can't add task for another application: target uid="
3112 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3113 }
3114
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003115 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003117 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003119 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003120 // The app has too many tasks already and we can't add any more
3121 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3122 return INVALID_TASK_ID;
3123 }
3124 task.lastTaskDescription.copyFrom(description);
3125
3126 // TODO: Send the thumbnail to WM to store it.
3127
3128 return task.taskId;
3129 }
3130 } finally {
3131 Binder.restoreCallingIdentity(callingIdent);
3132 }
3133 }
3134
3135 @Override
3136 public Point getAppTaskThumbnailSize() {
3137 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003138 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 }
3140 }
3141
3142 @Override
3143 public void setTaskResizeable(int taskId, int resizeableMode) {
3144 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003145 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3147 if (task == null) {
3148 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3149 return;
3150 }
3151 task.setResizeMode(resizeableMode);
3152 }
3153 }
3154
3155 @Override
3156 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003157 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 long ident = Binder.clearCallingIdentity();
3159 try {
3160 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003161 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003162 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 if (task == null) {
3164 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3165 return;
3166 }
3167 // Place the task in the right stack if it isn't there already based on
3168 // the requested bounds.
3169 // The stack transition logic is:
3170 // - a null bounds on a freeform task moves that task to fullscreen
3171 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3172 // that task to freeform
3173 // - otherwise the task is not moved
3174 ActivityStack stack = task.getStack();
3175 if (!task.getWindowConfiguration().canResizeTask()) {
3176 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3177 }
3178 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3179 stack = stack.getDisplay().getOrCreateStack(
3180 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3181 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3182 stack = stack.getDisplay().getOrCreateStack(
3183 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3184 }
3185
3186 // Reparent the task to the right stack if necessary
3187 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3188 if (stack != task.getStack()) {
3189 // Defer resume until the task is resized below
3190 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3191 DEFER_RESUME, "resizeTask");
3192 preserveWindow = false;
3193 }
3194
3195 // After reparenting (which only resizes the task to the stack bounds), resize the
3196 // task to the actual bounds provided
3197 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3198 }
3199 } finally {
3200 Binder.restoreCallingIdentity(ident);
3201 }
3202 }
3203
3204 @Override
3205 public boolean releaseActivityInstance(IBinder token) {
3206 synchronized (mGlobalLock) {
3207 final long origId = Binder.clearCallingIdentity();
3208 try {
3209 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3210 if (r == null) {
3211 return false;
3212 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003213 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 } finally {
3215 Binder.restoreCallingIdentity(origId);
3216 }
3217 }
3218 }
3219
3220 @Override
3221 public void releaseSomeActivities(IApplicationThread appInt) {
3222 synchronized (mGlobalLock) {
3223 final long origId = Binder.clearCallingIdentity();
3224 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003225 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003226 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 } finally {
3228 Binder.restoreCallingIdentity(origId);
3229 }
3230 }
3231 }
3232
3233 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003234 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003235 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003236 != PackageManager.PERMISSION_GRANTED) {
3237 throw new SecurityException("Requires permission "
3238 + android.Manifest.permission.DEVICE_POWER);
3239 }
3240
3241 synchronized (mGlobalLock) {
3242 long ident = Binder.clearCallingIdentity();
3243 if (mKeyguardShown != keyguardShowing) {
3244 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003245 final Message msg = PooledLambda.obtainMessage(
3246 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3247 keyguardShowing);
3248 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 }
3250 try {
wilsonshih177261f2019-02-22 12:02:18 +08003251 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003252 } finally {
3253 Binder.restoreCallingIdentity(ident);
3254 }
3255 }
3256
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003257 mH.post(() -> {
3258 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3259 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3260 }
3261 });
3262 }
3263
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003264 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 mH.post(() -> {
3266 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3267 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3268 }
3269 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003270 }
3271
3272 @Override
3273 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003274 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3275 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003276
3277 final File passedIconFile = new File(filePath);
3278 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3279 passedIconFile.getName());
3280 if (!legitIconFile.getPath().equals(filePath)
3281 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3282 throw new IllegalArgumentException("Bad file path: " + filePath
3283 + " passed for userId " + userId);
3284 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003285 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 }
3287
3288 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003289 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003290 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3291 final ActivityOptions activityOptions = safeOptions != null
3292 ? safeOptions.getOptions(mStackSupervisor)
3293 : null;
3294 if (activityOptions == null
3295 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3296 || activityOptions.getCustomInPlaceResId() == 0) {
3297 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3298 "with valid animation");
3299 }
lumark588a3e82018-07-20 18:53:54 +08003300 // Get top display of front most application.
3301 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3302 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003303 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3304 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3305 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003306 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003307 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003308 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 }
3310
3311 @Override
3312 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003313 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 synchronized (mGlobalLock) {
3315 final long ident = Binder.clearCallingIdentity();
3316 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003317 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 if (stack == null) {
3319 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3320 return;
3321 }
3322 if (!stack.isActivityTypeStandardOrUndefined()) {
3323 throw new IllegalArgumentException(
3324 "Removing non-standard stack is not allowed.");
3325 }
3326 mStackSupervisor.removeStack(stack);
3327 } finally {
3328 Binder.restoreCallingIdentity(ident);
3329 }
3330 }
3331 }
3332
3333 @Override
3334 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003335 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336
3337 synchronized (mGlobalLock) {
3338 final long ident = Binder.clearCallingIdentity();
3339 try {
3340 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3341 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003342 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 } finally {
3344 Binder.restoreCallingIdentity(ident);
3345 }
3346 }
3347 }
3348
3349 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003350 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 synchronized (mGlobalLock) {
3352 long ident = Binder.clearCallingIdentity();
3353 try {
3354 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3355 if (r == null) {
3356 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003357 "toggleFreeformWindowingMode: No activity record matching token="
3358 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359 }
3360
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003361 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003362 if (stack == null) {
3363 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3364 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 }
3366
Yunfan Chend967af82019-01-17 18:30:18 +09003367 if (!stack.inFreeformWindowingMode()
3368 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3369 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3370 + "toggle between fullscreen and freeform.");
3371 }
3372
3373 if (stack.inFreeformWindowingMode()) {
3374 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3375 } else {
3376 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3377 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } finally {
3379 Binder.restoreCallingIdentity(ident);
3380 }
3381 }
3382 }
3383
3384 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3385 @Override
3386 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003387 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003389 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 }
3391
3392 /** Unregister a task stack listener so that it stops receiving callbacks. */
3393 @Override
3394 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003395 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003397 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 }
3399
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 @Override
3401 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3402 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3403 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3404 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3405 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3406 }
3407
3408 @Override
3409 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3410 IBinder activityToken, int flags) {
3411 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3412 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3413 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3414 }
3415
3416 @Override
3417 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3418 Bundle args) {
3419 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3420 true /* focused */, true /* newSessionId */, userHandle, args,
3421 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3422 }
3423
3424 @Override
3425 public Bundle getAssistContextExtras(int requestType) {
3426 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3427 null, null, true /* focused */, true /* newSessionId */,
3428 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3429 if (pae == null) {
3430 return null;
3431 }
3432 synchronized (pae) {
3433 while (!pae.haveResult) {
3434 try {
3435 pae.wait();
3436 } catch (InterruptedException e) {
3437 }
3438 }
3439 }
3440 synchronized (mGlobalLock) {
3441 buildAssistBundleLocked(pae, pae.result);
3442 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003443 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444 }
3445 return pae.extras;
3446 }
3447
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003448 /**
3449 * Binder IPC calls go through the public entry point.
3450 * This can be called with or without the global lock held.
3451 */
3452 private static int checkCallingPermission(String permission) {
3453 return checkPermission(
3454 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3455 }
3456
3457 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003458 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3460 mAmInternal.enforceCallingPermission(permission, func);
3461 }
3462 }
3463
3464 @VisibleForTesting
3465 int checkGetTasksPermission(String permission, int pid, int uid) {
3466 return checkPermission(permission, pid, uid);
3467 }
3468
3469 static int checkPermission(String permission, int pid, int uid) {
3470 if (permission == null) {
3471 return PackageManager.PERMISSION_DENIED;
3472 }
3473 return checkComponentPermission(permission, pid, uid, -1, true);
3474 }
3475
Wale Ogunwale214f3482018-10-04 11:00:47 -07003476 public static int checkComponentPermission(String permission, int pid, int uid,
3477 int owningUid, boolean exported) {
3478 return ActivityManagerService.checkComponentPermission(
3479 permission, pid, uid, owningUid, exported);
3480 }
3481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3483 if (getRecentTasks().isCallerRecents(callingUid)) {
3484 // Always allow the recents component to get tasks
3485 return true;
3486 }
3487
3488 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3489 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3490 if (!allowed) {
3491 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3492 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3493 // Temporary compatibility: some existing apps on the system image may
3494 // still be requesting the old permission and not switched to the new
3495 // one; if so, we'll still allow them full access. This means we need
3496 // to see if they are holding the old permission and are a system app.
3497 try {
3498 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3499 allowed = true;
3500 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3501 + " is using old GET_TASKS but privileged; allowing");
3502 }
3503 } catch (RemoteException e) {
3504 }
3505 }
3506 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3507 + " does not hold REAL_GET_TASKS; limiting output");
3508 }
3509 return allowed;
3510 }
3511
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3513 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3514 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3515 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 "enqueueAssistContext()");
3518
3519 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003520 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 if (activity == null) {
3522 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3523 return null;
3524 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003525 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3527 return null;
3528 }
3529 if (focused) {
3530 if (activityToken != null) {
3531 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3532 if (activity != caller) {
3533 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3534 + " is not current top " + activity);
3535 return null;
3536 }
3537 }
3538 } else {
3539 activity = ActivityRecord.forTokenLocked(activityToken);
3540 if (activity == null) {
3541 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3542 + " couldn't be found");
3543 return null;
3544 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003545 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3547 return null;
3548 }
3549 }
3550
3551 PendingAssistExtras pae;
3552 Bundle extras = new Bundle();
3553 if (args != null) {
3554 extras.putAll(args);
3555 }
3556 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003557 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558
3559 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3560 userHandle);
3561 pae.isHome = activity.isActivityTypeHome();
3562
3563 // Increment the sessionId if necessary
3564 if (newSessionId) {
3565 mViSessionId++;
3566 }
3567 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003568 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3569 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003571 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003572 } catch (RemoteException e) {
3573 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3574 return null;
3575 }
3576 return pae;
3577 }
3578 }
3579
3580 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3581 if (result != null) {
3582 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3583 }
3584 if (pae.hint != null) {
3585 pae.extras.putBoolean(pae.hint, true);
3586 }
3587 }
3588
3589 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3590 IAssistDataReceiver receiver;
3591 synchronized (mGlobalLock) {
3592 mPendingAssistExtras.remove(pae);
3593 receiver = pae.receiver;
3594 }
3595 if (receiver != null) {
3596 // Caller wants result sent back to them.
3597 Bundle sendBundle = new Bundle();
3598 // At least return the receiver extras
3599 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3600 try {
3601 pae.receiver.onHandleAssistData(sendBundle);
3602 } catch (RemoteException e) {
3603 }
3604 }
3605 }
3606
3607 public class PendingAssistExtras extends Binder implements Runnable {
3608 public final ActivityRecord activity;
3609 public boolean isHome;
3610 public final Bundle extras;
3611 public final Intent intent;
3612 public final String hint;
3613 public final IAssistDataReceiver receiver;
3614 public final int userHandle;
3615 public boolean haveResult = false;
3616 public Bundle result = null;
3617 public AssistStructure structure = null;
3618 public AssistContent content = null;
3619 public Bundle receiverExtras;
3620
3621 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3622 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3623 int _userHandle) {
3624 activity = _activity;
3625 extras = _extras;
3626 intent = _intent;
3627 hint = _hint;
3628 receiver = _receiver;
3629 receiverExtras = _receiverExtras;
3630 userHandle = _userHandle;
3631 }
3632
3633 @Override
3634 public void run() {
3635 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3636 synchronized (this) {
3637 haveResult = true;
3638 notifyAll();
3639 }
3640 pendingAssistExtrasTimedOut(this);
3641 }
3642 }
3643
3644 @Override
3645 public boolean isAssistDataAllowedOnCurrentActivity() {
3646 int userId;
3647 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003648 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3650 return false;
3651 }
3652
3653 final ActivityRecord activity = focusedStack.getTopActivity();
3654 if (activity == null) {
3655 return false;
3656 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003657 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 }
3659 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3660 }
3661
3662 @Override
3663 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3664 long ident = Binder.clearCallingIdentity();
3665 try {
3666 synchronized (mGlobalLock) {
3667 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003668 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 if (top != caller) {
3670 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3671 + " is not current top " + top);
3672 return false;
3673 }
3674 if (!top.nowVisible) {
3675 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3676 + " is not visible");
3677 return false;
3678 }
3679 }
3680 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3681 token);
3682 } finally {
3683 Binder.restoreCallingIdentity(ident);
3684 }
3685 }
3686
3687 @Override
3688 public boolean isRootVoiceInteraction(IBinder token) {
3689 synchronized (mGlobalLock) {
3690 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3691 if (r == null) {
3692 return false;
3693 }
3694 return r.rootVoiceInteraction;
3695 }
3696 }
3697
Wale Ogunwalef6733932018-06-27 05:14:34 -07003698 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3699 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3700 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3701 if (activityToCallback == null) return;
3702 activityToCallback.setVoiceSessionLocked(voiceSession);
3703
3704 // Inform the activity
3705 try {
3706 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3707 voiceInteractor);
3708 long token = Binder.clearCallingIdentity();
3709 try {
3710 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3711 } finally {
3712 Binder.restoreCallingIdentity(token);
3713 }
3714 // TODO: VI Should we cache the activity so that it's easier to find later
3715 // rather than scan through all the stacks and activities?
3716 } catch (RemoteException re) {
3717 activityToCallback.clearVoiceSessionLocked();
3718 // TODO: VI Should this terminate the voice session?
3719 }
3720 }
3721
3722 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3723 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3724 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3725 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3726 boolean wasRunningVoice = mRunningVoice != null;
3727 mRunningVoice = session;
3728 if (!wasRunningVoice) {
3729 mVoiceWakeLock.acquire();
3730 updateSleepIfNeededLocked();
3731 }
3732 }
3733 }
3734
3735 void finishRunningVoiceLocked() {
3736 if (mRunningVoice != null) {
3737 mRunningVoice = null;
3738 mVoiceWakeLock.release();
3739 updateSleepIfNeededLocked();
3740 }
3741 }
3742
3743 @Override
3744 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3745 synchronized (mGlobalLock) {
3746 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3747 if (keepAwake) {
3748 mVoiceWakeLock.acquire();
3749 } else {
3750 mVoiceWakeLock.release();
3751 }
3752 }
3753 }
3754 }
3755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003756 @Override
3757 public ComponentName getActivityClassForToken(IBinder token) {
3758 synchronized (mGlobalLock) {
3759 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3760 if (r == null) {
3761 return null;
3762 }
3763 return r.intent.getComponent();
3764 }
3765 }
3766
3767 @Override
3768 public String getPackageForToken(IBinder token) {
3769 synchronized (mGlobalLock) {
3770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3771 if (r == null) {
3772 return null;
3773 }
3774 return r.packageName;
3775 }
3776 }
3777
3778 @Override
3779 public void showLockTaskEscapeMessage(IBinder token) {
3780 synchronized (mGlobalLock) {
3781 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3782 if (r == null) {
3783 return;
3784 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003785 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 }
3787 }
3788
3789 @Override
3790 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 final long token = Binder.clearCallingIdentity();
3793 try {
3794 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003795 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 }
3797 } finally {
3798 Binder.restoreCallingIdentity(token);
3799 }
3800 }
3801
3802 /**
3803 * Try to place task to provided position. The final position might be different depending on
3804 * current user and stacks state. The task will be moved to target stack if it's currently in
3805 * different stack.
3806 */
3807 @Override
3808 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003809 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 synchronized (mGlobalLock) {
3811 long ident = Binder.clearCallingIdentity();
3812 try {
3813 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3814 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003815 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 if (task == null) {
3817 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3818 + taskId);
3819 }
3820
Wale Ogunwaled32da472018-11-16 07:19:28 -08003821 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822
3823 if (stack == null) {
3824 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3825 + stackId);
3826 }
3827 if (!stack.isActivityTypeStandardOrUndefined()) {
3828 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3829 + " the position of task " + taskId + " in/to non-standard stack");
3830 }
3831
3832 // TODO: Have the callers of this API call a separate reparent method if that is
3833 // what they intended to do vs. having this method also do reparenting.
3834 if (task.getStack() == stack) {
3835 // Change position in current stack.
3836 stack.positionChildAt(task, position);
3837 } else {
3838 // Reparent to new stack.
3839 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3840 !DEFER_RESUME, "positionTaskInStack");
3841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(ident);
3844 }
3845 }
3846 }
3847
3848 @Override
3849 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3850 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3851 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3852 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3853 synchronized (mGlobalLock) {
3854 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3855 if (record == null) {
3856 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3857 + "found for: " + token);
3858 }
3859 record.setSizeConfigurations(horizontalSizeConfiguration,
3860 verticalSizeConfigurations, smallestSizeConfigurations);
3861 }
3862 }
3863
3864 /**
3865 * Dismisses split-screen multi-window mode.
3866 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3867 */
3868 @Override
3869 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003870 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3872 final long ident = Binder.clearCallingIdentity();
3873 try {
3874 synchronized (mGlobalLock) {
3875 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003876 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003877 if (stack == null) {
3878 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3879 return;
3880 }
3881
3882 if (toTop) {
3883 // Caller wants the current split-screen primary stack to be the top stack after
3884 // it goes fullscreen, so move it to the front.
3885 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003886 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003887 // In this case the current split-screen primary stack shouldn't be the top
3888 // stack after it goes fullscreen, but it current has focus, so we move the
3889 // focus to the top-most split-screen secondary stack next to it.
3890 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3891 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3892 if (otherStack != null) {
3893 otherStack.moveToFront("dismissSplitScreenMode_other");
3894 }
3895 }
3896
Evan Rosky10475742018-09-05 19:02:48 -07003897 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 }
3899 } finally {
3900 Binder.restoreCallingIdentity(ident);
3901 }
3902 }
3903
3904 /**
3905 * Dismisses Pip
3906 * @param animate True if the dismissal should be animated.
3907 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3908 * default animation duration should be used.
3909 */
3910 @Override
3911 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003912 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 final long ident = Binder.clearCallingIdentity();
3914 try {
3915 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003916 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003917 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 if (stack == null) {
3919 Slog.w(TAG, "dismissPip: pinned stack not found.");
3920 return;
3921 }
3922 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3923 throw new IllegalArgumentException("Stack: " + stack
3924 + " doesn't support animated resize.");
3925 }
3926 if (animate) {
3927 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3928 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3929 } else {
3930 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3931 }
3932 }
3933 } finally {
3934 Binder.restoreCallingIdentity(ident);
3935 }
3936 }
3937
3938 @Override
3939 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003940 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 synchronized (mGlobalLock) {
3942 mSuppressResizeConfigChanges = suppress;
3943 }
3944 }
3945
3946 /**
3947 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3948 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3949 * activity and clearing the task at the same time.
3950 */
3951 @Override
3952 // TODO: API should just be about changing windowing modes...
3953 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003954 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 "moveTasksToFullscreenStack()");
3956 synchronized (mGlobalLock) {
3957 final long origId = Binder.clearCallingIdentity();
3958 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003959 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 if (stack != null){
3961 if (!stack.isActivityTypeStandardOrUndefined()) {
3962 throw new IllegalArgumentException(
3963 "You can't move tasks from non-standard stacks.");
3964 }
3965 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3966 }
3967 } finally {
3968 Binder.restoreCallingIdentity(origId);
3969 }
3970 }
3971 }
3972
3973 /**
3974 * Moves the top activity in the input stackId to the pinned stack.
3975 *
3976 * @param stackId Id of stack to move the top activity to pinned stack.
3977 * @param bounds Bounds to use for pinned stack.
3978 *
3979 * @return True if the top activity of the input stack was successfully moved to the pinned
3980 * stack.
3981 */
3982 @Override
3983 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003984 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 "moveTopActivityToPinnedStack()");
3986 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3989 + "Device doesn't support picture-in-picture mode");
3990 }
3991
3992 long ident = Binder.clearCallingIdentity();
3993 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003994 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 } finally {
3996 Binder.restoreCallingIdentity(ident);
3997 }
3998 }
3999 }
4000
4001 @Override
4002 public boolean isInMultiWindowMode(IBinder token) {
4003 final long origId = Binder.clearCallingIdentity();
4004 try {
4005 synchronized (mGlobalLock) {
4006 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4007 if (r == null) {
4008 return false;
4009 }
4010 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4011 return r.inMultiWindowMode();
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(origId);
4015 }
4016 }
4017
4018 @Override
4019 public boolean isInPictureInPictureMode(IBinder token) {
4020 final long origId = Binder.clearCallingIdentity();
4021 try {
4022 synchronized (mGlobalLock) {
4023 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4024 }
4025 } finally {
4026 Binder.restoreCallingIdentity(origId);
4027 }
4028 }
4029
4030 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004031 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4032 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 return false;
4034 }
4035
4036 // If we are animating to fullscreen then we have already dispatched the PIP mode
4037 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004038 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4039 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 }
4041
4042 @Override
4043 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4044 final long origId = Binder.clearCallingIdentity();
4045 try {
4046 synchronized (mGlobalLock) {
4047 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4048 "enterPictureInPictureMode", token, params);
4049
4050 // If the activity is already in picture in picture mode, then just return early
4051 if (isInPictureInPictureMode(r)) {
4052 return true;
4053 }
4054
4055 // Activity supports picture-in-picture, now check that we can enter PiP at this
4056 // point, if it is
4057 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4058 false /* beforeStopping */)) {
4059 return false;
4060 }
4061
4062 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004063 synchronized (mGlobalLock) {
4064 // Only update the saved args from the args that are set
4065 r.pictureInPictureArgs.copyOnlySet(params);
4066 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4067 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4068 // Adjust the source bounds by the insets for the transition down
4069 final Rect sourceBounds = new Rect(
4070 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004071 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004072 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004073 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004074 stack.setPictureInPictureAspectRatio(aspectRatio);
4075 stack.setPictureInPictureActions(actions);
4076 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4077 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4078 logPictureInPictureArgs(params);
4079 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 };
4081
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004082 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 // If the keyguard is showing or occluded, then try and dismiss it before
4084 // entering picture-in-picture (this will prompt the user to authenticate if the
4085 // device is currently locked).
4086 dismissKeyguard(token, new KeyguardDismissCallback() {
4087 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004088 public void onDismissSucceeded() {
4089 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 }
4091 }, null /* message */);
4092 } else {
4093 // Enter picture in picture immediately otherwise
4094 enterPipRunnable.run();
4095 }
4096 return true;
4097 }
4098 } finally {
4099 Binder.restoreCallingIdentity(origId);
4100 }
4101 }
4102
4103 @Override
4104 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4105 final long origId = Binder.clearCallingIdentity();
4106 try {
4107 synchronized (mGlobalLock) {
4108 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4109 "setPictureInPictureParams", token, params);
4110
4111 // Only update the saved args from the args that are set
4112 r.pictureInPictureArgs.copyOnlySet(params);
4113 if (r.inPinnedWindowingMode()) {
4114 // If the activity is already in picture-in-picture, update the pinned stack now
4115 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4116 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004117 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 if (!stack.isAnimatingBoundsToFullscreen()) {
4119 stack.setPictureInPictureAspectRatio(
4120 r.pictureInPictureArgs.getAspectRatio());
4121 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4122 }
4123 }
4124 logPictureInPictureArgs(params);
4125 }
4126 } finally {
4127 Binder.restoreCallingIdentity(origId);
4128 }
4129 }
4130
4131 @Override
4132 public int getMaxNumPictureInPictureActions(IBinder token) {
4133 // Currently, this is a static constant, but later, we may change this to be dependent on
4134 // the context of the activity
4135 return 3;
4136 }
4137
4138 private void logPictureInPictureArgs(PictureInPictureParams params) {
4139 if (params.hasSetActions()) {
4140 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4141 params.getActions().size());
4142 }
4143 if (params.hasSetAspectRatio()) {
4144 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4145 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4146 MetricsLogger.action(lm);
4147 }
4148 }
4149
4150 /**
4151 * Checks the state of the system and the activity associated with the given {@param token} to
4152 * verify that picture-in-picture is supported for that activity.
4153 *
4154 * @return the activity record for the given {@param token} if all the checks pass.
4155 */
4156 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4157 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 throw new IllegalStateException(caller
4160 + ": Device doesn't support picture-in-picture mode.");
4161 }
4162
4163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4164 if (r == null) {
4165 throw new IllegalStateException(caller
4166 + ": Can't find activity for token=" + token);
4167 }
4168
4169 if (!r.supportsPictureInPicture()) {
4170 throw new IllegalStateException(caller
4171 + ": Current activity does not support picture-in-picture.");
4172 }
4173
4174 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004175 && !mWindowManager.isValidPictureInPictureAspectRatio(
4176 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 final float minAspectRatio = mContext.getResources().getFloat(
4178 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4179 final float maxAspectRatio = mContext.getResources().getFloat(
4180 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4181 throw new IllegalArgumentException(String.format(caller
4182 + ": Aspect ratio is too extreme (must be between %f and %f).",
4183 minAspectRatio, maxAspectRatio));
4184 }
4185
4186 // Truncate the number of actions if necessary
4187 params.truncateActions(getMaxNumPictureInPictureActions(token));
4188
4189 return r;
4190 }
4191
4192 @Override
4193 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 synchronized (mGlobalLock) {
4196 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4197 if (r == null) {
4198 throw new IllegalArgumentException("Activity does not exist; token="
4199 + activityToken);
4200 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004201 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 }
4203 }
4204
4205 @Override
4206 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4207 Rect tempDockedTaskInsetBounds,
4208 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004209 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 long ident = Binder.clearCallingIdentity();
4211 try {
4212 synchronized (mGlobalLock) {
4213 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4214 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4215 PRESERVE_WINDOWS);
4216 }
4217 } finally {
4218 Binder.restoreCallingIdentity(ident);
4219 }
4220 }
4221
4222 @Override
4223 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004224 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 final long ident = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
4228 mStackSupervisor.setSplitScreenResizing(resizing);
4229 }
4230 } finally {
4231 Binder.restoreCallingIdentity(ident);
4232 }
4233 }
4234
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 /**
4236 * Check that we have the features required for VR-related API calls, and throw an exception if
4237 * not.
4238 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004239 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 if (!mContext.getPackageManager().hasSystemFeature(
4241 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4242 throw new UnsupportedOperationException("VR mode not supported on this device!");
4243 }
4244 }
4245
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 @Override
4247 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249
4250 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4251
4252 ActivityRecord r;
4253 synchronized (mGlobalLock) {
4254 r = ActivityRecord.isInStackLocked(token);
4255 }
4256
4257 if (r == null) {
4258 throw new IllegalArgumentException();
4259 }
4260
4261 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004262 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 VrManagerInternal.NO_ERROR) {
4264 return err;
4265 }
4266
4267 // Clear the binder calling uid since this path may call moveToTask().
4268 final long callingId = Binder.clearCallingIdentity();
4269 try {
4270 synchronized (mGlobalLock) {
4271 r.requestedVrComponent = (enabled) ? packageName : null;
4272
4273 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004274 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004275 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 }
4277 return 0;
4278 }
4279 } finally {
4280 Binder.restoreCallingIdentity(callingId);
4281 }
4282 }
4283
4284 @Override
4285 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4286 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4287 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004288 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4290 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4291 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004292 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 || activity.voiceSession != null) {
4294 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4295 return;
4296 }
4297 if (activity.pendingVoiceInteractionStart) {
4298 Slog.w(TAG, "Pending start of voice interaction already.");
4299 return;
4300 }
4301 activity.pendingVoiceInteractionStart = true;
4302 }
4303 LocalServices.getService(VoiceInteractionManagerInternal.class)
4304 .startLocalVoiceInteraction(callingActivity, options);
4305 }
4306
4307 @Override
4308 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4309 LocalServices.getService(VoiceInteractionManagerInternal.class)
4310 .stopLocalVoiceInteraction(callingActivity);
4311 }
4312
4313 @Override
4314 public boolean supportsLocalVoiceInteraction() {
4315 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4316 .supportsLocalVoiceInteraction();
4317 }
4318
4319 /** Notifies all listeners when the pinned stack animation starts. */
4320 @Override
4321 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324
4325 /** Notifies all listeners when the pinned stack animation ends. */
4326 @Override
4327 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004328 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 }
4330
4331 @Override
4332 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004333 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 final long ident = Binder.clearCallingIdentity();
4335 try {
4336 synchronized (mGlobalLock) {
4337 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4338 }
4339 } finally {
4340 Binder.restoreCallingIdentity(ident);
4341 }
4342 }
4343
4344 @Override
4345 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347
4348 synchronized (mGlobalLock) {
4349 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004350 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 // Call might come when display is not yet added or has already been removed.
4352 if (DEBUG_CONFIGURATION) {
4353 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4354 + displayId);
4355 }
4356 return false;
4357 }
4358
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004361 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004364 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004365 final Message msg = PooledLambda.obtainMessage(
4366 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4367 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
4369
4370 final long origId = Binder.clearCallingIdentity();
4371 try {
4372 if (values != null) {
4373 Settings.System.clearConfiguration(values);
4374 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4377 return mTmpUpdateConfigurationResult.changes != 0;
4378 } finally {
4379 Binder.restoreCallingIdentity(origId);
4380 }
4381 }
4382 }
4383
4384 @Override
4385 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387
4388 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 }
4393
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004394 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004395 final Message msg = PooledLambda.obtainMessage(
4396 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4397 DEFAULT_DISPLAY);
4398 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 }
4400
4401 final long origId = Binder.clearCallingIdentity();
4402 try {
4403 if (values != null) {
4404 Settings.System.clearConfiguration(values);
4405 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 UserHandle.USER_NULL, false /* deferResume */,
4408 mTmpUpdateConfigurationResult);
4409 return mTmpUpdateConfigurationResult.changes != 0;
4410 } finally {
4411 Binder.restoreCallingIdentity(origId);
4412 }
4413 }
4414 }
4415
4416 @Override
4417 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4418 CharSequence message) {
4419 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4422 }
4423 final long callingId = Binder.clearCallingIdentity();
4424 try {
4425 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004426 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 }
4428 } finally {
4429 Binder.restoreCallingIdentity(callingId);
4430 }
4431 }
4432
4433 @Override
4434 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 "cancelTaskWindowTransition()");
4437 final long ident = Binder.clearCallingIdentity();
4438 try {
4439 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004440 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 MATCH_TASK_IN_STACKS_ONLY);
4442 if (task == null) {
4443 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4444 return;
4445 }
4446 task.cancelWindowTransition();
4447 }
4448 } finally {
4449 Binder.restoreCallingIdentity(ident);
4450 }
4451 }
4452
4453 @Override
4454 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 final long ident = Binder.clearCallingIdentity();
4457 try {
4458 final TaskRecord task;
4459 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004460 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4462 if (task == null) {
4463 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4464 return null;
4465 }
4466 }
4467 // Don't call this while holding the lock as this operation might hit the disk.
4468 return task.getSnapshot(reducedResolution);
4469 } finally {
4470 Binder.restoreCallingIdentity(ident);
4471 }
4472 }
4473
4474 @Override
4475 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4476 synchronized (mGlobalLock) {
4477 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4478 if (r == null) {
4479 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4480 + token);
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 r.setDisablePreviewScreenshots(disable);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
4492 /** Return the user id of the last resumed activity. */
4493 @Override
4494 public @UserIdInt
4495 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004499 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004502 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 }
4504 }
4505
4506 @Override
4507 public void updateLockTaskFeatures(int userId, int flags) {
4508 final int callingUid = Binder.getCallingUid();
4509 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 "updateLockTaskFeatures()");
4512 }
4513 synchronized (mGlobalLock) {
4514 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4515 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004516 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setShowWhenLocked(showWhenLocked);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
4536 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004537 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 return;
4542 }
4543 final long origId = Binder.clearCallingIdentity();
4544 try {
4545 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4546 } finally {
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549 }
4550 }
4551
4552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4554 synchronized (mGlobalLock) {
4555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4556 if (r == null) {
4557 return;
4558 }
4559 final long origId = Binder.clearCallingIdentity();
4560 try {
4561 r.setTurnScreenOn(turnScreenOn);
4562 } finally {
4563 Binder.restoreCallingIdentity(origId);
4564 }
4565 }
4566 }
4567
4568 @Override
4569 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "registerRemoteAnimations");
4572 definition.setCallingPid(Binder.getCallingPid());
4573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.registerRemoteAnimations(definition);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void registerRemoteAnimationForNextActivityStart(String packageName,
4589 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "registerRemoteAnimationForNextActivityStart");
4592 adapter.setCallingPid(Binder.getCallingPid());
4593 synchronized (mGlobalLock) {
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004596 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 packageName, adapter);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
Evan Rosky966759f2019-01-15 10:33:58 -08004604 @Override
4605 public void registerRemoteAnimationsForDisplay(int displayId,
4606 RemoteAnimationDefinition definition) {
4607 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4608 "registerRemoteAnimations");
4609 definition.setCallingPid(Binder.getCallingPid());
4610 synchronized (mGlobalLock) {
4611 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4612 if (display == null) {
4613 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 display.mDisplayContent.registerRemoteAnimations(definition);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4626 @Override
4627 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4628 synchronized (mGlobalLock) {
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004631 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004637
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004638 @Override
4639 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004642 final int pid = Binder.getCallingPid();
4643 final WindowProcessController wpc = mPidMap.get(pid);
4644 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 }
4646 }
4647
4648 @Override
4649 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 != PERMISSION_GRANTED) {
4652 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4653 + Binder.getCallingPid()
4654 + ", uid=" + Binder.getCallingUid()
4655 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4656 Slog.w(TAG, msg);
4657 throw new SecurityException(msg);
4658 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004661 final int pid = Binder.getCallingPid();
4662 final WindowProcessController proc = mPidMap.get(pid);
4663 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 }
4665 }
4666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004667 @Override
4668 public void stopAppSwitches() {
4669 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4670 synchronized (mGlobalLock) {
4671 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4672 mDidAppSwitch = false;
4673 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4674 }
4675 }
4676
4677 @Override
4678 public void resumeAppSwitches() {
4679 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4680 synchronized (mGlobalLock) {
4681 // Note that we don't execute any pending app switches... we will
4682 // let those wait until either the timeout, or the next start
4683 // activity request.
4684 mAppSwitchesAllowedTime = 0;
4685 }
4686 }
4687
4688 void onStartActivitySetDidAppSwitch() {
4689 if (mDidAppSwitch) {
4690 // This is the second allowed switch since we stopped switches, so now just generally
4691 // allow switches. Use case:
4692 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4693 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4694 // anyone to switch again).
4695 mAppSwitchesAllowedTime = 0;
4696 } else {
4697 mDidAppSwitch = true;
4698 }
4699 }
4700
4701 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 boolean shouldDisableNonVrUiLocked() {
4703 return mVrController.shouldDisableNonVrUiLocked();
4704 }
4705
Wale Ogunwale53783742018-09-16 10:21:51 -07004706 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 // VR apps are expected to run in a main display. If an app is turning on VR for
4708 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4709 // fullscreen stack before enabling VR Mode.
4710 // TODO: The goal of this code is to keep the VR app on the main display. When the
4711 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4712 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4713 // option would be a better choice here.
4714 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4715 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4716 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004717 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004719 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 }
4721 mH.post(() -> {
4722 if (!mVrController.onVrModeChanged(r)) {
4723 return;
4724 }
4725 synchronized (mGlobalLock) {
4726 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4727 mWindowManager.disableNonVrUi(disableNonVrUi);
4728 if (disableNonVrUi) {
4729 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4730 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004731 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734 });
4735 }
4736
Wale Ogunwale53783742018-09-16 10:21:51 -07004737 @Override
4738 public int getPackageScreenCompatMode(String packageName) {
4739 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4740 synchronized (mGlobalLock) {
4741 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4742 }
4743 }
4744
4745 @Override
4746 public void setPackageScreenCompatMode(String packageName, int mode) {
4747 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4748 "setPackageScreenCompatMode");
4749 synchronized (mGlobalLock) {
4750 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4751 }
4752 }
4753
4754 @Override
4755 public boolean getPackageAskScreenCompat(String packageName) {
4756 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4757 synchronized (mGlobalLock) {
4758 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4759 }
4760 }
4761
4762 @Override
4763 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4764 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4765 "setPackageAskScreenCompat");
4766 synchronized (mGlobalLock) {
4767 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4768 }
4769 }
4770
Wale Ogunwale64258362018-10-16 15:13:37 -07004771 public static String relaunchReasonToString(int relaunchReason) {
4772 switch (relaunchReason) {
4773 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4774 return "window_resize";
4775 case RELAUNCH_REASON_FREE_RESIZE:
4776 return "free_resize";
4777 default:
4778 return null;
4779 }
4780 }
4781
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004782 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004783 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 }
4785
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 /** Pokes the task persister. */
4787 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4788 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4789 }
4790
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 boolean isKeyguardLocked() {
4792 return mKeyguardController.isKeyguardLocked();
4793 }
4794
Garfield Tan01548632018-11-27 10:15:48 -08004795 /**
4796 * Clears launch params for the given package.
4797 * @param packageNames the names of the packages of which the launch params are to be cleared
4798 */
4799 @Override
4800 public void clearLaunchParamsForPackages(List<String> packageNames) {
4801 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4802 "clearLaunchParamsForPackages");
4803 synchronized (mGlobalLock) {
4804 for (int i = 0; i < packageNames.size(); ++i) {
4805 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4806 }
4807 }
4808 }
4809
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004810 /**
4811 * Makes the display with the given id a single task instance display. I.e the display can only
4812 * contain one task.
4813 */
4814 @Override
4815 public void setDisplayToSingleTaskInstance(int displayId) {
4816 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4817 "setDisplayToSingleTaskInstance");
4818 final long origId = Binder.clearCallingIdentity();
4819 try {
4820 final ActivityDisplay display =
4821 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4822 if (display != null) {
4823 display.setDisplayToSingleTaskInstance();
4824 }
4825 } finally {
4826 Binder.restoreCallingIdentity(origId);
4827 }
4828 }
4829
Wale Ogunwale31913b52018-10-13 08:29:31 -07004830 void dumpLastANRLocked(PrintWriter pw) {
4831 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4832 if (mLastANRState == null) {
4833 pw.println(" <no ANR has occurred since boot>");
4834 } else {
4835 pw.println(mLastANRState);
4836 }
4837 }
4838
4839 void dumpLastANRTracesLocked(PrintWriter pw) {
4840 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4841
4842 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4843 if (ArrayUtils.isEmpty(files)) {
4844 pw.println(" <no ANR has occurred since boot>");
4845 return;
4846 }
4847 // Find the latest file.
4848 File latest = null;
4849 for (File f : files) {
4850 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4851 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004853 }
4854 pw.print("File: ");
4855 pw.print(latest.getName());
4856 pw.println();
4857 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4858 String line;
4859 while ((line = in.readLine()) != null) {
4860 pw.println(line);
4861 }
4862 } catch (IOException e) {
4863 pw.print("Unable to read: ");
4864 pw.print(e);
4865 pw.println();
4866 }
4867 }
4868
4869 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4870 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4871 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4872 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4873 }
4874
4875 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4876 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4877 pw.println(header);
4878
Wale Ogunwaled32da472018-11-16 07:19:28 -08004879 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004880 dumpPackage);
4881 boolean needSep = printedAnything;
4882
4883 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004884 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004885 " ResumedActivity: ");
4886 if (printed) {
4887 printedAnything = true;
4888 needSep = false;
4889 }
4890
4891 if (dumpPackage == null) {
4892 if (needSep) {
4893 pw.println();
4894 }
4895 printedAnything = true;
4896 mStackSupervisor.dump(pw, " ");
4897 }
4898
4899 if (!printedAnything) {
4900 pw.println(" (nothing)");
4901 }
4902 }
4903
4904 void dumpActivityContainersLocked(PrintWriter pw) {
4905 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004906 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004907 pw.println(" ");
4908 }
4909
4910 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4911 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4912 getActivityStartController().dump(pw, "", dumpPackage);
4913 }
4914
4915 /**
4916 * There are three things that cmd can be:
4917 * - a flattened component name that matches an existing activity
4918 * - the cmd arg isn't the flattened component name of an existing activity:
4919 * dump all activity whose component contains the cmd as a substring
4920 * - A hex number of the ActivityRecord object instance.
4921 *
4922 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4923 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4924 */
4925 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4926 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4927 ArrayList<ActivityRecord> activities;
4928
4929 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004930 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 dumpFocusedStackOnly);
4932 }
4933
4934 if (activities.size() <= 0) {
4935 return false;
4936 }
4937
4938 String[] newArgs = new String[args.length - opti];
4939 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4940
4941 TaskRecord lastTask = null;
4942 boolean needSep = false;
4943 for (int i = activities.size() - 1; i >= 0; i--) {
4944 ActivityRecord r = activities.get(i);
4945 if (needSep) {
4946 pw.println();
4947 }
4948 needSep = true;
4949 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004951 if (lastTask != task) {
4952 lastTask = task;
4953 pw.print("TASK "); pw.print(lastTask.affinity);
4954 pw.print(" id="); pw.print(lastTask.taskId);
4955 pw.print(" userId="); pw.println(lastTask.userId);
4956 if (dumpAll) {
4957 lastTask.dump(pw, " ");
4958 }
4959 }
4960 }
4961 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4962 }
4963 return true;
4964 }
4965
4966 /**
4967 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4968 * there is a thread associated with the activity.
4969 */
4970 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4971 final ActivityRecord r, String[] args, boolean dumpAll) {
4972 String innerPrefix = prefix + " ";
4973 synchronized (mGlobalLock) {
4974 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4975 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4976 pw.print(" pid=");
4977 if (r.hasProcess()) pw.println(r.app.getPid());
4978 else pw.println("(not running)");
4979 if (dumpAll) {
4980 r.dump(pw, innerPrefix);
4981 }
4982 }
4983 if (r.attachedToProcess()) {
4984 // flush anything that is already in the PrintWriter since the thread is going
4985 // to write to the file descriptor directly
4986 pw.flush();
4987 try {
4988 TransferPipe tp = new TransferPipe();
4989 try {
4990 r.app.getThread().dumpActivity(tp.getWriteFd(),
4991 r.appToken, innerPrefix, args);
4992 tp.go(fd);
4993 } finally {
4994 tp.kill();
4995 }
4996 } catch (IOException e) {
4997 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4998 } catch (RemoteException e) {
4999 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5000 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005002 }
5003
sanryhuang498e77e2018-12-06 14:57:01 +08005004 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5005 boolean testPssMode) {
5006 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5007 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5008 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005009 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005010 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5011 st.toString());
5012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005013 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5015 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005016 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5017 testPssMode);
5018 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005019 }
5020
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005021 int getCurrentUserId() {
5022 return mAmInternal.getCurrentUserId();
5023 }
5024
5025 private void enforceNotIsolatedCaller(String caller) {
5026 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5027 throw new SecurityException("Isolated process not allowed to call " + caller);
5028 }
5029 }
5030
Wale Ogunwalef6733932018-06-27 05:14:34 -07005031 public Configuration getConfiguration() {
5032 Configuration ci;
5033 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005034 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005035 ci.userSetLocale = false;
5036 }
5037 return ci;
5038 }
5039
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040 /**
5041 * Current global configuration information. Contains general settings for the entire system,
5042 * also corresponds to the merged configuration of the default display.
5043 */
5044 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005045 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046 }
5047
5048 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5049 boolean initLocale) {
5050 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5051 }
5052
5053 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5054 boolean initLocale, boolean deferResume) {
5055 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5056 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5057 UserHandle.USER_NULL, deferResume);
5058 }
5059
Wale Ogunwale59507092018-10-29 09:00:30 -07005060 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 final long origId = Binder.clearCallingIdentity();
5062 try {
5063 synchronized (mGlobalLock) {
5064 updateConfigurationLocked(values, null, false, true, userId,
5065 false /* deferResume */);
5066 }
5067 } finally {
5068 Binder.restoreCallingIdentity(origId);
5069 }
5070 }
5071
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5073 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5074 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5075 deferResume, null /* result */);
5076 }
5077
5078 /**
5079 * Do either or both things: (1) change the current configuration, and (2)
5080 * make sure the given activity is running with the (now) current
5081 * configuration. Returns true if the activity has been left running, or
5082 * false if <var>starting</var> is being destroyed to match the new
5083 * configuration.
5084 *
5085 * @param userId is only used when persistent parameter is set to true to persist configuration
5086 * for that particular user
5087 */
5088 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5089 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5090 ActivityTaskManagerService.UpdateConfigurationResult result) {
5091 int changes = 0;
5092 boolean kept = true;
5093
5094 if (mWindowManager != null) {
5095 mWindowManager.deferSurfaceLayout();
5096 }
5097 try {
5098 if (values != null) {
5099 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5100 deferResume);
5101 }
5102
5103 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5104 } finally {
5105 if (mWindowManager != null) {
5106 mWindowManager.continueSurfaceLayout();
5107 }
5108 }
5109
5110 if (result != null) {
5111 result.changes = changes;
5112 result.activityRelaunched = !kept;
5113 }
5114 return kept;
5115 }
5116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005117 /** Update default (global) configuration and notify listeners about changes. */
5118 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5119 boolean persistent, int userId, boolean deferResume) {
5120 mTempConfig.setTo(getGlobalConfiguration());
5121 final int changes = mTempConfig.updateFrom(values);
5122 if (changes == 0) {
5123 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5124 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5125 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5126 // (even if there are no actual changes) to unfreeze the window.
5127 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5128 return 0;
5129 }
5130
5131 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5132 "Updating global configuration to: " + values);
5133
5134 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5135 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5136 values.colorMode,
5137 values.densityDpi,
5138 values.fontScale,
5139 values.hardKeyboardHidden,
5140 values.keyboard,
5141 values.keyboardHidden,
5142 values.mcc,
5143 values.mnc,
5144 values.navigation,
5145 values.navigationHidden,
5146 values.orientation,
5147 values.screenHeightDp,
5148 values.screenLayout,
5149 values.screenWidthDp,
5150 values.smallestScreenWidthDp,
5151 values.touchscreen,
5152 values.uiMode);
5153
5154
5155 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5156 final LocaleList locales = values.getLocales();
5157 int bestLocaleIndex = 0;
5158 if (locales.size() > 1) {
5159 if (mSupportedSystemLocales == null) {
5160 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5161 }
5162 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5163 }
5164 SystemProperties.set("persist.sys.locale",
5165 locales.get(bestLocaleIndex).toLanguageTag());
5166 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005167
5168 final Message m = PooledLambda.obtainMessage(
5169 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5170 locales.get(bestLocaleIndex));
5171 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 }
5173
Yunfan Chen75157d72018-07-27 14:47:21 +09005174 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175
5176 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005177 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178
5179 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5180 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005181 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182
5183 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005184 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185
5186 AttributeCache ac = AttributeCache.instance();
5187 if (ac != null) {
5188 ac.updateConfiguration(mTempConfig);
5189 }
5190
5191 // Make sure all resources in our process are updated right now, so that anyone who is going
5192 // to retrieve resource values after we return will be sure to get the new ones. This is
5193 // especially important during boot, where the first config change needs to guarantee all
5194 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005195 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 // We need another copy of global config because we're scheduling some calls instead of
5198 // running them in place. We need to be sure that object we send will be handled unchanged.
5199 final Configuration configCopy = new Configuration(mTempConfig);
5200 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005201 final Message msg = PooledLambda.obtainMessage(
5202 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5203 this, userId, configCopy);
5204 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 }
5206
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005207 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005208 final int pid = mPidMap.keyAt(i);
5209 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005210 if (DEBUG_CONFIGURATION) {
5211 Slog.v(TAG_CONFIGURATION, "Update process config of "
5212 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005214 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 }
5216
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005217 final Message msg = PooledLambda.obtainMessage(
5218 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5219 mAmInternal, changes, initLocale);
5220 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221
5222 // Override configuration of the default display duplicates global config, so we need to
5223 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005224 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 DEFAULT_DISPLAY);
5226
5227 return changes;
5228 }
5229
5230 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5231 boolean deferResume, int displayId) {
5232 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5233 displayId, null /* result */);
5234 }
5235
5236 /**
5237 * Updates override configuration specific for the selected display. If no config is provided,
5238 * new one will be computed in WM based on current display info.
5239 */
5240 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5241 ActivityRecord starting, boolean deferResume, int displayId,
5242 ActivityTaskManagerService.UpdateConfigurationResult result) {
5243 int changes = 0;
5244 boolean kept = true;
5245
5246 if (mWindowManager != null) {
5247 mWindowManager.deferSurfaceLayout();
5248 }
5249 try {
5250 if (values != null) {
5251 if (displayId == DEFAULT_DISPLAY) {
5252 // Override configuration of the default display duplicates global config, so
5253 // we're calling global config update instead for default display. It will also
5254 // apply the correct override config.
5255 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5256 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5257 } else {
5258 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5259 }
5260 }
5261
5262 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5263 } finally {
5264 if (mWindowManager != null) {
5265 mWindowManager.continueSurfaceLayout();
5266 }
5267 }
5268
5269 if (result != null) {
5270 result.changes = changes;
5271 result.activityRelaunched = !kept;
5272 }
5273 return kept;
5274 }
5275
5276 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5277 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005278 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005279 final int changes = mTempConfig.updateFrom(values);
5280 if (changes != 0) {
5281 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5282 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005283 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284
5285 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5286 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005287 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288
Wale Ogunwale5c918702018-10-18 11:06:33 -07005289 // Post message to start process to avoid possible deadlock of calling into AMS with
5290 // the ATMS lock held.
5291 final Message msg = PooledLambda.obtainMessage(
5292 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005293 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005294 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005295 }
5296 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297 return changes;
5298 }
5299
Wale Ogunwalef6733932018-06-27 05:14:34 -07005300 private void updateEventDispatchingLocked(boolean booted) {
5301 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5302 }
5303
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005304 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5305 final ContentResolver resolver = mContext.getContentResolver();
5306 Settings.System.putConfigurationForUser(resolver, config, userId);
5307 }
5308
5309 private void sendLocaleToMountDaemonMsg(Locale l) {
5310 try {
5311 IBinder service = ServiceManager.getService("mount");
5312 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5313 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5314 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5315 } catch (RemoteException e) {
5316 Log.e(TAG, "Error storing locale for decryption UI", e);
5317 }
5318 }
5319
Alison Cichowlas3e340502018-08-07 17:15:01 -04005320 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5321 mStartActivitySources.remove(permissionToken);
5322 mExpiredStartAsCallerTokens.add(permissionToken);
5323 }
5324
5325 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5326 mExpiredStartAsCallerTokens.remove(permissionToken);
5327 }
5328
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005329 boolean isActivityStartsLoggingEnabled() {
5330 return mAmInternal.isActivityStartsLoggingEnabled();
5331 }
5332
Michal Karpinski8596ded2018-11-14 14:43:48 +00005333 boolean isBackgroundActivityStartsEnabled() {
5334 return mAmInternal.isBackgroundActivityStartsEnabled();
5335 }
5336
Ricky Waiaca8a772019-04-04 16:01:06 +01005337 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5338 if (packageName == null) {
5339 return false;
5340 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005341 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5342 }
5343
Wale Ogunwalef6733932018-06-27 05:14:34 -07005344 void enableScreenAfterBoot(boolean booted) {
5345 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5346 SystemClock.uptimeMillis());
5347 mWindowManager.enableScreenAfterBoot();
5348
5349 synchronized (mGlobalLock) {
5350 updateEventDispatchingLocked(booted);
5351 }
5352 }
5353
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005354 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5355 if (r == null || !r.hasProcess()) {
5356 return KEY_DISPATCHING_TIMEOUT_MS;
5357 }
5358 return getInputDispatchingTimeoutLocked(r.app);
5359 }
5360
5361 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005362 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005363 }
5364
Wale Ogunwalef6733932018-06-27 05:14:34 -07005365 /**
5366 * Decide based on the configuration whether we should show the ANR,
5367 * crash, etc dialogs. The idea is that if there is no affordance to
5368 * press the on-screen buttons, or the user experience would be more
5369 * greatly impacted than the crash itself, we shouldn't show the dialog.
5370 *
5371 * A thought: SystemUI might also want to get told about this, the Power
5372 * dialog / global actions also might want different behaviors.
5373 */
5374 private void updateShouldShowDialogsLocked(Configuration config) {
5375 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5376 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5377 && config.navigation == Configuration.NAVIGATION_NONAV);
5378 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5379 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5380 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5381 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5382 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5383 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5384 HIDE_ERROR_DIALOGS, 0) != 0;
5385 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5386 }
5387
5388 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5389 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5390 FONT_SCALE, 1.0f, userId);
5391
5392 synchronized (this) {
5393 if (getGlobalConfiguration().fontScale == scaleFactor) {
5394 return;
5395 }
5396
5397 final Configuration configuration
5398 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5399 configuration.fontScale = scaleFactor;
5400 updatePersistentConfiguration(configuration, userId);
5401 }
5402 }
5403
5404 // Actually is sleeping or shutting down or whatever else in the future
5405 // is an inactive state.
5406 boolean isSleepingOrShuttingDownLocked() {
5407 return isSleepingLocked() || mShuttingDown;
5408 }
5409
5410 boolean isSleepingLocked() {
5411 return mSleeping;
5412 }
5413
Riddle Hsu16567132018-08-16 21:37:47 +08005414 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005416 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005417 if (task.isActivityTypeStandard()) {
5418 if (mCurAppTimeTracker != r.appTimeTracker) {
5419 // We are switching app tracking. Complete the current one.
5420 if (mCurAppTimeTracker != null) {
5421 mCurAppTimeTracker.stop();
5422 mH.obtainMessage(
5423 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005424 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005425 mCurAppTimeTracker = null;
5426 }
5427 if (r.appTimeTracker != null) {
5428 mCurAppTimeTracker = r.appTimeTracker;
5429 startTimeTrackingFocusedActivityLocked();
5430 }
5431 } else {
5432 startTimeTrackingFocusedActivityLocked();
5433 }
5434 } else {
5435 r.appTimeTracker = null;
5436 }
5437 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5438 // TODO: Probably not, because we don't want to resume voice on switching
5439 // back to this activity
5440 if (task.voiceInteractor != null) {
5441 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5442 } else {
5443 finishRunningVoiceLocked();
5444
5445 if (mLastResumedActivity != null) {
5446 final IVoiceInteractionSession session;
5447
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005448 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005449 if (lastResumedActivityTask != null
5450 && lastResumedActivityTask.voiceSession != null) {
5451 session = lastResumedActivityTask.voiceSession;
5452 } else {
5453 session = mLastResumedActivity.voiceSession;
5454 }
5455
5456 if (session != null) {
5457 // We had been in a voice interaction session, but now focused has
5458 // move to something different. Just finish the session, we can't
5459 // return to it and retain the proper state and synchronization with
5460 // the voice interaction service.
5461 finishVoiceTask(session);
5462 }
5463 }
5464 }
5465
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005466 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5467 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 }
5469 updateResumedAppTrace(r);
5470 mLastResumedActivity = r;
5471
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005472 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473
5474 applyUpdateLockStateLocked(r);
5475 applyUpdateVrModeLocked(r);
5476
5477 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005478 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479 r == null ? "NULL" : r.shortComponentName,
5480 reason);
5481 }
5482
5483 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5484 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005485 final ActivityTaskManagerInternal.SleepToken token =
5486 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005487 updateSleepIfNeededLocked();
5488 return token;
5489 }
5490 }
5491
5492 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005493 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 final boolean wasSleeping = mSleeping;
5495 boolean updateOomAdj = false;
5496
5497 if (!shouldSleep) {
5498 // If wasSleeping is true, we need to wake up activity manager state from when
5499 // we started sleeping. In either case, we need to apply the sleep tokens, which
5500 // will wake up stacks or put them to sleep as appropriate.
5501 if (wasSleeping) {
5502 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005503 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5504 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 startTimeTrackingFocusedActivityLocked();
5506 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5507 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5508 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005509 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005510 if (wasSleeping) {
5511 updateOomAdj = true;
5512 }
5513 } else if (!mSleeping && shouldSleep) {
5514 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005515 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5516 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (mCurAppTimeTracker != null) {
5518 mCurAppTimeTracker.stop();
5519 }
5520 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5521 mStackSupervisor.goingToSleepLocked();
5522 updateResumedAppTrace(null /* resumed */);
5523 updateOomAdj = true;
5524 }
5525 if (updateOomAdj) {
5526 mH.post(mAmInternal::updateOomAdj);
5527 }
5528 }
5529
5530 void updateOomAdj() {
5531 mH.post(mAmInternal::updateOomAdj);
5532 }
5533
Wale Ogunwale53783742018-09-16 10:21:51 -07005534 void updateCpuStats() {
5535 mH.post(mAmInternal::updateCpuStats);
5536 }
5537
Hui Yu03d12402018-12-06 18:00:37 -08005538 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5539 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005540 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5541 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005542 mH.sendMessage(m);
5543 }
5544
Hui Yu03d12402018-12-06 18:00:37 -08005545 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005546 ComponentName taskRoot = null;
5547 final TaskRecord task = activity.getTaskRecord();
5548 if (task != null) {
5549 final ActivityRecord rootActivity = task.getRootActivity();
5550 if (rootActivity != null) {
5551 taskRoot = rootActivity.mActivityComponent;
5552 }
5553 }
5554
Hui Yu03d12402018-12-06 18:00:37 -08005555 final Message m = PooledLambda.obtainMessage(
5556 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005557 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005558 mH.sendMessage(m);
5559 }
5560
Wale Ogunwale53783742018-09-16 10:21:51 -07005561 void setBooting(boolean booting) {
5562 mAmInternal.setBooting(booting);
5563 }
5564
5565 boolean isBooting() {
5566 return mAmInternal.isBooting();
5567 }
5568
5569 void setBooted(boolean booted) {
5570 mAmInternal.setBooted(booted);
5571 }
5572
5573 boolean isBooted() {
5574 return mAmInternal.isBooted();
5575 }
5576
5577 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5578 mH.post(() -> {
5579 if (finishBooting) {
5580 mAmInternal.finishBooting();
5581 }
5582 if (enableScreen) {
5583 mInternal.enableScreenAfterBoot(isBooted());
5584 }
5585 });
5586 }
5587
5588 void setHeavyWeightProcess(ActivityRecord root) {
5589 mHeavyWeightProcess = root.app;
5590 final Message m = PooledLambda.obtainMessage(
5591 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005592 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005593 mH.sendMessage(m);
5594 }
5595
5596 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5597 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5598 return;
5599 }
5600
5601 mHeavyWeightProcess = null;
5602 final Message m = PooledLambda.obtainMessage(
5603 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5604 proc.mUserId);
5605 mH.sendMessage(m);
5606 }
5607
5608 private void cancelHeavyWeightProcessNotification(int userId) {
5609 final INotificationManager inm = NotificationManager.getService();
5610 if (inm == null) {
5611 return;
5612 }
5613 try {
5614 inm.cancelNotificationWithTag("android", null,
5615 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5616 } catch (RuntimeException e) {
5617 Slog.w(TAG, "Error canceling notification for service", e);
5618 } catch (RemoteException e) {
5619 }
5620
5621 }
5622
5623 private void postHeavyWeightProcessNotification(
5624 WindowProcessController proc, Intent intent, int userId) {
5625 if (proc == null) {
5626 return;
5627 }
5628
5629 final INotificationManager inm = NotificationManager.getService();
5630 if (inm == null) {
5631 return;
5632 }
5633
5634 try {
5635 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5636 String text = mContext.getString(R.string.heavy_weight_notification,
5637 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5638 Notification notification =
5639 new Notification.Builder(context,
5640 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5641 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5642 .setWhen(0)
5643 .setOngoing(true)
5644 .setTicker(text)
5645 .setColor(mContext.getColor(
5646 com.android.internal.R.color.system_notification_accent_color))
5647 .setContentTitle(text)
5648 .setContentText(
5649 mContext.getText(R.string.heavy_weight_notification_detail))
5650 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5651 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5652 new UserHandle(userId)))
5653 .build();
5654 try {
5655 inm.enqueueNotificationWithTag("android", "android", null,
5656 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5657 } catch (RuntimeException e) {
5658 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5659 } catch (RemoteException e) {
5660 }
5661 } catch (PackageManager.NameNotFoundException e) {
5662 Slog.w(TAG, "Unable to create context for heavy notification", e);
5663 }
5664
5665 }
5666
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005667 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5668 IBinder token, String resultWho, int requestCode, Intent[] intents,
5669 String[] resolvedTypes, int flags, Bundle bOptions) {
5670
5671 ActivityRecord activity = null;
5672 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5673 activity = ActivityRecord.isInStackLocked(token);
5674 if (activity == null) {
5675 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5676 return null;
5677 }
5678 if (activity.finishing) {
5679 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5680 return null;
5681 }
5682 }
5683
5684 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5685 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5686 bOptions);
5687 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5688 if (noCreate) {
5689 return rec;
5690 }
5691 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5692 if (activity.pendingResults == null) {
5693 activity.pendingResults = new HashSet<>();
5694 }
5695 activity.pendingResults.add(rec.ref);
5696 }
5697 return rec;
5698 }
5699
Andrii Kulian52d255c2018-07-13 11:32:19 -07005700 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005701 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005702 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005703 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5704 mCurAppTimeTracker.start(resumedActivity.packageName);
5705 }
5706 }
5707
5708 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5709 if (mTracedResumedActivity != null) {
5710 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5711 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5712 }
5713 if (resumed != null) {
5714 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5715 constructResumedTraceName(resumed.packageName), 0);
5716 }
5717 mTracedResumedActivity = resumed;
5718 }
5719
5720 private String constructResumedTraceName(String packageName) {
5721 return "focused app: " + packageName;
5722 }
5723
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005724 /** Applies latest configuration and/or visibility updates if needed. */
5725 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5726 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005727 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005728 // mainStack is null during startup.
5729 if (mainStack != null) {
5730 if (changes != 0 && starting == null) {
5731 // If the configuration changed, and the caller is not already
5732 // in the process of starting an activity, then find the top
5733 // activity to check if its configuration needs to change.
5734 starting = mainStack.topRunningActivityLocked();
5735 }
5736
5737 if (starting != null) {
5738 kept = starting.ensureActivityConfiguration(changes,
5739 false /* preserveWindow */);
5740 // And we need to make sure at this point that all other activities
5741 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005742 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005743 !PRESERVE_WINDOWS);
5744 }
5745 }
5746
5747 return kept;
5748 }
5749
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005750 void scheduleAppGcsLocked() {
5751 mH.post(() -> mAmInternal.scheduleAppGcs());
5752 }
5753
Wale Ogunwale53783742018-09-16 10:21:51 -07005754 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5755 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5756 }
5757
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005758 /**
5759 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5760 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5761 * on demand.
5762 */
5763 IPackageManager getPackageManager() {
5764 return AppGlobals.getPackageManager();
5765 }
5766
5767 PackageManagerInternal getPackageManagerInternalLocked() {
5768 if (mPmInternal == null) {
5769 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5770 }
5771 return mPmInternal;
5772 }
5773
Wale Ogunwale008163e2018-07-23 23:11:08 -07005774 AppWarnings getAppWarningsLocked() {
5775 return mAppWarnings;
5776 }
5777
Wale Ogunwale214f3482018-10-04 11:00:47 -07005778 Intent getHomeIntent() {
5779 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5780 intent.setComponent(mTopComponent);
5781 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5782 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5783 intent.addCategory(Intent.CATEGORY_HOME);
5784 }
5785 return intent;
5786 }
5787
Chilun2ef71f72018-11-16 17:57:15 +08005788 /**
5789 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5790 * activities.
5791 *
5792 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5793 * component defined in config_secondaryHomeComponent.
5794 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5795 */
5796 Intent getSecondaryHomeIntent(String preferredPackage) {
5797 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5798 if (preferredPackage == null) {
5799 // Using the component stored in config if no package name.
5800 final String secondaryHomeComponent = mContext.getResources().getString(
5801 com.android.internal.R.string.config_secondaryHomeComponent);
5802 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5803 } else {
5804 intent.setPackage(preferredPackage);
5805 }
5806 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5807 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5808 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5809 }
5810 return intent;
5811 }
5812
Wale Ogunwale214f3482018-10-04 11:00:47 -07005813 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5814 if (info == null) return null;
5815 ApplicationInfo newInfo = new ApplicationInfo(info);
5816 newInfo.initForUser(userId);
5817 return newInfo;
5818 }
5819
Wale Ogunwale9c103022018-10-18 07:44:54 -07005820 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005821 if (uid == SYSTEM_UID) {
5822 // The system gets to run in any process. If there are multiple processes with the same
5823 // uid, just pick the first (this should never happen).
5824 final SparseArray<WindowProcessController> procs =
5825 mProcessNames.getMap().get(processName);
5826 if (procs == null) return null;
5827 final int procCount = procs.size();
5828 for (int i = 0; i < procCount; i++) {
5829 final int procUid = procs.keyAt(i);
5830 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5831 // Don't use an app process or different user process for system component.
5832 continue;
5833 }
5834 return procs.valueAt(i);
5835 }
5836 }
5837
5838 return mProcessNames.get(processName, uid);
5839 }
5840
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005841 WindowProcessController getProcessController(IApplicationThread thread) {
5842 if (thread == null) {
5843 return null;
5844 }
5845
5846 final IBinder threadBinder = thread.asBinder();
5847 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5848 for (int i = pmap.size()-1; i >= 0; i--) {
5849 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5850 for (int j = procs.size() - 1; j >= 0; j--) {
5851 final WindowProcessController proc = procs.valueAt(j);
5852 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5853 return proc;
5854 }
5855 }
5856 }
5857
5858 return null;
5859 }
5860
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005861 WindowProcessController getProcessController(int pid, int uid) {
Yunfan Chen8546b212019-04-01 15:34:44 +09005862 final WindowProcessController proc = mPidMap.get(pid);
5863 if (proc == null) return null;
5864 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5865 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005866 }
5867 return null;
5868 }
5869
Riddle Hsua0536432019-02-16 00:38:59 +08005870 int getUidState(int uid) {
5871 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005872 }
5873
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005874 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005875 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005876 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5877 }
5878
Ricky Wai96f5c352019-04-10 18:40:17 +01005879 boolean isDeviceOwner(int uid) {
5880 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005881 }
5882
Ricky Wai96f5c352019-04-10 18:40:17 +01005883 void setDeviceOwnerUid(int uid) {
5884 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005885 }
5886
Wale Ogunwale9de19442018-10-18 19:05:03 -07005887 /**
5888 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5889 * the whitelist
5890 */
5891 String getPendingTempWhitelistTagForUidLocked(int uid) {
5892 return mPendingTempWhitelist.get(uid);
5893 }
5894
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005895 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5896 if (true || Build.IS_USER) {
5897 return;
5898 }
5899
5900 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5901 StrictMode.allowThreadDiskWrites();
5902 try {
5903 File tracesDir = new File("/data/anr");
5904 File tracesFile = null;
5905 try {
5906 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5907
5908 StringBuilder sb = new StringBuilder();
5909 Time tobj = new Time();
5910 tobj.set(System.currentTimeMillis());
5911 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5912 sb.append(": ");
5913 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5914 sb.append(" since ");
5915 sb.append(msg);
5916 FileOutputStream fos = new FileOutputStream(tracesFile);
5917 fos.write(sb.toString().getBytes());
5918 if (app == null) {
5919 fos.write("\n*** No application process!".getBytes());
5920 }
5921 fos.close();
5922 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5923 } catch (IOException e) {
5924 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5925 return;
5926 }
5927
5928 if (app != null && app.getPid() > 0) {
5929 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5930 firstPids.add(app.getPid());
5931 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5932 }
5933
5934 File lastTracesFile = null;
5935 File curTracesFile = null;
5936 for (int i=9; i>=0; i--) {
5937 String name = String.format(Locale.US, "slow%02d.txt", i);
5938 curTracesFile = new File(tracesDir, name);
5939 if (curTracesFile.exists()) {
5940 if (lastTracesFile != null) {
5941 curTracesFile.renameTo(lastTracesFile);
5942 } else {
5943 curTracesFile.delete();
5944 }
5945 }
5946 lastTracesFile = curTracesFile;
5947 }
5948 tracesFile.renameTo(curTracesFile);
5949 } finally {
5950 StrictMode.setThreadPolicy(oldPolicy);
5951 }
5952 }
5953
Michal Karpinskida34cd42019-04-02 19:46:52 +01005954 boolean isAssociatedCompanionApp(int userId, int uid) {
5955 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5956 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005957 return false;
5958 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005959 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005960 }
5961
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005962 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005963 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005964
5965
Wale Ogunwale98875612018-10-12 07:53:02 -07005966 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5967 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005968
Riddle Hsud93a6c42018-11-29 21:50:06 +08005969 H(Looper looper) {
5970 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005971 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972
5973 @Override
5974 public void handleMessage(Message msg) {
5975 switch (msg.what) {
5976 case REPORT_TIME_TRACKER_MSG: {
5977 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5978 tracker.deliverResult(mContext);
5979 } break;
5980 }
5981 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005982 }
5983
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005984 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005985 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005986
5987 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005988 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005989 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005990
5991 @Override
5992 public void handleMessage(Message msg) {
5993 switch (msg.what) {
5994 case DISMISS_DIALOG_UI_MSG: {
5995 final Dialog d = (Dialog) msg.obj;
5996 d.dismiss();
5997 break;
5998 }
5999 }
6000 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006001 }
6002
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 final class LocalService extends ActivityTaskManagerInternal {
6004 @Override
6005 public SleepToken acquireSleepToken(String tag, int displayId) {
6006 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006007 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 }
6009
6010 @Override
6011 public ComponentName getHomeActivityForUser(int userId) {
6012 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006013 final ActivityRecord homeActivity =
6014 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006015 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006016 }
6017 }
6018
6019 @Override
6020 public void onLocalVoiceInteractionStarted(IBinder activity,
6021 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6022 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006023 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006024 }
6025 }
6026
6027 @Override
6028 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6029 synchronized (mGlobalLock) {
6030 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6031 reasons, timestamp);
6032 }
6033 }
6034
6035 @Override
6036 public void notifyAppTransitionFinished() {
6037 synchronized (mGlobalLock) {
6038 mStackSupervisor.notifyAppTransitionDone();
6039 }
6040 }
6041
6042 @Override
6043 public void notifyAppTransitionCancelled() {
6044 synchronized (mGlobalLock) {
6045 mStackSupervisor.notifyAppTransitionDone();
6046 }
6047 }
6048
6049 @Override
6050 public List<IBinder> getTopVisibleActivities() {
6051 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006052 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 }
6054 }
6055
6056 @Override
6057 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6058 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006059 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006060 }
6061 }
6062
6063 @Override
6064 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6065 Bundle bOptions) {
6066 Preconditions.checkNotNull(intents, "intents");
6067 final String[] resolvedTypes = new String[intents.length];
6068
6069 // UID of the package on user userId.
6070 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6071 // packageUid may not be initialized.
6072 int packageUid = 0;
6073 final long ident = Binder.clearCallingIdentity();
6074
6075 try {
6076 for (int i = 0; i < intents.length; i++) {
6077 resolvedTypes[i] =
6078 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6079 }
6080
6081 packageUid = AppGlobals.getPackageManager().getPackageUid(
6082 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6083 } catch (RemoteException e) {
6084 // Shouldn't happen.
6085 } finally {
6086 Binder.restoreCallingIdentity(ident);
6087 }
6088
Riddle Hsu591bf612019-02-14 17:55:31 +08006089 return getActivityStartController().startActivitiesInPackage(
6090 packageUid, packageName,
6091 intents, resolvedTypes, null /* resultTo */,
6092 SafeActivityOptions.fromBundle(bOptions), userId,
6093 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6094 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006095 }
6096
6097 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006098 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6099 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6100 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6101 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006102 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006103 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006104 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6105 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6106 userId, validateIncomingUser, originatingPendingIntent,
6107 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006108 }
6109 }
6110
6111 @Override
6112 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6113 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6114 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6115 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006116 PendingIntentRecord originatingPendingIntent,
6117 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006118 synchronized (mGlobalLock) {
6119 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6120 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6121 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006122 validateIncomingUser, originatingPendingIntent,
6123 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006124 }
6125 }
6126
6127 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6129 Intent intent, Bundle options, int userId) {
6130 return ActivityTaskManagerService.this.startActivityAsUser(
6131 caller, callerPacakge, intent,
6132 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6133 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6134 false /*validateIncomingUser*/);
6135 }
6136
6137 @Override
lumark588a3e82018-07-20 18:53:54 +08006138 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006139 synchronized (mGlobalLock) {
6140
6141 // We might change the visibilities here, so prepare an empty app transition which
6142 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006143 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006144 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006145 if (activityDisplay == null) {
6146 return;
6147 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006148 final DisplayContent dc = activityDisplay.mDisplayContent;
6149 final boolean wasTransitionSet =
6150 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006151 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006152 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006154 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155
6156 // If there was a transition set already we don't want to interfere with it as we
6157 // might be starting it too early.
6158 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006159 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 }
6161 }
6162 if (callback != null) {
6163 callback.run();
6164 }
6165 }
6166
6167 @Override
6168 public void notifyKeyguardTrustedChanged() {
6169 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006170 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006171 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 }
6173 }
6174 }
6175
6176 /**
6177 * Called after virtual display Id is updated by
6178 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6179 * {@param vrVr2dDisplayId}.
6180 */
6181 @Override
6182 public void setVr2dDisplayId(int vr2dDisplayId) {
6183 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6184 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006185 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187 }
6188
6189 @Override
6190 public void setFocusedActivity(IBinder token) {
6191 synchronized (mGlobalLock) {
6192 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6193 if (r == null) {
6194 throw new IllegalArgumentException(
6195 "setFocusedActivity: No activity record matching token=" + token);
6196 }
Louis Chang19443452018-10-09 12:10:21 +08006197 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006198 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006199 }
6200 }
6201 }
6202
6203 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006205 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
6207
6208 @Override
6209 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006210 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212
6213 @Override
6214 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006215 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 }
6217
6218 @Override
6219 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6220 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6221 }
6222
6223 @Override
6224 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006225 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006227
6228 @Override
6229 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6230 synchronized (mGlobalLock) {
6231 mActiveVoiceInteractionServiceComponent = component;
6232 }
6233 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006234
6235 @Override
6236 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6237 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6238 return;
6239 }
6240 synchronized (mGlobalLock) {
6241 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6242 if (types == null) {
6243 if (uid < 0) {
6244 return;
6245 }
6246 types = new ArrayMap<>();
6247 mAllowAppSwitchUids.put(userId, types);
6248 }
6249 if (uid < 0) {
6250 types.remove(type);
6251 } else {
6252 types.put(type, uid);
6253 }
6254 }
6255 }
6256
6257 @Override
6258 public void onUserStopped(int userId) {
6259 synchronized (mGlobalLock) {
6260 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6261 mAllowAppSwitchUids.remove(userId);
6262 }
6263 }
6264
6265 @Override
6266 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6267 synchronized (mGlobalLock) {
6268 return ActivityTaskManagerService.this.isGetTasksAllowed(
6269 caller, callingPid, callingUid);
6270 }
6271 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006272
Riddle Hsua0536432019-02-16 00:38:59 +08006273 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006274 @Override
6275 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006277 mProcessNames.put(proc.mName, proc.mUid, proc);
6278 }
6279 }
6280
Riddle Hsua0536432019-02-16 00:38:59 +08006281 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006282 @Override
6283 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006284 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006285 mProcessNames.remove(name, uid);
6286 }
6287 }
6288
Riddle Hsua0536432019-02-16 00:38:59 +08006289 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006290 @Override
6291 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006292 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006293 if (proc == mHomeProcess) {
6294 mHomeProcess = null;
6295 }
6296 if (proc == mPreviousProcess) {
6297 mPreviousProcess = null;
6298 }
6299 }
6300 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006301
Riddle Hsua0536432019-02-16 00:38:59 +08006302 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006303 @Override
6304 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 return mTopProcessState;
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006311 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006312 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 return proc == mHeavyWeightProcess;
6315 }
6316 }
6317
Riddle Hsua0536432019-02-16 00:38:59 +08006318 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006319 @Override
6320 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006321 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006322 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6323 }
6324 }
6325
6326 @Override
6327 public void finishHeavyWeightApp() {
6328 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006329 if (mHeavyWeightProcess != null) {
6330 mHeavyWeightProcess.finishActivities();
6331 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006332 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6333 mHeavyWeightProcess);
6334 }
6335 }
6336
Riddle Hsua0536432019-02-16 00:38:59 +08006337 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006338 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006339 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006340 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006341 return isSleepingLocked();
6342 }
6343 }
6344
6345 @Override
6346 public boolean isShuttingDown() {
6347 synchronized (mGlobalLock) {
6348 return mShuttingDown;
6349 }
6350 }
6351
6352 @Override
6353 public boolean shuttingDown(boolean booted, int timeout) {
6354 synchronized (mGlobalLock) {
6355 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006356 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006357 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006358 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006359 return mStackSupervisor.shutdownLocked(timeout);
6360 }
6361 }
6362
6363 @Override
6364 public void enableScreenAfterBoot(boolean booted) {
6365 synchronized (mGlobalLock) {
6366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6367 SystemClock.uptimeMillis());
6368 mWindowManager.enableScreenAfterBoot();
6369 updateEventDispatchingLocked(booted);
6370 }
6371 }
6372
6373 @Override
6374 public boolean showStrictModeViolationDialog() {
6375 synchronized (mGlobalLock) {
6376 return mShowDialogs && !mSleeping && !mShuttingDown;
6377 }
6378 }
6379
6380 @Override
6381 public void showSystemReadyErrorDialogsIfNeeded() {
6382 synchronized (mGlobalLock) {
6383 try {
6384 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6385 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6386 + " data partition or your device will be unstable.");
6387 mUiHandler.post(() -> {
6388 if (mShowDialogs) {
6389 AlertDialog d = new BaseErrorDialog(mUiContext);
6390 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6391 d.setCancelable(false);
6392 d.setTitle(mUiContext.getText(R.string.android_system_label));
6393 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6394 d.setButton(DialogInterface.BUTTON_POSITIVE,
6395 mUiContext.getText(R.string.ok),
6396 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6397 d.show();
6398 }
6399 });
6400 }
6401 } catch (RemoteException e) {
6402 }
6403
6404 if (!Build.isBuildConsistent()) {
6405 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6406 mUiHandler.post(() -> {
6407 if (mShowDialogs) {
6408 AlertDialog d = new BaseErrorDialog(mUiContext);
6409 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6410 d.setCancelable(false);
6411 d.setTitle(mUiContext.getText(R.string.android_system_label));
6412 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6413 d.setButton(DialogInterface.BUTTON_POSITIVE,
6414 mUiContext.getText(R.string.ok),
6415 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6416 d.show();
6417 }
6418 });
6419 }
6420 }
6421 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006422
6423 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006424 public void onProcessMapped(int pid, WindowProcessController proc) {
6425 synchronized (mGlobalLock) {
6426 mPidMap.put(pid, proc);
6427 }
6428 }
6429
6430 @Override
6431 public void onProcessUnMapped(int pid) {
6432 synchronized (mGlobalLock) {
6433 mPidMap.remove(pid);
6434 }
6435 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006436
6437 @Override
6438 public void onPackageDataCleared(String name) {
6439 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006440 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006441 mAppWarnings.onPackageDataCleared(name);
6442 }
6443 }
6444
6445 @Override
6446 public void onPackageUninstalled(String name) {
6447 synchronized (mGlobalLock) {
6448 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006449 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006450 }
6451 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006452
6453 @Override
6454 public void onPackageAdded(String name, boolean replacing) {
6455 synchronized (mGlobalLock) {
6456 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6457 }
6458 }
6459
6460 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006461 public void onPackageReplaced(ApplicationInfo aInfo) {
6462 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006463 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006464 }
6465 }
6466
6467 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006468 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6469 synchronized (mGlobalLock) {
6470 return compatibilityInfoForPackageLocked(ai);
6471 }
6472 }
6473
Yunfan Chen75157d72018-07-27 14:47:21 +09006474 /**
6475 * Set the corresponding display information for the process global configuration. To be
6476 * called when we need to show IME on a different display.
6477 *
6478 * @param pid The process id associated with the IME window.
6479 * @param displayId The ID of the display showing the IME.
6480 */
6481 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006482 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006483 // Don't update process-level configuration for Multi-Client IME process since other
6484 // IMEs on other displays will also receive this configuration change due to IME
6485 // services use the same application config/context.
6486 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006487
Yunfan Chen75157d72018-07-27 14:47:21 +09006488 if (pid == MY_PID || pid < 0) {
6489 if (DEBUG_CONFIGURATION) {
6490 Slog.w(TAG,
6491 "Trying to update display configuration for system/invalid process.");
6492 }
6493 return;
6494 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006495 synchronized (mGlobalLock) {
6496 final ActivityDisplay activityDisplay =
6497 mRootActivityContainer.getActivityDisplay(displayId);
6498 if (activityDisplay == null) {
6499 // Call might come when display is not yet added or has been removed.
6500 if (DEBUG_CONFIGURATION) {
6501 Slog.w(TAG, "Trying to update display configuration for non-existing "
6502 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006503 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006504 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006505 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006506 final WindowProcessController process = mPidMap.get(pid);
6507 if (process == null) {
6508 if (DEBUG_CONFIGURATION) {
6509 Slog.w(TAG, "Trying to update display configuration for invalid "
6510 + "process, pid=" + pid);
6511 }
6512 return;
6513 }
6514 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6515 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006516 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006517
6518 @Override
6519 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6520 int requestCode, int resultCode, Intent data) {
6521 synchronized (mGlobalLock) {
6522 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006523 if (r != null && r.getActivityStack() != null) {
6524 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6525 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006526 }
6527 }
6528 }
6529
6530 @Override
6531 public void clearPendingResultForActivity(IBinder activityToken,
6532 WeakReference<PendingIntentRecord> pir) {
6533 synchronized (mGlobalLock) {
6534 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6535 if (r != null && r.pendingResults != null) {
6536 r.pendingResults.remove(pir);
6537 }
6538 }
6539 }
6540
6541 @Override
6542 public IIntentSender getIntentSender(int type, String packageName,
6543 int callingUid, int userId, IBinder token, String resultWho,
6544 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6545 Bundle bOptions) {
6546 synchronized (mGlobalLock) {
6547 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6548 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6549 }
6550 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006551
6552 @Override
6553 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6554 synchronized (mGlobalLock) {
6555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6556 if (r == null) {
6557 return null;
6558 }
6559 if (r.mServiceConnectionsHolder == null) {
6560 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6561 ActivityTaskManagerService.this, r);
6562 }
6563
6564 return r.mServiceConnectionsHolder;
6565 }
6566 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006567
6568 @Override
6569 public Intent getHomeIntent() {
6570 synchronized (mGlobalLock) {
6571 return ActivityTaskManagerService.this.getHomeIntent();
6572 }
6573 }
6574
6575 @Override
6576 public boolean startHomeActivity(int userId, String reason) {
6577 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006578 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006579 }
6580 }
6581
6582 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006583 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006584 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006585 synchronized (mGlobalLock) {
6586 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006587 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006588 }
Chilun8b1f1be2019-03-13 17:14:36 +08006589 }
6590
6591 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006592 public boolean startHomeOnAllDisplays(int userId, String reason) {
6593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006594 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006595 }
6596 }
6597
Riddle Hsua0536432019-02-16 00:38:59 +08006598 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006599 @Override
6600 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006601 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006602 if (mFactoryTest == FACTORY_TEST_OFF) {
6603 return false;
6604 }
6605 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6606 && wpc.mName.equals(mTopComponent.getPackageName())) {
6607 return true;
6608 }
6609 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6610 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6611 }
6612 }
6613
6614 @Override
6615 public void updateTopComponentForFactoryTest() {
6616 synchronized (mGlobalLock) {
6617 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6618 return;
6619 }
6620 final ResolveInfo ri = mContext.getPackageManager()
6621 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6622 final CharSequence errorMsg;
6623 if (ri != null) {
6624 final ActivityInfo ai = ri.activityInfo;
6625 final ApplicationInfo app = ai.applicationInfo;
6626 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6627 mTopAction = Intent.ACTION_FACTORY_TEST;
6628 mTopData = null;
6629 mTopComponent = new ComponentName(app.packageName, ai.name);
6630 errorMsg = null;
6631 } else {
6632 errorMsg = mContext.getResources().getText(
6633 com.android.internal.R.string.factorytest_not_system);
6634 }
6635 } else {
6636 errorMsg = mContext.getResources().getText(
6637 com.android.internal.R.string.factorytest_no_action);
6638 }
6639 if (errorMsg == null) {
6640 return;
6641 }
6642
6643 mTopAction = null;
6644 mTopData = null;
6645 mTopComponent = null;
6646 mUiHandler.post(() -> {
6647 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6648 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006649 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006650 });
6651 }
6652 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006653
Riddle Hsua0536432019-02-16 00:38:59 +08006654 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006655 @Override
6656 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6657 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006658 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006659 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006660 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006661
6662 wpc.clearRecentTasks();
6663 wpc.clearActivities();
6664
6665 if (wpc.isInstrumenting()) {
6666 finishInstrumentationCallback.run();
6667 }
6668
Jorim Jaggid0752812018-10-16 16:07:20 +02006669 if (!restarting && hasVisibleActivities) {
6670 mWindowManager.deferSurfaceLayout();
6671 try {
6672 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6673 // If there was nothing to resume, and we are not already restarting
6674 // this process, but there is a visible activity that is hosted by the
6675 // process...then make sure all visible activities are running, taking
6676 // care of restarting this process.
6677 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6678 !PRESERVE_WINDOWS);
6679 }
6680 } finally {
6681 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006682 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 }
6684 }
6685 }
6686
6687 @Override
6688 public void closeSystemDialogs(String reason) {
6689 enforceNotIsolatedCaller("closeSystemDialogs");
6690
6691 final int pid = Binder.getCallingPid();
6692 final int uid = Binder.getCallingUid();
6693 final long origId = Binder.clearCallingIdentity();
6694 try {
6695 synchronized (mGlobalLock) {
6696 // Only allow this from foreground processes, so that background
6697 // applications can't abuse it to prevent system UI from being shown.
6698 if (uid >= FIRST_APPLICATION_UID) {
6699 final WindowProcessController proc = mPidMap.get(pid);
6700 if (!proc.isPerceptible()) {
6701 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6702 + " from background process " + proc);
6703 return;
6704 }
6705 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 mWindowManager.closeSystemDialogs(reason);
6707
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006710 // Call into AM outside the synchronized block.
6711 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712 } finally {
6713 Binder.restoreCallingIdentity(origId);
6714 }
6715 }
6716
6717 @Override
6718 public void cleanupDisabledPackageComponents(
6719 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6720 synchronized (mGlobalLock) {
6721 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006722 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006724 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006725 mStackSupervisor.scheduleIdleLocked();
6726 }
6727
6728 // Clean-up disabled tasks
6729 getRecentTasks().cleanupDisabledPackageTasksLocked(
6730 packageName, disabledClasses, userId);
6731 }
6732 }
6733
6734 @Override
6735 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6736 int userId) {
6737 synchronized (mGlobalLock) {
6738
6739 boolean didSomething =
6740 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006741 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 null, doit, evenPersistent, userId);
6743 return didSomething;
6744 }
6745 }
6746
6747 @Override
6748 public void resumeTopActivities(boolean scheduleIdle) {
6749 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006750 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 if (scheduleIdle) {
6752 mStackSupervisor.scheduleIdleLocked();
6753 }
6754 }
6755 }
6756
Riddle Hsua0536432019-02-16 00:38:59 +08006757 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 @Override
6759 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006760 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6762 }
6763 }
6764
Riddle Hsua0536432019-02-16 00:38:59 +08006765 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766 @Override
6767 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006768 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006769 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 }
6771 }
6772
6773 @Override
6774 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6775 try {
6776 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6777 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6778 }
6779 } catch (RemoteException ex) {
6780 throw new SecurityException("Fail to check is caller a privileged app", ex);
6781 }
6782
6783 synchronized (mGlobalLock) {
6784 final long ident = Binder.clearCallingIdentity();
6785 try {
6786 if (mAmInternal.shouldConfirmCredentials(userId)) {
6787 if (mKeyguardController.isKeyguardLocked()) {
6788 // Showing launcher to avoid user entering credential twice.
6789 startHomeActivity(currentUserId, "notifyLockedProfile");
6790 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006791 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 }
6793 } finally {
6794 Binder.restoreCallingIdentity(ident);
6795 }
6796 }
6797 }
6798
6799 @Override
6800 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6801 mAmInternal.enforceCallingPermission(
6802 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6803
6804 synchronized (mGlobalLock) {
6805 final long ident = Binder.clearCallingIdentity();
6806 try {
6807 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6808 FLAG_ACTIVITY_TASK_ON_HOME);
6809 ActivityOptions activityOptions = options != null
6810 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006811 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006812 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006813 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006814 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006815 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6817 UserHandle.CURRENT);
6818 } finally {
6819 Binder.restoreCallingIdentity(ident);
6820 }
6821 }
6822 }
6823
6824 @Override
6825 public void writeActivitiesToProto(ProtoOutputStream proto) {
6826 synchronized (mGlobalLock) {
6827 // The output proto of "activity --proto activities"
6828 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006829 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006830 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6831 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 }
6833 }
6834
6835 @Override
6836 public void saveANRState(String reason) {
6837 synchronized (mGlobalLock) {
6838 final StringWriter sw = new StringWriter();
6839 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6840 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6841 if (reason != null) {
6842 pw.println(" Reason: " + reason);
6843 }
6844 pw.println();
6845 getActivityStartController().dump(pw, " ", null);
6846 pw.println();
6847 pw.println("-------------------------------------------------------------------------------");
6848 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6849 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6850 "" /* header */);
6851 pw.println();
6852 pw.close();
6853
6854 mLastANRState = sw.toString();
6855 }
6856 }
6857
6858 @Override
6859 public void clearSavedANRState() {
6860 synchronized (mGlobalLock) {
6861 mLastANRState = null;
6862 }
6863 }
6864
6865 @Override
6866 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6867 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6868 synchronized (mGlobalLock) {
6869 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6870 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6871 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6872 dumpLastANRLocked(pw);
6873 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6874 dumpLastANRTracesLocked(pw);
6875 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6876 dumpActivityStarterLocked(pw, dumpPackage);
6877 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6878 dumpActivityContainersLocked(pw);
6879 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6880 if (getRecentTasks() != null) {
6881 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6882 }
6883 }
6884 }
6885 }
6886
6887 @Override
6888 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6889 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6890 int wakefulness) {
6891 synchronized (mGlobalLock) {
6892 if (mHomeProcess != null && (dumpPackage == null
6893 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6894 if (needSep) {
6895 pw.println();
6896 needSep = false;
6897 }
6898 pw.println(" mHomeProcess: " + mHomeProcess);
6899 }
6900 if (mPreviousProcess != null && (dumpPackage == null
6901 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6902 if (needSep) {
6903 pw.println();
6904 needSep = false;
6905 }
6906 pw.println(" mPreviousProcess: " + mPreviousProcess);
6907 }
6908 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6909 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6910 StringBuilder sb = new StringBuilder(128);
6911 sb.append(" mPreviousProcessVisibleTime: ");
6912 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6913 pw.println(sb);
6914 }
6915 if (mHeavyWeightProcess != null && (dumpPackage == null
6916 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6917 if (needSep) {
6918 pw.println();
6919 needSep = false;
6920 }
6921 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6922 }
6923 if (dumpPackage == null) {
6924 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006925 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006926 }
6927 if (dumpAll) {
6928 if (dumpPackage == null) {
6929 pw.println(" mConfigWillChange: "
6930 + getTopDisplayFocusedStack().mConfigWillChange);
6931 }
6932 if (mCompatModePackages.getPackages().size() > 0) {
6933 boolean printed = false;
6934 for (Map.Entry<String, Integer> entry
6935 : mCompatModePackages.getPackages().entrySet()) {
6936 String pkg = entry.getKey();
6937 int mode = entry.getValue();
6938 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6939 continue;
6940 }
6941 if (!printed) {
6942 pw.println(" mScreenCompatPackages:");
6943 printed = true;
6944 }
6945 pw.println(" " + pkg + ": " + mode);
6946 }
6947 }
6948 }
6949
6950 if (dumpPackage == null) {
6951 pw.println(" mWakefulness="
6952 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006953 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 if (mRunningVoice != null) {
6955 pw.println(" mRunningVoice=" + mRunningVoice);
6956 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6957 }
6958 pw.println(" mSleeping=" + mSleeping);
6959 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6960 pw.println(" mVrController=" + mVrController);
6961 }
6962 if (mCurAppTimeTracker != null) {
6963 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6964 }
6965 if (mAllowAppSwitchUids.size() > 0) {
6966 boolean printed = false;
6967 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6968 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6969 for (int j = 0; j < types.size(); j++) {
6970 if (dumpPackage == null ||
6971 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6972 if (needSep) {
6973 pw.println();
6974 needSep = false;
6975 }
6976 if (!printed) {
6977 pw.println(" mAllowAppSwitchUids:");
6978 printed = true;
6979 }
6980 pw.print(" User ");
6981 pw.print(mAllowAppSwitchUids.keyAt(i));
6982 pw.print(": Type ");
6983 pw.print(types.keyAt(j));
6984 pw.print(" = ");
6985 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6986 pw.println();
6987 }
6988 }
6989 }
6990 }
6991 if (dumpPackage == null) {
6992 if (mController != null) {
6993 pw.println(" mController=" + mController
6994 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6995 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006996 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6997 pw.println(" mLaunchingActivityWakeLock="
6998 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006999 }
7000
7001 return needSep;
7002 }
7003 }
7004
7005 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007006 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7007 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007008 synchronized (mGlobalLock) {
7009 if (dumpPackage == null) {
7010 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7011 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007012 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7013 if (mRunningVoice != null) {
7014 final long vrToken = proto.start(
7015 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7016 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7017 mRunningVoice.toString());
7018 mVoiceWakeLock.writeToProto(
7019 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7020 proto.end(vrToken);
7021 }
7022 mVrController.writeToProto(proto,
7023 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007024 if (mController != null) {
7025 final long token = proto.start(CONTROLLER);
7026 proto.write(CONTROLLER, mController.toString());
7027 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7028 proto.end(token);
7029 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007030 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7031 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7032 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034
7035 if (mHomeProcess != null && (dumpPackage == null
7036 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007037 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 }
7039
7040 if (mPreviousProcess != null && (dumpPackage == null
7041 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007042 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7044 }
7045
7046 if (mHeavyWeightProcess != null && (dumpPackage == null
7047 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007048 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007049 }
7050
7051 for (Map.Entry<String, Integer> entry
7052 : mCompatModePackages.getPackages().entrySet()) {
7053 String pkg = entry.getKey();
7054 int mode = entry.getValue();
7055 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7056 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7057 proto.write(PACKAGE, pkg);
7058 proto.write(MODE, mode);
7059 proto.end(compatToken);
7060 }
7061 }
7062
7063 if (mCurAppTimeTracker != null) {
7064 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7065 }
7066
7067 }
7068 }
7069
7070 @Override
7071 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7072 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7073 boolean dumpFocusedStackOnly) {
7074 synchronized (mGlobalLock) {
7075 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7076 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7077 }
7078 }
7079
7080 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007081 public void dumpForOom(PrintWriter pw) {
7082 synchronized (mGlobalLock) {
7083 pw.println(" mHomeProcess: " + mHomeProcess);
7084 pw.println(" mPreviousProcess: " + mPreviousProcess);
7085 if (mHeavyWeightProcess != null) {
7086 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7087 }
7088 }
7089 }
7090
7091 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 public boolean canGcNow() {
7093 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007094 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007095 }
7096 }
7097
Riddle Hsua0536432019-02-16 00:38:59 +08007098 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 @Override
7100 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007101 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007102 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007103 return top != null ? top.app : null;
7104 }
7105 }
7106
Riddle Hsua0536432019-02-16 00:38:59 +08007107 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007108 @Override
7109 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007110 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007111 if (mRootActivityContainer != null) {
7112 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114 }
7115 }
7116
7117 @Override
7118 public void scheduleDestroyAllActivities(String reason) {
7119 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007120 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122 }
7123
7124 @Override
7125 public void removeUser(int userId) {
7126 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007127 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007128 }
7129 }
7130
7131 @Override
7132 public boolean switchUser(int userId, UserState userState) {
7133 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007134 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007135 }
7136 }
7137
7138 @Override
7139 public void onHandleAppCrash(WindowProcessController wpc) {
7140 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007141 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007142 }
7143 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007144
7145 @Override
7146 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7147 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007148 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007149 }
7150 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007151
Riddle Hsua0536432019-02-16 00:38:59 +08007152 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007153 @Override
7154 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007155 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007156 }
7157
Riddle Hsua0536432019-02-16 00:38:59 +08007158 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007159 @Override
7160 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007161 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007162 }
7163
Riddle Hsua0536432019-02-16 00:38:59 +08007164 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007165 @Override
7166 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007167 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007168 }
7169
Riddle Hsua0536432019-02-16 00:38:59 +08007170 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007171 @Override
7172 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007173 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007174 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007175
7176 @Override
7177 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007178 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007179 mPendingTempWhitelist.put(uid, tag);
7180 }
7181 }
7182
7183 @Override
7184 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007185 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007186 mPendingTempWhitelist.remove(uid);
7187 }
7188 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007189
7190 @Override
7191 public boolean handleAppCrashInActivityController(String processName, int pid,
7192 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7193 Runnable killCrashingAppCallback) {
7194 synchronized (mGlobalLock) {
7195 if (mController == null) {
7196 return false;
7197 }
7198
7199 try {
7200 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7201 stackTrace)) {
7202 killCrashingAppCallback.run();
7203 return true;
7204 }
7205 } catch (RemoteException e) {
7206 mController = null;
7207 Watchdog.getInstance().setActivityController(null);
7208 }
7209 return false;
7210 }
7211 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007212
7213 @Override
7214 public void removeRecentTasksByPackageName(String packageName, int userId) {
7215 synchronized (mGlobalLock) {
7216 mRecentTasks.removeTasksByPackageName(packageName, userId);
7217 }
7218 }
7219
7220 @Override
7221 public void cleanupRecentTasksForUser(int userId) {
7222 synchronized (mGlobalLock) {
7223 mRecentTasks.cleanupLocked(userId);
7224 }
7225 }
7226
7227 @Override
7228 public void loadRecentTasksForUser(int userId) {
7229 synchronized (mGlobalLock) {
7230 mRecentTasks.loadUserRecentsLocked(userId);
7231 }
7232 }
7233
7234 @Override
7235 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7236 synchronized (mGlobalLock) {
7237 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7238 }
7239 }
7240
7241 @Override
7242 public void flushRecentTasks() {
7243 mRecentTasks.flush();
7244 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007245
7246 @Override
7247 public WindowProcessController getHomeProcess() {
7248 synchronized (mGlobalLock) {
7249 return mHomeProcess;
7250 }
7251 }
7252
7253 @Override
7254 public WindowProcessController getPreviousProcess() {
7255 synchronized (mGlobalLock) {
7256 return mPreviousProcess;
7257 }
7258 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007259
7260 @Override
7261 public void clearLockedTasks(String reason) {
7262 synchronized (mGlobalLock) {
7263 getLockTaskController().clearLockedTasks(reason);
7264 }
7265 }
7266
7267 @Override
7268 public void updateUserConfiguration() {
7269 synchronized (mGlobalLock) {
7270 final Configuration configuration = new Configuration(getGlobalConfiguration());
7271 final int currentUserId = mAmInternal.getCurrentUserId();
7272 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7273 configuration, currentUserId, Settings.System.canWrite(mContext));
7274 updateConfigurationLocked(configuration, null /* starting */,
7275 false /* initLocale */, false /* persistent */, currentUserId,
7276 false /* deferResume */);
7277 }
7278 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007279
7280 @Override
7281 public boolean canShowErrorDialogs() {
7282 synchronized (mGlobalLock) {
7283 return mShowDialogs && !mSleeping && !mShuttingDown
7284 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7285 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7286 mAmInternal.getCurrentUserId())
7287 && !(UserManager.isDeviceInDemoMode(mContext)
7288 && mAmInternal.getCurrentUser().isDemo());
7289 }
7290 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007291
7292 @Override
7293 public void setProfileApp(String profileApp) {
7294 synchronized (mGlobalLock) {
7295 mProfileApp = profileApp;
7296 }
7297 }
7298
7299 @Override
7300 public void setProfileProc(WindowProcessController wpc) {
7301 synchronized (mGlobalLock) {
7302 mProfileProc = wpc;
7303 }
7304 }
7305
7306 @Override
7307 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7308 synchronized (mGlobalLock) {
7309 mProfilerInfo = profilerInfo;
7310 }
7311 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007312
7313 @Override
7314 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7315 synchronized (mGlobalLock) {
7316 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7317 }
7318 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007319
7320 @Override
7321 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7322 synchronized (mGlobalLock) {
7323 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7324 }
7325 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007326
7327 @Override
7328 public boolean isUidForeground(int uid) {
7329 synchronized (mGlobalLock) {
7330 return ActivityTaskManagerService.this.isUidForeground(uid);
7331 }
7332 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007333
7334 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007335 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007336 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007337 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007338 }
7339 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007340
7341 @Override
7342 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007343 // Translate package names into UIDs
7344 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007345 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007346 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7347 if (uid >= 0) {
7348 result.add(uid);
7349 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007350 }
7351 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007352 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007353 }
7354 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007355 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007356}